llvm_backend_proc.cpp 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411
  1. gb_internal LLVMValueRef lb_call_intrinsic(lbProcedure *p, const char *name, LLVMValueRef* args, unsigned arg_count, LLVMTypeRef* types, unsigned type_count) {
  2. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  4. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, type_count);
  5. LLVMTypeRef call_type = LLVMIntrinsicGetType(p->module->ctx, id, types, type_count);
  6. return LLVMBuildCall2(p->builder, call_type, ip, args, arg_count, "");
  7. }
  8. gb_internal void lb_mem_copy_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  9. dst = lb_emit_conv(p, dst, t_rawptr);
  10. src = lb_emit_conv(p, src, t_rawptr);
  11. len = lb_emit_conv(p, len, t_int);
  12. char const *name = "llvm.memmove";
  13. if (LLVMIsConstant(len.value)) {
  14. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  15. if (const_len <= 4*build_context.int_size) {
  16. name = "llvm.memmove.inline";
  17. }
  18. }
  19. LLVMTypeRef types[3] = {
  20. lb_type(p->module, t_rawptr),
  21. lb_type(p->module, t_rawptr),
  22. lb_type(p->module, t_int)
  23. };
  24. LLVMValueRef args[4] = {
  25. dst.value,
  26. src.value,
  27. len.value,
  28. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile)
  29. };
  30. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  31. }
  32. gb_internal void lb_mem_copy_non_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  33. dst = lb_emit_conv(p, dst, t_rawptr);
  34. src = lb_emit_conv(p, src, t_rawptr);
  35. len = lb_emit_conv(p, len, t_int);
  36. char const *name = "llvm.memcpy";
  37. if (LLVMIsConstant(len.value)) {
  38. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  39. if (const_len <= 4*build_context.int_size) {
  40. name = "llvm.memcpy.inline";
  41. }
  42. }
  43. LLVMTypeRef types[3] = {
  44. lb_type(p->module, t_rawptr),
  45. lb_type(p->module, t_rawptr),
  46. lb_type(p->module, t_int)
  47. };
  48. LLVMValueRef args[4] = {
  49. dst.value,
  50. src.value,
  51. len.value,
  52. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile) };
  53. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  54. }
  55. gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  56. GB_ASSERT(entity != nullptr);
  57. GB_ASSERT(entity->kind == Entity_Procedure);
  58. if (!entity->Procedure.is_foreign) {
  59. if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  60. GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false));
  61. }
  62. }
  63. String link_name = {};
  64. if (ignore_body) {
  65. lbModule *other_module = lb_module_of_entity(m->gen, entity);
  66. link_name = lb_get_entity_name(other_module, entity);
  67. } else {
  68. link_name = lb_get_entity_name(m, entity);
  69. }
  70. {
  71. StringHashKey key = string_hash_string(link_name);
  72. lbValue *found = string_map_get(&m->members, key);
  73. if (found) {
  74. lb_add_entity(m, entity, *found);
  75. return string_map_must_get(&m->procedures, key);
  76. }
  77. }
  78. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  79. p->module = m;
  80. entity->code_gen_module = m;
  81. entity->code_gen_procedure = p;
  82. p->entity = entity;
  83. p->name = link_name;
  84. DeclInfo *decl = entity->decl_info;
  85. ast_node(pl, ProcLit, decl->proc_lit);
  86. Type *pt = base_type(entity->type);
  87. GB_ASSERT(pt->kind == Type_Proc);
  88. p->type = entity->type;
  89. p->type_expr = decl->type_expr;
  90. p->body = pl->body;
  91. p->inlining = pl->inlining;
  92. p->is_foreign = entity->Procedure.is_foreign;
  93. p->is_export = entity->Procedure.is_export;
  94. p->is_entry_point = false;
  95. gbAllocator a = heap_allocator();
  96. p->children.allocator = a;
  97. p->defer_stmts.allocator = a;
  98. p->blocks.allocator = a;
  99. p->branch_blocks.allocator = a;
  100. p->context_stack.allocator = a;
  101. p->scope_stack.allocator = a;
  102. // map_init(&p->selector_values, 0);
  103. // map_init(&p->selector_addr, 0);
  104. // map_init(&p->tuple_fix_map, 0);
  105. if (p->is_foreign) {
  106. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  107. }
  108. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  109. {
  110. TEMPORARY_ALLOCATOR_GUARD();
  111. char *c_link_name = alloc_cstring(temporary_allocator(), p->name);
  112. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  113. }
  114. lb_ensure_abi_function_type(m, p);
  115. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  116. if (pt->Proc.diverging) {
  117. lb_add_attribute_to_proc(m, p->value, "noreturn");
  118. }
  119. if (pt->Proc.calling_convention == ProcCC_Naked) {
  120. lb_add_attribute_to_proc(m, p->value, "naked");
  121. }
  122. if (!entity->Procedure.is_foreign && build_context.disable_red_zone) {
  123. lb_add_attribute_to_proc(m, p->value, "noredzone");
  124. }
  125. switch (p->inlining) {
  126. case ProcInlining_inline:
  127. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  128. break;
  129. case ProcInlining_no_inline:
  130. lb_add_attribute_to_proc(m, p->value, "noinline");
  131. break;
  132. }
  133. switch (entity->Procedure.optimization_mode) {
  134. case ProcedureOptimizationMode_None:
  135. break;
  136. case ProcedureOptimizationMode_Minimal:
  137. lb_add_attribute_to_proc(m, p->value, "optnone");
  138. lb_add_attribute_to_proc(m, p->value, "noinline");
  139. break;
  140. case ProcedureOptimizationMode_Size:
  141. lb_add_attribute_to_proc(m, p->value, "optsize");
  142. break;
  143. case ProcedureOptimizationMode_Speed:
  144. // TODO(bill): handle this correctly
  145. lb_add_attribute_to_proc(m, p->value, "optsize");
  146. break;
  147. }
  148. if (!entity->Procedure.target_feature_disabled &&
  149. entity->Procedure.target_feature.len != 0) {
  150. auto features = split_by_comma(entity->Procedure.target_feature);
  151. for_array(i, features) {
  152. String feature = features[i];
  153. LLVMAttributeRef ref = LLVMCreateStringAttribute(
  154. m->ctx,
  155. cast(char const *)feature.text, cast(unsigned)feature.len,
  156. "", 0);
  157. LLVMAddAttributeAtIndex(p->value, LLVMAttributeIndex_FunctionIndex, ref);
  158. }
  159. }
  160. if (entity->flags & EntityFlag_Cold) {
  161. lb_add_attribute_to_proc(m, p->value, "cold");
  162. }
  163. if (p->is_export) {
  164. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  165. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  166. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  167. lb_set_wasm_export_attributes(p->value, p->name);
  168. } else if (!p->is_foreign) {
  169. if (USE_SEPARATE_MODULES) {
  170. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  171. } else {
  172. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  173. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  174. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  175. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  176. GB_ASSERT(entity->kind == Entity_Procedure);
  177. String link_name = entity->Procedure.link_name;
  178. if (entity->flags & EntityFlag_CustomLinkName &&
  179. link_name != "") {
  180. if (string_starts_with(link_name, str_lit("__"))) {
  181. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  182. } else {
  183. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  184. }
  185. }
  186. }
  187. }
  188. }
  189. lb_set_linkage_from_entity_flags(p->module, p->value, entity->flags);
  190. if (p->is_foreign) {
  191. lb_set_wasm_import_attributes(p->value, entity, p->name);
  192. }
  193. // NOTE(bill): offset==0 is the return value
  194. isize offset = 1;
  195. if (pt->Proc.return_by_pointer) {
  196. offset = 2;
  197. }
  198. isize parameter_index = 0;
  199. if (pt->Proc.param_count) {
  200. TypeTuple *params = &pt->Proc.params->Tuple;
  201. for (isize i = 0; i < pt->Proc.param_count; i++) {
  202. Entity *e = params->variables[i];
  203. if (e->kind != Entity_Variable) {
  204. continue;
  205. }
  206. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  207. continue;
  208. }
  209. if (e->flags&EntityFlag_NoAlias) {
  210. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  211. }
  212. parameter_index += 1;
  213. }
  214. }
  215. if (ignore_body) {
  216. p->body = nullptr;
  217. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  218. }
  219. if (m->debug_builder) { // Debug Information
  220. Type *bt = base_type(p->type);
  221. unsigned line = cast(unsigned)entity->token.pos.line;
  222. LLVMMetadataRef scope = nullptr;
  223. LLVMMetadataRef file = nullptr;
  224. LLVMMetadataRef type = nullptr;
  225. scope = p->module->debug_compile_unit;
  226. type = lb_debug_type_internal_proc(m, bt);
  227. Ast *ident = entity->identifier.load();
  228. if (entity->file != nullptr) {
  229. file = lb_get_llvm_metadata(m, entity->file);
  230. scope = file;
  231. } else if (ident != nullptr && ident->file_id != 0) {
  232. file = lb_get_llvm_metadata(m, ident->file());
  233. scope = file;
  234. } else if (entity->scope != nullptr) {
  235. file = lb_get_llvm_metadata(m, entity->scope->file);
  236. scope = file;
  237. }
  238. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  239. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  240. LLVMBool is_local_to_unit = false;
  241. LLVMBool is_definition = p->body != nullptr;
  242. unsigned scope_line = line;
  243. u32 flags = LLVMDIFlagStaticMember;
  244. LLVMBool is_optimized = false;
  245. if (bt->Proc.diverging) {
  246. flags |= LLVMDIFlagNoReturn;
  247. }
  248. if (p->body == nullptr) {
  249. flags |= LLVMDIFlagPrototyped;
  250. is_optimized = false;
  251. }
  252. if (p->body != nullptr) {
  253. // String debug_name = entity->token.string.text;
  254. String debug_name = p->name;
  255. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  256. cast(char const *)debug_name.text, debug_name.len,
  257. cast(char const *)p->name.text, p->name.len,
  258. file, line, type,
  259. is_local_to_unit, is_definition,
  260. scope_line, cast(LLVMDIFlags)flags, is_optimized
  261. );
  262. GB_ASSERT(p->debug_info != nullptr);
  263. LLVMSetSubprogram(p->value, p->debug_info);
  264. lb_set_llvm_metadata(m, p, p->debug_info);
  265. }
  266. }
  267. if (p->body && entity->pkg && ((entity->pkg->kind == Package_Normal) || (entity->pkg->kind == Package_Init))) {
  268. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  269. lb_add_attribute_to_proc(m, p->value, "sanitize_address");
  270. }
  271. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  272. lb_add_attribute_to_proc(m, p->value, "sanitize_memory");
  273. }
  274. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  275. lb_add_attribute_to_proc(m, p->value, "sanitize_thread");
  276. }
  277. }
  278. lbValue proc_value = {p->value, p->type};
  279. lb_add_entity(m, entity, proc_value);
  280. lb_add_member(m, p->name, proc_value);
  281. lb_add_procedure_value(m, p);
  282. return p;
  283. }
  284. gb_internal lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  285. {
  286. lbValue *found = string_map_get(&m->members, link_name);
  287. GB_ASSERT_MSG(found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name));
  288. }
  289. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  290. p->module = m;
  291. p->name = link_name;
  292. p->type = type;
  293. p->type_expr = nullptr;
  294. p->body = nullptr;
  295. p->tags = 0;
  296. p->inlining = ProcInlining_none;
  297. p->is_foreign = false;
  298. p->is_export = false;
  299. p->is_entry_point = false;
  300. gbAllocator a = permanent_allocator();
  301. p->children.allocator = a;
  302. p->defer_stmts.allocator = a;
  303. p->blocks.allocator = a;
  304. p->branch_blocks.allocator = a;
  305. p->context_stack.allocator = a;
  306. map_init(&p->tuple_fix_map, 0);
  307. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  308. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  309. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  310. Type *pt = p->type;
  311. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  312. if (!is_arch_wasm()) {
  313. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  314. }
  315. LLVMSetFunctionCallConv(p->value, cc_kind);
  316. lbValue proc_value = {p->value, p->type};
  317. lb_add_member(m, p->name, proc_value);
  318. lb_add_procedure_value(m, p);
  319. // NOTE(bill): offset==0 is the return value
  320. isize offset = 1;
  321. if (pt->Proc.return_by_pointer) {
  322. lb_add_proc_attribute_at_index(p, 1, "sret");
  323. lb_add_proc_attribute_at_index(p, 1, "noalias");
  324. offset = 2;
  325. }
  326. isize parameter_index = 0;
  327. if (pt->Proc.calling_convention == ProcCC_Odin) {
  328. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  329. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  330. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  331. }
  332. return p;
  333. }
  334. // gb_internal lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  335. // lbParamPasskind kind = lbParamPass_Value;
  336. // if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  337. // if (is_type_pointer(abi_type)) {
  338. // GB_ASSERT(e->kind == Entity_Variable);
  339. // Type *av = core_type(type_deref(abi_type));
  340. // if (are_types_identical(av, core_type(e->type))) {
  341. // kind = lbParamPass_Pointer;
  342. // if (e->flags&EntityFlag_Value) {
  343. // kind = lbParamPass_ConstRef;
  344. // }
  345. // } else {
  346. // kind = lbParamPass_BitCast;
  347. // }
  348. // } else if (is_type_integer(abi_type)) {
  349. // kind = lbParamPass_Integer;
  350. // } else if (abi_type == t_llvm_bool) {
  351. // kind = lbParamPass_Value;
  352. // } else if (is_type_boolean(abi_type)) {
  353. // kind = lbParamPass_Integer;
  354. // } else if (is_type_simd_vector(abi_type)) {
  355. // kind = lbParamPass_BitCast;
  356. // } else if (is_type_float(abi_type)) {
  357. // kind = lbParamPass_BitCast;
  358. // } else if (is_type_tuple(abi_type)) {
  359. // kind = lbParamPass_Tuple;
  360. // } else if (is_type_proc(abi_type)) {
  361. // kind = lbParamPass_Value;
  362. // } else {
  363. // GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  364. // }
  365. // }
  366. // if (kind_) *kind_ = kind;
  367. // lbValue res = {};
  368. // res.value = LLVMGetParam(p->value, cast(unsigned)index);
  369. // res.type = abi_type;
  370. // return res;
  371. // }
  372. gb_internal void lb_start_block(lbProcedure *p, lbBlock *b) {
  373. GB_ASSERT(b != nullptr);
  374. if (!b->appended) {
  375. b->appended = true;
  376. LLVMAppendExistingBasicBlock(p->value, b->block);
  377. }
  378. LLVMPositionBuilderAtEnd(p->builder, b->block);
  379. p->curr_block = b;
  380. }
  381. gb_internal void lb_set_debug_position_to_procedure_begin(lbProcedure *p) {
  382. if (p->debug_info == nullptr) {
  383. return;
  384. }
  385. TokenPos pos = {};
  386. if (p->body != nullptr) {
  387. pos = ast_token(p->body).pos;
  388. } else if (p->type_expr != nullptr) {
  389. pos = ast_token(p->type_expr).pos;
  390. } else if (p->entity != nullptr) {
  391. pos = p->entity->token.pos;
  392. }
  393. if (pos.file_id != 0) {
  394. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  395. }
  396. }
  397. gb_internal void lb_set_debug_position_to_procedure_end(lbProcedure *p) {
  398. if (p->debug_info == nullptr) {
  399. return;
  400. }
  401. TokenPos pos = {};
  402. if (p->body != nullptr) {
  403. pos = ast_end_token(p->body).pos;
  404. } else if (p->type_expr != nullptr) {
  405. pos = ast_end_token(p->type_expr).pos;
  406. } else if (p->entity != nullptr) {
  407. pos = p->entity->token.pos;
  408. }
  409. if (pos.file_id != 0) {
  410. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  411. }
  412. }
  413. gb_internal void lb_begin_procedure_body(lbProcedure *p) {
  414. DeclInfo *decl = decl_info_of_entity(p->entity);
  415. if (decl != nullptr) {
  416. for_array(i, decl->labels) {
  417. BlockLabel bl = decl->labels[i];
  418. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  419. array_add(&p->branch_blocks, bb);
  420. }
  421. }
  422. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  423. p->decl_block = lb_create_block(p, "decls", true);
  424. p->entry_block = lb_create_block(p, "entry", true);
  425. lb_start_block(p, p->entry_block);
  426. map_init(&p->direct_parameters);
  427. GB_ASSERT(p->type != nullptr);
  428. lb_ensure_abi_function_type(p->module, p);
  429. {
  430. lbFunctionType *ft = p->abi_function_type;
  431. unsigned param_offset = 0;
  432. lbValue return_ptr_value = {};
  433. if (ft->ret.kind == lbArg_Indirect) {
  434. // NOTE(bill): this must be parameter 0
  435. String name = str_lit("agg.result");
  436. if (ft->multiple_return_original_type &&
  437. p->type->Proc.has_named_results) {
  438. auto const &variables = p->type->Proc.results->Tuple.variables;
  439. Entity *e = variables[variables.count-1];
  440. if (!is_blank_ident(e->token)) {
  441. name = e->token.string;
  442. }
  443. }
  444. Type *return_ptr_type = reduce_tuple_to_single_type(p->type->Proc.results);
  445. bool split_returns = ft->multiple_return_original_type != nullptr;
  446. if (split_returns) {
  447. GB_ASSERT(is_type_tuple(return_ptr_type));
  448. auto const &variables = return_ptr_type->Tuple.variables;
  449. return_ptr_type = variables[variables.count-1]->type;
  450. }
  451. Type *ptr_type = alloc_type_pointer(return_ptr_type);
  452. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  453. e->flags |= EntityFlag_NoAlias;
  454. return_ptr_value.value = LLVMGetParam(p->value, 0);
  455. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  456. return_ptr_value.type = ptr_type;
  457. p->return_ptr = lb_addr(return_ptr_value);
  458. lb_add_entity(p->module, e, return_ptr_value);
  459. param_offset += 1;
  460. }
  461. if (p->type->Proc.params != nullptr) {
  462. TypeTuple *params = &p->type->Proc.params->Tuple;
  463. unsigned raw_input_parameters_count = LLVMCountParams(p->value);
  464. p->raw_input_parameters = array_make<LLVMValueRef>(permanent_allocator(), raw_input_parameters_count);
  465. LLVMGetParams(p->value, p->raw_input_parameters.data);
  466. unsigned param_index = 0;
  467. for_array(i, params->variables) {
  468. Entity *e = params->variables[i];
  469. if (e->kind != Entity_Variable) {
  470. continue;
  471. }
  472. lbArgType *arg_type = &ft->args[param_index];
  473. defer (param_index += 1);
  474. if (arg_type->kind == lbArg_Ignore) {
  475. continue;
  476. } else if (arg_type->kind == lbArg_Direct) {
  477. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  478. LLVMTypeRef param_type = lb_type(p->module, e->type);
  479. LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index);
  480. LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type);
  481. lbValue param = {};
  482. param.value = value;
  483. param.type = e->type;
  484. map_set(&p->direct_parameters, e, param);
  485. lbValue ptr = lb_address_from_load_or_generate_local(p, param);
  486. GB_ASSERT(LLVMIsAAllocaInst(ptr.value));
  487. lb_add_entity(p->module, e, ptr);
  488. lbBlock *block = p->decl_block;
  489. if (original_value != value) {
  490. block = p->curr_block;
  491. }
  492. LLVMValueRef debug_storage_value = value;
  493. if (original_value != value && LLVMIsALoadInst(value)) {
  494. debug_storage_value = LLVMGetOperand(value, 0);
  495. }
  496. lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind);
  497. }
  498. } else if (arg_type->kind == lbArg_Indirect) {
  499. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  500. lbValue ptr = {};
  501. ptr.value = LLVMGetParam(p->value, param_offset+param_index);
  502. ptr.type = alloc_type_pointer(e->type);
  503. lb_add_entity(p->module, e, ptr);
  504. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind);
  505. }
  506. }
  507. }
  508. }
  509. if (p->type->Proc.has_named_results) {
  510. GB_ASSERT(p->type->Proc.result_count > 0);
  511. TypeTuple *results = &p->type->Proc.results->Tuple;
  512. for_array(i, results->variables) {
  513. Entity *e = results->variables[i];
  514. GB_ASSERT(e->kind == Entity_Variable);
  515. if (e->token.string != "") {
  516. GB_ASSERT(!is_blank_ident(e->token));
  517. lbAddr res = {};
  518. if (p->entity && p->entity->decl_info &&
  519. p->entity->decl_info->defer_use_checked &&
  520. p->entity->decl_info->defer_used == 0) {
  521. // NOTE(bill): this is a bodge to get around the issue of the problem BELOW
  522. // We check to see if we ever use a defer statement ever within a procedure and if it
  523. // if it never happens, see if you can possibly do take the return value pointer
  524. //
  525. // NOTE(bill): this could be buggy in that I have missed a case where `defer` was used
  526. //
  527. // TODO(bill): This could be optimized to check to see where a `defer` only uses
  528. // the variable in question
  529. bool has_return_ptr = p->return_ptr.addr.value != nullptr;
  530. lbValue ptr = {};
  531. if (ft->multiple_return_original_type != nullptr) {
  532. isize the_offset = -1;
  533. if (i+1 < results->variables.count) {
  534. the_offset = cast(isize)param_offset + ft->original_arg_count + i;
  535. } else if (has_return_ptr) {
  536. GB_ASSERT(i+1 == results->variables.count);
  537. the_offset = 0;
  538. }
  539. if (the_offset >= 0) {
  540. lbValue ptr = {};
  541. ptr.value = LLVMGetParam(p->value, cast(unsigned)the_offset);
  542. ptr.type = alloc_type_pointer(e->type);
  543. }
  544. } else if (has_return_ptr) {
  545. lbValue ptr = p->return_ptr.addr;
  546. if (results->variables.count > 1) {
  547. ptr = lb_emit_tuple_ep(p, ptr, cast(i32)i);
  548. }
  549. GB_ASSERT(is_type_pointer(ptr.type));
  550. GB_ASSERT(are_types_identical(type_deref(ptr.type), e->type));
  551. }
  552. if (ptr.value != nullptr) {
  553. lb_add_entity(p->module, e, ptr);
  554. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  555. // NOTE(bill): no need to zero on the callee side as it is zeroed on the caller side
  556. res = lb_addr(ptr);
  557. }
  558. }
  559. if (res.addr.type == nullptr) {
  560. // NOTE(bill): Don't even bother trying to optimize this with the return ptr value
  561. // This will violate the defer rules if you do:
  562. // foo :: proc() -> (x, y: T) {
  563. // defer x = ... // defer is executed after the `defer`
  564. // return // the values returned should be zeroed
  565. // }
  566. // NOTE(bill): REALLY, don't even bother.
  567. //
  568. // IMPORTANT NOTE(bill): REALLY, don't even bother!!!!!!
  569. res = lb_add_local(p, e->type, e);
  570. }
  571. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  572. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  573. lb_addr_store(p, res, c);
  574. }
  575. }
  576. }
  577. }
  578. }
  579. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  580. lb_push_context_onto_stack_from_implicit_parameter(p);
  581. }
  582. lb_set_debug_position_to_procedure_begin(p);
  583. if (p->debug_info != nullptr) {
  584. if (p->context_stack.count != 0) {
  585. p->curr_block = p->decl_block;
  586. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  587. }
  588. }
  589. lb_start_block(p, p->entry_block);
  590. }
  591. gb_internal void lb_end_procedure_body(lbProcedure *p) {
  592. lb_set_debug_position_to_procedure_begin(p);
  593. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  594. LLVMBuildBr(p->builder, p->entry_block->block);
  595. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  596. LLVMValueRef instr = nullptr;
  597. // Make sure there is a "ret void" at the end of a procedure with no return type
  598. if (p->type->Proc.result_count == 0) {
  599. instr = LLVMGetLastInstruction(p->curr_block->block);
  600. if (!lb_is_instr_terminating(instr)) {
  601. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  602. lb_set_debug_position_to_procedure_end(p);
  603. LLVMBuildRetVoid(p->builder);
  604. }
  605. }
  606. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  607. LLVMBasicBlockRef block = nullptr;
  608. // Make sure every block terminates, and if not, make it unreachable
  609. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  610. instr = LLVMGetLastInstruction(block);
  611. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  612. LLVMPositionBuilderAtEnd(p->builder, block);
  613. LLVMBuildUnreachable(p->builder);
  614. }
  615. }
  616. p->curr_block = nullptr;
  617. p->state_flags = 0;
  618. }
  619. gb_internal void lb_end_procedure(lbProcedure *p) {
  620. LLVMDisposeBuilder(p->builder);
  621. }
  622. gb_internal void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  623. GB_ASSERT(pd->body != nullptr);
  624. lbModule *m = p->module;
  625. auto *min_dep_set = &m->info->minimum_dependency_set;
  626. if (ptr_set_exists(min_dep_set, e) == false) {
  627. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  628. return;
  629. }
  630. // NOTE(bill): Generate a new name
  631. // parent.name-guid
  632. String original_name = e->token.string;
  633. String pd_name = original_name;
  634. if (e->Procedure.link_name.len > 0) {
  635. pd_name = e->Procedure.link_name;
  636. }
  637. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  638. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  639. i32 guid = cast(i32)p->children.count;
  640. name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  641. String name = make_string(cast(u8 *)name_text, name_len-1);
  642. e->Procedure.link_name = name;
  643. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  644. e->code_gen_procedure = nested_proc;
  645. lbValue value = {};
  646. value.value = nested_proc->value;
  647. value.type = nested_proc->type;
  648. lb_add_entity(m, e, value);
  649. array_add(&p->children, nested_proc);
  650. array_add(&m->procedures_to_generate, nested_proc);
  651. }
  652. gb_internal Array<lbValue> lb_value_to_array(lbProcedure *p, gbAllocator const &allocator, lbValue value) {
  653. Array<lbValue> array = {};
  654. Type *t = base_type(value.type);
  655. if (t == nullptr) {
  656. // Do nothing
  657. } else if (is_type_tuple(t)) {
  658. array = array_make<lbValue>(allocator, 0, t->Tuple.variables.count);
  659. lb_append_tuple_values(p, &array, value);
  660. } else {
  661. array = array_make<lbValue>(allocator, 1);
  662. array[0] = value;
  663. }
  664. return array;
  665. }
  666. gb_internal lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  667. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  668. unsigned arg_count = cast(unsigned)processed_args.count;
  669. if (return_ptr.value != nullptr) {
  670. arg_count += 1;
  671. }
  672. if (context_ptr.addr.value != nullptr) {
  673. arg_count += 1;
  674. }
  675. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  676. isize arg_index = 0;
  677. if (return_ptr.value != nullptr) {
  678. args[arg_index++] = return_ptr.value;
  679. }
  680. for_array(i, processed_args) {
  681. lbValue arg = processed_args[i];
  682. if (is_type_proc(arg.type)) {
  683. arg.value = LLVMBuildPointerCast(p->builder, arg.value, lb_type(p->module, arg.type), "");
  684. }
  685. args[arg_index++] = arg.value;
  686. }
  687. if (context_ptr.addr.value != nullptr) {
  688. LLVMValueRef cp = context_ptr.addr.value;
  689. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  690. args[arg_index++] = cp;
  691. }
  692. GB_ASSERT(arg_index == arg_count);
  693. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  694. GB_ASSERT(curr_block != p->decl_block->block);
  695. {
  696. Type *proc_type = base_type(value.type);
  697. GB_ASSERT(proc_type->kind == Type_Proc);
  698. LLVMTypeRef fnp = lb_type_internal_for_procedures_raw(p->module, proc_type);
  699. LLVMTypeRef ftp = LLVMPointerType(fnp, 0);
  700. LLVMValueRef fn = value.value;
  701. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  702. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  703. }
  704. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  705. lbFunctionType *ft = map_must_get(&p->module->function_type_map, base_type(value.type));
  706. {
  707. unsigned param_count = LLVMCountParamTypes(fnp);
  708. GB_ASSERT(arg_count >= param_count);
  709. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  710. LLVMGetParamTypes(fnp, param_types);
  711. for (unsigned i = 0; i < param_count; i++) {
  712. LLVMTypeRef param_type = param_types[i];
  713. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  714. if (LB_USE_NEW_PASS_SYSTEM &&
  715. arg_type != param_type) {
  716. LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  717. LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  718. if (arg_kind == param_kind &&
  719. arg_kind == LLVMPointerTypeKind) {
  720. // NOTE(bill): LLVM's newer `ptr` only type system seems to fail at times
  721. // I don't know why...
  722. args[i] = LLVMBuildPointerCast(p->builder, args[i], param_type, "");
  723. gb_printf_err("%s\n", LLVMPrintValueToString(args[i]));
  724. arg_type = param_type;
  725. continue;
  726. }
  727. }
  728. GB_ASSERT_MSG(
  729. arg_type == param_type,
  730. "Parameter types do not match: %s != %s, argument: %s\n\t%s",
  731. LLVMPrintTypeToString(arg_type),
  732. LLVMPrintTypeToString(param_type),
  733. LLVMPrintValueToString(args[i]),
  734. LLVMPrintTypeToString(fnp)
  735. );
  736. }
  737. }
  738. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  739. LLVMAttributeIndex param_offset = LLVMAttributeIndex_FirstArgIndex;
  740. if (return_ptr.value != nullptr) {
  741. param_offset += 1;
  742. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  743. }
  744. for_array(i, ft->args) {
  745. LLVMAttributeRef attribute = ft->args[i].attribute;
  746. if (attribute != nullptr) {
  747. LLVMAddCallSiteAttribute(ret, param_offset + cast(LLVMAttributeIndex)i, attribute);
  748. }
  749. }
  750. switch (inlining) {
  751. case ProcInlining_none:
  752. break;
  753. case ProcInlining_inline:
  754. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  755. break;
  756. case ProcInlining_no_inline:
  757. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  758. break;
  759. }
  760. lbValue res = {};
  761. res.value = ret;
  762. res.type = abi_rt;
  763. return res;
  764. }
  765. }
  766. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  767. AstPackage *pkg = m->info->runtime_package;
  768. Entity *e = scope_lookup_current(pkg->scope, name);
  769. return lb_find_procedure_value_from_entity(m, e);
  770. }
  771. gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  772. String name = make_string_c(c_name);
  773. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  774. return lb_emit_call(p, proc, args);
  775. }
  776. gb_internal lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  777. lbValue res = {};
  778. Type *t = val.type;
  779. if (is_type_complex(t)) {
  780. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  781. lbValue real = lb_emit_struct_ev(p, val, 0);
  782. lbValue imag = lb_emit_struct_ev(p, val, 1);
  783. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  784. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  785. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  786. } else if (is_type_quaternion(t)) {
  787. // @QuaternionLayout
  788. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  789. lbValue real = lb_emit_struct_ev(p, val, 3);
  790. lbValue imag = lb_emit_struct_ev(p, val, 0);
  791. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  792. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  793. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  794. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  795. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  796. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  797. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  798. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  799. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  800. } else if (is_type_array_like(t)) {
  801. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  802. Type *elem_type = base_array_type(t);
  803. i64 count = get_array_type_count(t);
  804. for (i64 i = 0; i < count; i++) {
  805. lbValue dst = lb_emit_array_epi(p, res, i);
  806. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  807. elem = lb_emit_conjugate(p, elem, elem_type);
  808. lb_emit_store(p, dst, elem);
  809. }
  810. } else if (is_type_matrix(t)) {
  811. Type *mt = base_type(t);
  812. GB_ASSERT(mt->kind == Type_Matrix);
  813. Type *elem_type = mt->Matrix.elem;
  814. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  815. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  816. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  817. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  818. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  819. elem = lb_emit_conjugate(p, elem, elem_type);
  820. lb_emit_store(p, dst, elem);
  821. }
  822. }
  823. }
  824. return lb_emit_load(p, res);
  825. }
  826. gb_internal lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining) {
  827. lbModule *m = p->module;
  828. Type *pt = base_type(value.type);
  829. GB_ASSERT(pt->kind == Type_Proc);
  830. Type *results = pt->Proc.results;
  831. lbAddr context_ptr = {};
  832. if (pt->Proc.calling_convention == ProcCC_Odin) {
  833. context_ptr = lb_find_or_generate_context_ptr(p);
  834. }
  835. defer (if (pt->Proc.diverging) {
  836. LLVMBuildUnreachable(p->builder);
  837. });
  838. bool is_c_vararg = pt->Proc.c_vararg;
  839. isize param_count = pt->Proc.param_count;
  840. if (is_c_vararg) {
  841. GB_ASSERT(param_count-1 <= args.count);
  842. param_count -= 1;
  843. } else {
  844. GB_ASSERT_MSG(param_count == args.count, "%td == %td (%s)", param_count, args.count, LLVMPrintValueToString(value.value));
  845. }
  846. lbValue result = {};
  847. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  848. {
  849. bool is_odin_cc = is_calling_convention_odin(pt->Proc.calling_convention);
  850. lbFunctionType *ft = lb_get_function_type(m, pt);
  851. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  852. bool split_returns = ft->multiple_return_original_type != nullptr;
  853. unsigned param_index = 0;
  854. for (isize i = 0; i < param_count; i++) {
  855. Entity *e = pt->Proc.params->Tuple.variables[i];
  856. if (e->kind != Entity_Variable) {
  857. continue;
  858. }
  859. GB_ASSERT(e->flags & EntityFlag_Param);
  860. Type *original_type = e->type;
  861. lbArgType *arg = &ft->args[param_index];
  862. if (arg->kind == lbArg_Ignore) {
  863. continue;
  864. }
  865. lbValue x = lb_emit_conv(p, args[i], original_type);
  866. LLVMTypeRef xt = lb_type(p->module, x.type);
  867. if (arg->kind == lbArg_Direct) {
  868. LLVMTypeRef abi_type = arg->cast_type;
  869. if (!abi_type) {
  870. abi_type = arg->type;
  871. }
  872. if (xt == abi_type) {
  873. array_add(&processed_args, x);
  874. } else {
  875. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  876. array_add(&processed_args, x);
  877. }
  878. } else if (arg->kind == lbArg_Indirect) {
  879. lbValue ptr = {};
  880. if (arg->is_byval) {
  881. if (is_odin_cc) {
  882. if (are_types_identical(original_type, t_source_code_location)) {
  883. ptr = lb_address_from_load_or_generate_local(p, x);
  884. // } else {
  885. // ptr = lb_address_from_load_if_readonly_parameter(p, x);
  886. }
  887. }
  888. if (ptr.value == nullptr) {
  889. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  890. }
  891. } else if (is_odin_cc) {
  892. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  893. // i.e. `T const &` in C++
  894. if (LLVMIsConstant(x.value)) {
  895. // NOTE(bill): if the value is already constant, then just it as a global variable
  896. // and pass it by pointer
  897. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  898. lb_make_global_private_const(addr);
  899. ptr = addr.addr;
  900. } else {
  901. ptr = lb_address_from_load_or_generate_local(p, x);
  902. }
  903. } else {
  904. if (LLVMIsConstant(x.value)) {
  905. // NOTE(bill): if the value is already constant, then just it as a global variable
  906. // and pass it by pointer
  907. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  908. lb_make_global_private_const(addr);
  909. ptr = addr.addr;
  910. } else {
  911. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  912. }
  913. }
  914. array_add(&processed_args, ptr);
  915. }
  916. param_index += 1;
  917. }
  918. if (is_c_vararg) {
  919. for (isize i = processed_args.count; i < args.count; i++) {
  920. array_add(&processed_args, args[i]);
  921. }
  922. }
  923. if (inlining == ProcInlining_none) {
  924. inlining = p->inlining;
  925. }
  926. Type *rt = reduce_tuple_to_single_type(results);
  927. Type *original_rt = rt;
  928. if (split_returns) {
  929. GB_ASSERT(rt->kind == Type_Tuple);
  930. for (isize j = 0; j < rt->Tuple.variables.count-1; j++) {
  931. Type *partial_return_type = rt->Tuple.variables[j]->type;
  932. lbValue partial_return_ptr = lb_add_local(p, partial_return_type, nullptr, true, false).addr;
  933. array_add(&processed_args, partial_return_ptr);
  934. }
  935. rt = reduce_tuple_to_single_type(rt->Tuple.variables[rt->Tuple.variables.count-1]->type);
  936. }
  937. if (return_by_pointer) {
  938. lbValue return_ptr = lb_add_local_generated(p, rt, true).addr;
  939. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  940. result = lb_emit_load(p, return_ptr);
  941. } else if (rt != nullptr) {
  942. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  943. if (ft->ret.cast_type) {
  944. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  945. }
  946. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  947. result.type = rt;
  948. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  949. result.type = t_llvm_bool;
  950. }
  951. if (!is_type_tuple(rt)) {
  952. result = lb_emit_conv(p, result, rt);
  953. }
  954. } else {
  955. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  956. }
  957. if (original_rt != rt) {
  958. GB_ASSERT(split_returns);
  959. GB_ASSERT(is_type_tuple(original_rt));
  960. // IMPORTANT NOTE(bill, 2022-11-24)
  961. // result_ptr is a dummy value which is only used to reference a tuple
  962. // value for the "tuple-fix"
  963. //
  964. // The reason for the fake stack allocation is to have a unique pointer
  965. // for the value to be used as a key within the procedure itself
  966. lbValue result_ptr = lb_add_local_generated(p, original_rt, false).addr;
  967. isize ret_count = original_rt->Tuple.variables.count;
  968. auto tuple_fix_values = slice_make<lbValue>(permanent_allocator(), ret_count);
  969. auto tuple_geps = slice_make<lbValue>(permanent_allocator(), ret_count);
  970. isize offset = ft->original_arg_count;
  971. for (isize j = 0; j < ret_count-1; j++) {
  972. lbValue ret_arg_ptr = processed_args[offset + j];
  973. lbValue ret_arg = lb_emit_load(p, ret_arg_ptr);
  974. tuple_fix_values[j] = ret_arg;
  975. }
  976. tuple_fix_values[ret_count-1] = result;
  977. #if 0
  978. for (isize j = 0; j < ret_count; j++) {
  979. tuple_geps[j] = lb_emit_struct_ep(p, result_ptr, cast(i32)j);
  980. }
  981. for (isize j = 0; j < ret_count; j++) {
  982. lb_emit_store(p, tuple_geps[j], tuple_fix_values[j]);
  983. }
  984. #endif
  985. result = lb_emit_load(p, result_ptr);
  986. lbTupleFix tf = {tuple_fix_values};
  987. map_set(&p->tuple_fix_map, result_ptr.value, tf);
  988. map_set(&p->tuple_fix_map, result.value, tf);
  989. }
  990. }
  991. LLVMValueRef the_proc_value = value.value;
  992. if (LLVMIsAConstantExpr(the_proc_value)) {
  993. // NOTE(bill): it's a bit cast
  994. the_proc_value = LLVMGetOperand(the_proc_value, 0);
  995. }
  996. Entity **found = map_get(&p->module->procedure_values, the_proc_value);
  997. if (found != nullptr) {
  998. Entity *e = *found;
  999. if (e != nullptr && entity_has_deferred_procedure(e)) {
  1000. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  1001. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  1002. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  1003. bool by_ptr = false;
  1004. auto in_args = args;
  1005. Array<lbValue> result_as_args = {};
  1006. switch (kind) {
  1007. case DeferredProcedure_none:
  1008. break;
  1009. case DeferredProcedure_in_by_ptr:
  1010. by_ptr = true;
  1011. /*fallthrough*/
  1012. case DeferredProcedure_in:
  1013. result_as_args = array_clone(heap_allocator(), in_args);
  1014. break;
  1015. case DeferredProcedure_out_by_ptr:
  1016. by_ptr = true;
  1017. /*fallthrough*/
  1018. case DeferredProcedure_out:
  1019. result_as_args = lb_value_to_array(p, heap_allocator(), result);
  1020. break;
  1021. case DeferredProcedure_in_out_by_ptr:
  1022. by_ptr = true;
  1023. /*fallthrough*/
  1024. case DeferredProcedure_in_out:
  1025. {
  1026. auto out_args = lb_value_to_array(p, heap_allocator(), result);
  1027. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  1028. array_copy(&result_as_args, in_args, 0);
  1029. array_copy(&result_as_args, out_args, in_args.count);
  1030. }
  1031. break;
  1032. }
  1033. if (by_ptr) {
  1034. for_array(i, result_as_args) {
  1035. lbValue arg_ptr = lb_address_from_load_or_generate_local(p, result_as_args[i]);
  1036. result_as_args[i] = arg_ptr;
  1037. }
  1038. }
  1039. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  1040. }
  1041. }
  1042. return result;
  1043. }
  1044. gb_internal LLVMValueRef llvm_splat_int(i64 count, LLVMTypeRef type, i64 value, bool is_signed=false) {
  1045. LLVMValueRef v = LLVMConstInt(type, value, is_signed);
  1046. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1047. for (i64 i = 0; i < count; i++) {
  1048. values[i] = v;
  1049. }
  1050. return LLVMConstVector(values, cast(unsigned)count);
  1051. }
  1052. gb_internal lbValue lb_build_builtin_simd_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId builtin_id) {
  1053. ast_node(ce, CallExpr, expr);
  1054. lbModule *m = p->module;
  1055. lbValue res = {};
  1056. res.type = tv.type;
  1057. lbValue arg0 = {}; if (ce->args.count > 0) arg0 = lb_build_expr(p, ce->args[0]);
  1058. lbValue arg1 = {}; if (ce->args.count > 1) arg1 = lb_build_expr(p, ce->args[1]);
  1059. lbValue arg2 = {}; if (ce->args.count > 2) arg2 = lb_build_expr(p, ce->args[2]);
  1060. Type *elem = base_array_type(arg0.type);
  1061. bool is_float = is_type_float(elem);
  1062. bool is_signed = !is_type_unsigned(elem);
  1063. LLVMOpcode op_code = cast(LLVMOpcode)0;
  1064. switch (builtin_id) {
  1065. case BuiltinProc_simd_add:
  1066. case BuiltinProc_simd_sub:
  1067. case BuiltinProc_simd_mul:
  1068. case BuiltinProc_simd_div:
  1069. case BuiltinProc_simd_rem:
  1070. if (is_float) {
  1071. switch (builtin_id) {
  1072. case BuiltinProc_simd_add: op_code = LLVMFAdd; break;
  1073. case BuiltinProc_simd_sub: op_code = LLVMFSub; break;
  1074. case BuiltinProc_simd_mul: op_code = LLVMFMul; break;
  1075. case BuiltinProc_simd_div: op_code = LLVMFDiv; break;
  1076. }
  1077. } else {
  1078. switch (builtin_id) {
  1079. case BuiltinProc_simd_add: op_code = LLVMAdd; break;
  1080. case BuiltinProc_simd_sub: op_code = LLVMSub; break;
  1081. case BuiltinProc_simd_mul: op_code = LLVMMul; break;
  1082. case BuiltinProc_simd_div:
  1083. if (is_signed) {
  1084. op_code = LLVMSDiv;
  1085. } else {
  1086. op_code = LLVMUDiv;
  1087. }
  1088. break;
  1089. case BuiltinProc_simd_rem:
  1090. if (is_signed) {
  1091. op_code = LLVMSRem;
  1092. } else {
  1093. op_code = LLVMURem;
  1094. }
  1095. break;
  1096. }
  1097. }
  1098. if (op_code) {
  1099. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1100. return res;
  1101. }
  1102. break;
  1103. case BuiltinProc_simd_shl: // Odin logic
  1104. case BuiltinProc_simd_shr: // Odin logic
  1105. case BuiltinProc_simd_shl_masked: // C logic
  1106. case BuiltinProc_simd_shr_masked: // C logic
  1107. {
  1108. i64 sz = type_size_of(elem);
  1109. GB_ASSERT(arg0.type->kind == Type_SimdVector);
  1110. i64 count = arg0.type->SimdVector.count;
  1111. Type *elem1 = base_array_type(arg1.type);
  1112. bool is_masked = false;
  1113. switch (builtin_id) {
  1114. case BuiltinProc_simd_shl: op_code = LLVMShl; is_masked = false; break;
  1115. case BuiltinProc_simd_shr: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = false; break;
  1116. case BuiltinProc_simd_shl_masked: op_code = LLVMShl; is_masked = true; break;
  1117. case BuiltinProc_simd_shr_masked: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = true; break;
  1118. }
  1119. if (op_code) {
  1120. LLVMValueRef bits = llvm_splat_int(count, lb_type(m, elem1), sz*8 - 1);
  1121. if (is_masked) {
  1122. // C logic
  1123. LLVMValueRef shift = LLVMBuildAnd(p->builder, arg1.value, bits, "");
  1124. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, shift, "");
  1125. } else {
  1126. // Odin logic
  1127. LLVMValueRef zero = lb_const_nil(m, arg1.type).value;
  1128. LLVMValueRef mask = LLVMBuildICmp(p->builder, LLVMIntULE, arg1.value, bits, "");
  1129. LLVMValueRef shift = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1130. res.value = LLVMBuildSelect(p->builder, mask, shift, zero, "");
  1131. }
  1132. return res;
  1133. }
  1134. }
  1135. break;
  1136. case BuiltinProc_simd_and:
  1137. case BuiltinProc_simd_or:
  1138. case BuiltinProc_simd_xor:
  1139. case BuiltinProc_simd_and_not:
  1140. switch (builtin_id) {
  1141. case BuiltinProc_simd_and: op_code = LLVMAnd; break;
  1142. case BuiltinProc_simd_or: op_code = LLVMOr; break;
  1143. case BuiltinProc_simd_xor: op_code = LLVMXor; break;
  1144. case BuiltinProc_simd_and_not:
  1145. op_code = LLVMAnd;
  1146. arg1.value = LLVMBuildNot(p->builder, arg1.value, "");
  1147. break;
  1148. }
  1149. if (op_code) {
  1150. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1151. return res;
  1152. }
  1153. break;
  1154. case BuiltinProc_simd_neg:
  1155. if (is_float) {
  1156. res.value = LLVMBuildFNeg(p->builder, arg0.value, "");
  1157. } else {
  1158. res.value = LLVMBuildNeg(p->builder, arg0.value, "");
  1159. }
  1160. return res;
  1161. case BuiltinProc_simd_abs:
  1162. if (is_float) {
  1163. LLVMValueRef pos = arg0.value;
  1164. LLVMValueRef neg = LLVMBuildFNeg(p->builder, pos, "");
  1165. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, pos, neg, "");
  1166. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1167. } else {
  1168. LLVMValueRef pos = arg0.value;
  1169. LLVMValueRef neg = LLVMBuildNeg(p->builder, pos, "");
  1170. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, pos, neg, "");
  1171. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1172. }
  1173. return res;
  1174. case BuiltinProc_simd_min:
  1175. if (is_float) {
  1176. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOLT, arg0.value, arg1.value, "");
  1177. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1178. } else {
  1179. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSLT : LLVMIntULT, arg0.value, arg1.value, "");
  1180. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1181. }
  1182. return res;
  1183. case BuiltinProc_simd_max:
  1184. if (is_float) {
  1185. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, arg0.value, arg1.value, "");
  1186. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1187. } else {
  1188. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, arg0.value, arg1.value, "");
  1189. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1190. }
  1191. return res;
  1192. case BuiltinProc_simd_lanes_eq:
  1193. case BuiltinProc_simd_lanes_ne:
  1194. case BuiltinProc_simd_lanes_lt:
  1195. case BuiltinProc_simd_lanes_le:
  1196. case BuiltinProc_simd_lanes_gt:
  1197. case BuiltinProc_simd_lanes_ge:
  1198. if (is_float) {
  1199. LLVMRealPredicate pred = cast(LLVMRealPredicate)0;
  1200. switch (builtin_id) {
  1201. case BuiltinProc_simd_lanes_eq: pred = LLVMRealOEQ; break;
  1202. case BuiltinProc_simd_lanes_ne: pred = LLVMRealONE; break;
  1203. case BuiltinProc_simd_lanes_lt: pred = LLVMRealOLT; break;
  1204. case BuiltinProc_simd_lanes_le: pred = LLVMRealOLE; break;
  1205. case BuiltinProc_simd_lanes_gt: pred = LLVMRealOGT; break;
  1206. case BuiltinProc_simd_lanes_ge: pred = LLVMRealOGE; break;
  1207. }
  1208. if (pred) {
  1209. res.value = LLVMBuildFCmp(p->builder, pred, arg0.value, arg1.value, "");
  1210. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1211. return res;
  1212. }
  1213. } else {
  1214. LLVMIntPredicate pred = cast(LLVMIntPredicate)0;
  1215. switch (builtin_id) {
  1216. case BuiltinProc_simd_lanes_eq: pred = LLVMIntEQ; break;
  1217. case BuiltinProc_simd_lanes_ne: pred = LLVMIntNE; break;
  1218. case BuiltinProc_simd_lanes_lt: pred = is_signed ? LLVMIntSLT :LLVMIntULT; break;
  1219. case BuiltinProc_simd_lanes_le: pred = is_signed ? LLVMIntSLE :LLVMIntULE; break;
  1220. case BuiltinProc_simd_lanes_gt: pred = is_signed ? LLVMIntSGT :LLVMIntUGT; break;
  1221. case BuiltinProc_simd_lanes_ge: pred = is_signed ? LLVMIntSGE :LLVMIntUGE; break;
  1222. }
  1223. if (pred) {
  1224. res.value = LLVMBuildICmp(p->builder, pred, arg0.value, arg1.value, "");
  1225. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1226. return res;
  1227. }
  1228. }
  1229. break;
  1230. case BuiltinProc_simd_extract:
  1231. res.value = LLVMBuildExtractElement(p->builder, arg0.value, arg1.value, "");
  1232. return res;
  1233. case BuiltinProc_simd_replace:
  1234. res.value = LLVMBuildInsertElement(p->builder, arg0.value, arg2.value, arg1.value, "");
  1235. return res;
  1236. case BuiltinProc_simd_reduce_add_ordered:
  1237. case BuiltinProc_simd_reduce_mul_ordered:
  1238. {
  1239. LLVMTypeRef llvm_elem = lb_type(m, elem);
  1240. LLVMValueRef args[2] = {};
  1241. isize args_count = 0;
  1242. char const *name = nullptr;
  1243. switch (builtin_id) {
  1244. case BuiltinProc_simd_reduce_add_ordered:
  1245. if (is_float) {
  1246. name = "llvm.vector.reduce.fadd";
  1247. args[args_count++] = LLVMConstReal(llvm_elem, 0.0);
  1248. } else {
  1249. name = "llvm.vector.reduce.add";
  1250. }
  1251. break;
  1252. case BuiltinProc_simd_reduce_mul_ordered:
  1253. if (is_float) {
  1254. name = "llvm.vector.reduce.fmul";
  1255. args[args_count++] = LLVMConstReal(llvm_elem, 1.0);
  1256. } else {
  1257. name = "llvm.vector.reduce.mul";
  1258. }
  1259. break;
  1260. }
  1261. args[args_count++] = arg0.value;
  1262. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1263. res.value = lb_call_intrinsic(p, name, args, cast(unsigned)args_count, types, gb_count_of(types));
  1264. return res;
  1265. }
  1266. case BuiltinProc_simd_reduce_min:
  1267. case BuiltinProc_simd_reduce_max:
  1268. case BuiltinProc_simd_reduce_and:
  1269. case BuiltinProc_simd_reduce_or:
  1270. case BuiltinProc_simd_reduce_xor:
  1271. {
  1272. char const *name = nullptr;
  1273. switch (builtin_id) {
  1274. case BuiltinProc_simd_reduce_min:
  1275. if (is_float) {
  1276. name = "llvm.vector.reduce.fmin";
  1277. } else if (is_signed) {
  1278. name = "llvm.vector.reduce.smin";
  1279. } else {
  1280. name = "llvm.vector.reduce.umin";
  1281. }
  1282. break;
  1283. case BuiltinProc_simd_reduce_max:
  1284. if (is_float) {
  1285. name = "llvm.vector.reduce.fmax";
  1286. } else if (is_signed) {
  1287. name = "llvm.vector.reduce.smax";
  1288. } else {
  1289. name = "llvm.vector.reduce.umax";
  1290. }
  1291. break;
  1292. case BuiltinProc_simd_reduce_and: name = "llvm.vector.reduce.and"; break;
  1293. case BuiltinProc_simd_reduce_or: name = "llvm.vector.reduce.or"; break;
  1294. case BuiltinProc_simd_reduce_xor: name = "llvm.vector.reduce.xor"; break;
  1295. }
  1296. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1297. LLVMValueRef args[1] = { arg0.value };
  1298. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1299. return res;
  1300. }
  1301. case BuiltinProc_simd_shuffle:
  1302. {
  1303. Type *vt = arg0.type;
  1304. GB_ASSERT(vt->kind == Type_SimdVector);
  1305. i64 indices_count = ce->args.count-2;
  1306. i64 max_count = vt->SimdVector.count*2;
  1307. GB_ASSERT(indices_count <= max_count);
  1308. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, indices_count);
  1309. for (isize i = 0; i < indices_count; i++) {
  1310. lbValue idx = lb_build_expr(p, ce->args[i+2]);
  1311. GB_ASSERT(LLVMIsConstant(idx.value));
  1312. values[i] = idx.value;
  1313. }
  1314. LLVMValueRef indices = LLVMConstVector(values, cast(unsigned)indices_count);
  1315. res.value = LLVMBuildShuffleVector(p->builder, arg0.value, arg1.value, indices, "");
  1316. return res;
  1317. }
  1318. case BuiltinProc_simd_select:
  1319. {
  1320. LLVMValueRef cond = arg0.value;
  1321. LLVMValueRef x = lb_build_expr(p, ce->args[1]).value;
  1322. LLVMValueRef y = lb_build_expr(p, ce->args[2]).value;
  1323. cond = LLVMBuildICmp(p->builder, LLVMIntNE, cond, LLVMConstNull(LLVMTypeOf(cond)), "");
  1324. res.value = LLVMBuildSelect(p->builder, cond, x, y, "");
  1325. return res;
  1326. }
  1327. case BuiltinProc_simd_ceil:
  1328. case BuiltinProc_simd_floor:
  1329. case BuiltinProc_simd_trunc:
  1330. case BuiltinProc_simd_nearest:
  1331. {
  1332. char const *name = nullptr;
  1333. switch (builtin_id) {
  1334. case BuiltinProc_simd_ceil: name = "llvm.ceil"; break;
  1335. case BuiltinProc_simd_floor: name = "llvm.floor"; break;
  1336. case BuiltinProc_simd_trunc: name = "llvm.trunc"; break;
  1337. case BuiltinProc_simd_nearest: name = "llvm.nearbyint"; break;
  1338. }
  1339. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1340. LLVMValueRef args[1] = { arg0.value };
  1341. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1342. return res;
  1343. }
  1344. case BuiltinProc_simd_lanes_reverse:
  1345. {
  1346. i64 count = get_array_type_count(arg0.type);
  1347. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1348. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1349. for (i64 i = 0; i < count; i++) {
  1350. values[i] = LLVMConstInt(llvm_u32, count-1-i, false);
  1351. }
  1352. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1353. LLVMValueRef v = arg0.value;
  1354. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1355. return res;
  1356. }
  1357. case BuiltinProc_simd_lanes_rotate_left:
  1358. case BuiltinProc_simd_lanes_rotate_right:
  1359. {
  1360. i64 count = get_array_type_count(arg0.type);
  1361. GB_ASSERT(is_power_of_two(count));
  1362. BigInt bi_count = {};
  1363. big_int_from_i64(&bi_count, count);
  1364. TypeAndValue const &tv = ce->args[1]->tav;
  1365. ExactValue val = exact_value_to_integer(tv.value);
  1366. GB_ASSERT(val.kind == ExactValue_Integer);
  1367. BigInt *bi = &val.value_integer;
  1368. if (builtin_id == BuiltinProc_simd_lanes_rotate_right) {
  1369. big_int_neg(bi, bi);
  1370. }
  1371. big_int_rem(bi, bi, &bi_count);
  1372. big_int_dealloc(&bi_count);
  1373. i64 left = big_int_to_i64(bi);
  1374. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1375. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1376. for (i64 i = 0; i < count; i++) {
  1377. u64 idx = cast(u64)(i+left) & cast(u64)(count-1);
  1378. values[i] = LLVMConstInt(llvm_u32, idx, false);
  1379. }
  1380. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1381. LLVMValueRef v = arg0.value;
  1382. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1383. return res;
  1384. }
  1385. case BuiltinProc_simd_add_sat:
  1386. case BuiltinProc_simd_sub_sat:
  1387. {
  1388. char const *name = nullptr;
  1389. switch (builtin_id) {
  1390. case BuiltinProc_simd_add_sat: name = is_signed ? "llvm.sadd.sat" : "llvm.uadd.sat"; break;
  1391. case BuiltinProc_simd_sub_sat: name = is_signed ? "llvm.ssub.sat" : "llvm.usub.sat"; break;
  1392. }
  1393. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1394. LLVMValueRef args[2] = { arg0.value, arg1.value };
  1395. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1396. return res;
  1397. }
  1398. case BuiltinProc_simd_clamp:
  1399. {
  1400. LLVMValueRef v = arg0.value;
  1401. LLVMValueRef min = arg1.value;
  1402. LLVMValueRef max = arg2.value;
  1403. if (is_float) {
  1404. v = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOLT, v, min, ""), min, v, "");
  1405. res.value = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOGT, v, max, ""), max, v, "");
  1406. } else if (is_signed) {
  1407. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSLT, v, min, ""), min, v, "");
  1408. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSGT, v, max, ""), max, v, "");
  1409. } else {
  1410. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntULT, v, min, ""), min, v, "");
  1411. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntUGT, v, max, ""), max, v, "");
  1412. }
  1413. return res;
  1414. }
  1415. case BuiltinProc_simd_to_bits:
  1416. {
  1417. res.value = LLVMBuildBitCast(p->builder, arg0.value, lb_type(m, tv.type), "");
  1418. return res;
  1419. }
  1420. }
  1421. GB_PANIC("Unhandled simd intrinsic: '%.*s'", LIT(builtin_procs[builtin_id].name));
  1422. return {};
  1423. }
  1424. gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  1425. ast_node(ce, CallExpr, expr);
  1426. if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {
  1427. return lb_build_builtin_simd_proc(p, expr, tv, id);
  1428. }
  1429. switch (id) {
  1430. case BuiltinProc_DIRECTIVE: {
  1431. ast_node(bd, BasicDirective, ce->proc);
  1432. String name = bd->name.string;
  1433. GB_ASSERT(name == "location");
  1434. String procedure = p->entity->token.string;
  1435. TokenPos pos = ast_token(ce->proc).pos;
  1436. if (ce->args.count > 0) {
  1437. Ast *ident = unselector_expr(ce->args[0]);
  1438. GB_ASSERT(ident->kind == Ast_Ident);
  1439. Entity *e = entity_of_node(ident);
  1440. GB_ASSERT(e != nullptr);
  1441. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  1442. procedure = e->parent_proc_decl->entity->token.string;
  1443. } else {
  1444. procedure = str_lit("");
  1445. }
  1446. pos = e->token.pos;
  1447. }
  1448. return lb_emit_source_code_location_as_global(p, procedure, pos);
  1449. }
  1450. case BuiltinProc_type_info_of: {
  1451. Ast *arg = ce->args[0];
  1452. TypeAndValue tav = type_and_value_of_expr(arg);
  1453. if (tav.mode == Addressing_Type) {
  1454. Type *t = default_type(type_of_expr(arg));
  1455. return lb_type_info(p->module, t);
  1456. }
  1457. GB_ASSERT(is_type_typeid(tav.type));
  1458. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1459. args[0] = lb_build_expr(p, arg);
  1460. return lb_emit_runtime_call(p, "__type_info_of", args);
  1461. }
  1462. case BuiltinProc_typeid_of: {
  1463. Ast *arg = ce->args[0];
  1464. TypeAndValue tav = type_and_value_of_expr(arg);
  1465. GB_ASSERT(tav.mode == Addressing_Type);
  1466. Type *t = default_type(type_of_expr(arg));
  1467. return lb_typeid(p->module, t);
  1468. }
  1469. case BuiltinProc_len: {
  1470. lbValue v = lb_build_expr(p, ce->args[0]);
  1471. Type *t = base_type(v.type);
  1472. if (is_type_pointer(t)) {
  1473. v = lb_emit_load(p, v);
  1474. t = type_deref(t);
  1475. }
  1476. if (is_type_cstring(t)) {
  1477. return lb_cstring_len(p, v);
  1478. } else if (is_type_string(t)) {
  1479. return lb_string_len(p, v);
  1480. } else if (is_type_array(t)) {
  1481. GB_PANIC("Array lengths are constant");
  1482. } else if (is_type_slice(t)) {
  1483. return lb_slice_len(p, v);
  1484. } else if (is_type_dynamic_array(t)) {
  1485. return lb_dynamic_array_len(p, v);
  1486. } else if (is_type_map(t)) {
  1487. return lb_map_len(p, v);
  1488. } else if (is_type_soa_struct(t)) {
  1489. return lb_soa_struct_len(p, v);
  1490. }
  1491. GB_PANIC("Unreachable");
  1492. break;
  1493. }
  1494. case BuiltinProc_cap: {
  1495. lbValue v = lb_build_expr(p, ce->args[0]);
  1496. Type *t = base_type(v.type);
  1497. if (is_type_pointer(t)) {
  1498. v = lb_emit_load(p, v);
  1499. t = type_deref(t);
  1500. }
  1501. if (is_type_string(t)) {
  1502. GB_PANIC("Unreachable");
  1503. } else if (is_type_array(t)) {
  1504. GB_PANIC("Array lengths are constant");
  1505. } else if (is_type_slice(t)) {
  1506. return lb_slice_len(p, v);
  1507. } else if (is_type_dynamic_array(t)) {
  1508. return lb_dynamic_array_cap(p, v);
  1509. } else if (is_type_map(t)) {
  1510. return lb_map_cap(p, v);
  1511. } else if (is_type_soa_struct(t)) {
  1512. return lb_soa_struct_cap(p, v);
  1513. }
  1514. GB_PANIC("Unreachable");
  1515. break;
  1516. }
  1517. case BuiltinProc_swizzle: {
  1518. isize index_count = ce->args.count-1;
  1519. if (is_type_simd_vector(tv.type)) {
  1520. lbValue vec = lb_build_expr(p, ce->args[0]);
  1521. if (index_count == 0) {
  1522. return vec;
  1523. }
  1524. unsigned mask_len = cast(unsigned)index_count;
  1525. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1526. for (isize i = 1; i < ce->args.count; i++) {
  1527. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  1528. GB_ASSERT(is_type_integer(tv.type));
  1529. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  1530. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  1531. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  1532. }
  1533. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1534. LLVMValueRef v1 = vec.value;
  1535. LLVMValueRef v2 = vec.value;
  1536. lbValue res = {};
  1537. res.type = tv.type;
  1538. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1539. return res;
  1540. }
  1541. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  1542. return lb_addr_load(p, addr);
  1543. }
  1544. case BuiltinProc_complex: {
  1545. lbValue real = lb_build_expr(p, ce->args[0]);
  1546. lbValue imag = lb_build_expr(p, ce->args[1]);
  1547. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1548. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1549. Type *ft = base_complex_elem_type(tv.type);
  1550. real = lb_emit_conv(p, real, ft);
  1551. imag = lb_emit_conv(p, imag, ft);
  1552. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  1553. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  1554. return lb_emit_load(p, dst);
  1555. }
  1556. case BuiltinProc_quaternion: {
  1557. lbValue real = lb_build_expr(p, ce->args[0]);
  1558. lbValue imag = lb_build_expr(p, ce->args[1]);
  1559. lbValue jmag = lb_build_expr(p, ce->args[2]);
  1560. lbValue kmag = lb_build_expr(p, ce->args[3]);
  1561. // @QuaternionLayout
  1562. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1563. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1564. Type *ft = base_complex_elem_type(tv.type);
  1565. real = lb_emit_conv(p, real, ft);
  1566. imag = lb_emit_conv(p, imag, ft);
  1567. jmag = lb_emit_conv(p, jmag, ft);
  1568. kmag = lb_emit_conv(p, kmag, ft);
  1569. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  1570. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  1571. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  1572. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  1573. return lb_emit_load(p, dst);
  1574. }
  1575. case BuiltinProc_real: {
  1576. lbValue val = lb_build_expr(p, ce->args[0]);
  1577. if (is_type_complex(val.type)) {
  1578. lbValue real = lb_emit_struct_ev(p, val, 0);
  1579. return lb_emit_conv(p, real, tv.type);
  1580. } else if (is_type_quaternion(val.type)) {
  1581. // @QuaternionLayout
  1582. lbValue real = lb_emit_struct_ev(p, val, 3);
  1583. return lb_emit_conv(p, real, tv.type);
  1584. }
  1585. GB_PANIC("invalid type for real");
  1586. return {};
  1587. }
  1588. case BuiltinProc_imag: {
  1589. lbValue val = lb_build_expr(p, ce->args[0]);
  1590. if (is_type_complex(val.type)) {
  1591. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1592. return lb_emit_conv(p, imag, tv.type);
  1593. } else if (is_type_quaternion(val.type)) {
  1594. // @QuaternionLayout
  1595. lbValue imag = lb_emit_struct_ev(p, val, 0);
  1596. return lb_emit_conv(p, imag, tv.type);
  1597. }
  1598. GB_PANIC("invalid type for imag");
  1599. return {};
  1600. }
  1601. case BuiltinProc_jmag: {
  1602. lbValue val = lb_build_expr(p, ce->args[0]);
  1603. if (is_type_quaternion(val.type)) {
  1604. // @QuaternionLayout
  1605. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1606. return lb_emit_conv(p, imag, tv.type);
  1607. }
  1608. GB_PANIC("invalid type for jmag");
  1609. return {};
  1610. }
  1611. case BuiltinProc_kmag: {
  1612. lbValue val = lb_build_expr(p, ce->args[0]);
  1613. if (is_type_quaternion(val.type)) {
  1614. // @QuaternionLayout
  1615. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1616. return lb_emit_conv(p, imag, tv.type);
  1617. }
  1618. GB_PANIC("invalid type for kmag");
  1619. return {};
  1620. }
  1621. case BuiltinProc_conj: {
  1622. lbValue val = lb_build_expr(p, ce->args[0]);
  1623. return lb_emit_conjugate(p, val, tv.type);
  1624. }
  1625. case BuiltinProc_expand_values: {
  1626. lbValue val = lb_build_expr(p, ce->args[0]);
  1627. Type *t = base_type(val.type);
  1628. if (!is_type_tuple(tv.type)) {
  1629. if (t->kind == Type_Struct) {
  1630. GB_ASSERT(t->Struct.fields.count == 1);
  1631. return lb_emit_struct_ev(p, val, 0);
  1632. } else if (t->kind == Type_Array) {
  1633. GB_ASSERT(t->Array.count == 1);
  1634. return lb_emit_struct_ev(p, val, 0);
  1635. } else {
  1636. GB_PANIC("Unknown type of expand_values");
  1637. }
  1638. }
  1639. GB_ASSERT(is_type_tuple(tv.type));
  1640. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1641. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1642. if (t->kind == Type_Struct) {
  1643. for_array(src_index, t->Struct.fields) {
  1644. Entity *field = t->Struct.fields[src_index];
  1645. i32 field_index = field->Variable.field_index;
  1646. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1647. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1648. lb_emit_store(p, ep, f);
  1649. }
  1650. } else if (is_type_array_like(t)) {
  1651. // TODO(bill): Clean-up this code
  1652. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1653. i32 n = cast(i32)get_array_type_count(t);
  1654. for (i32 i = 0; i < n; i++) {
  1655. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1656. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1657. lb_emit_store(p, ep, f);
  1658. }
  1659. } else {
  1660. GB_PANIC("Unknown type of expand_values");
  1661. }
  1662. return lb_emit_load(p, tuple);
  1663. }
  1664. case BuiltinProc_min: {
  1665. Type *t = type_of_expr(expr);
  1666. if (ce->args.count == 2) {
  1667. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1668. } else {
  1669. lbValue x = lb_build_expr(p, ce->args[0]);
  1670. for (isize i = 1; i < ce->args.count; i++) {
  1671. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1672. }
  1673. return x;
  1674. }
  1675. }
  1676. case BuiltinProc_max: {
  1677. Type *t = type_of_expr(expr);
  1678. if (ce->args.count == 2) {
  1679. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1680. } else {
  1681. lbValue x = lb_build_expr(p, ce->args[0]);
  1682. for (isize i = 1; i < ce->args.count; i++) {
  1683. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1684. }
  1685. return x;
  1686. }
  1687. }
  1688. case BuiltinProc_abs: {
  1689. lbValue x = lb_build_expr(p, ce->args[0]);
  1690. Type *t = x.type;
  1691. if (is_type_unsigned(t)) {
  1692. return x;
  1693. }
  1694. if (is_type_quaternion(t)) {
  1695. i64 sz = 8*type_size_of(t);
  1696. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1697. args[0] = x;
  1698. switch (sz) {
  1699. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1700. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1701. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1702. }
  1703. GB_PANIC("Unknown complex type");
  1704. } else if (is_type_complex(t)) {
  1705. i64 sz = 8*type_size_of(t);
  1706. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1707. args[0] = x;
  1708. switch (sz) {
  1709. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1710. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1711. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1712. }
  1713. GB_PANIC("Unknown complex type");
  1714. }
  1715. lbValue zero = lb_const_nil(p->module, t);
  1716. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1717. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1718. return lb_emit_select(p, cond, neg, x);
  1719. }
  1720. case BuiltinProc_clamp:
  1721. return lb_emit_clamp(p, type_of_expr(expr),
  1722. lb_build_expr(p, ce->args[0]),
  1723. lb_build_expr(p, ce->args[1]),
  1724. lb_build_expr(p, ce->args[2]));
  1725. case BuiltinProc_soa_zip:
  1726. return lb_soa_zip(p, ce, tv);
  1727. case BuiltinProc_soa_unzip:
  1728. return lb_soa_unzip(p, ce, tv);
  1729. case BuiltinProc_transpose:
  1730. {
  1731. lbValue m = lb_build_expr(p, ce->args[0]);
  1732. return lb_emit_matrix_tranpose(p, m, tv.type);
  1733. }
  1734. case BuiltinProc_outer_product:
  1735. {
  1736. lbValue a = lb_build_expr(p, ce->args[0]);
  1737. lbValue b = lb_build_expr(p, ce->args[1]);
  1738. return lb_emit_outer_product(p, a, b, tv.type);
  1739. }
  1740. case BuiltinProc_hadamard_product:
  1741. {
  1742. lbValue a = lb_build_expr(p, ce->args[0]);
  1743. lbValue b = lb_build_expr(p, ce->args[1]);
  1744. if (is_type_array(tv.type)) {
  1745. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1746. }
  1747. GB_ASSERT(is_type_matrix(tv.type));
  1748. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1749. }
  1750. case BuiltinProc_matrix_flatten:
  1751. {
  1752. lbValue m = lb_build_expr(p, ce->args[0]);
  1753. return lb_emit_matrix_flatten(p, m, tv.type);
  1754. }
  1755. case BuiltinProc_unreachable:
  1756. lb_emit_unreachable(p);
  1757. return {};
  1758. case BuiltinProc_raw_data:
  1759. {
  1760. lbValue x = lb_build_expr(p, ce->args[0]);
  1761. Type *t = base_type(x.type);
  1762. lbValue res = {};
  1763. switch (t->kind) {
  1764. case Type_Slice:
  1765. res = lb_slice_elem(p, x);
  1766. res = lb_emit_conv(p, res, tv.type);
  1767. break;
  1768. case Type_DynamicArray:
  1769. res = lb_dynamic_array_elem(p, x);
  1770. res = lb_emit_conv(p, res, tv.type);
  1771. break;
  1772. case Type_Basic:
  1773. if (t->Basic.kind == Basic_string) {
  1774. res = lb_string_elem(p, x);
  1775. res = lb_emit_conv(p, res, tv.type);
  1776. } else if (t->Basic.kind == Basic_cstring) {
  1777. res = lb_emit_conv(p, x, tv.type);
  1778. }
  1779. break;
  1780. case Type_Pointer:
  1781. case Type_MultiPointer:
  1782. res = lb_emit_conv(p, x, tv.type);
  1783. break;
  1784. }
  1785. GB_ASSERT(res.value != nullptr);
  1786. return res;
  1787. }
  1788. // "Intrinsics"
  1789. case BuiltinProc_alloca:
  1790. {
  1791. lbValue sz = lb_build_expr(p, ce->args[0]);
  1792. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1793. lbValue res = {};
  1794. res.type = alloc_type_multi_pointer(t_u8);
  1795. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1796. LLVMSetAlignment(res.value, cast(unsigned)al);
  1797. return res;
  1798. }
  1799. case BuiltinProc_cpu_relax:
  1800. if (build_context.metrics.arch == TargetArch_i386 ||
  1801. build_context.metrics.arch == TargetArch_amd64) {
  1802. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1803. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1804. GB_ASSERT(the_asm != nullptr);
  1805. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1806. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1807. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1808. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1809. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1810. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1811. GB_ASSERT(the_asm != nullptr);
  1812. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1813. } else {
  1814. // NOTE: default to something to prevent optimization
  1815. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1816. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1817. GB_ASSERT(the_asm != nullptr);
  1818. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1819. }
  1820. return {};
  1821. case BuiltinProc_debug_trap:
  1822. case BuiltinProc_trap:
  1823. {
  1824. char const *name = nullptr;
  1825. switch (id) {
  1826. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1827. case BuiltinProc_trap: name = "llvm.trap"; break;
  1828. }
  1829. lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1830. if (id == BuiltinProc_trap) {
  1831. LLVMBuildUnreachable(p->builder);
  1832. }
  1833. return {};
  1834. }
  1835. case BuiltinProc_read_cycle_counter:
  1836. {
  1837. lbValue res = {};
  1838. res.type = tv.type;
  1839. if (build_context.metrics.arch == TargetArch_arm64) {
  1840. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1841. bool has_side_effects = false;
  1842. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs $0, cntvct_el0"), str_lit("=r"), has_side_effects);
  1843. GB_ASSERT(the_asm != nullptr);
  1844. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1845. } else {
  1846. char const *name = "llvm.readcyclecounter";
  1847. res.value = lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1848. }
  1849. return res;
  1850. }
  1851. case BuiltinProc_count_trailing_zeros:
  1852. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1853. case BuiltinProc_count_leading_zeros:
  1854. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1855. case BuiltinProc_count_ones:
  1856. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1857. case BuiltinProc_count_zeros:
  1858. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1859. case BuiltinProc_reverse_bits:
  1860. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1861. case BuiltinProc_byte_swap:
  1862. {
  1863. lbValue x = lb_build_expr(p, ce->args[0]);
  1864. x = lb_emit_conv(p, x, tv.type);
  1865. return lb_emit_byte_swap(p, x, tv.type);
  1866. }
  1867. case BuiltinProc_overflow_add:
  1868. case BuiltinProc_overflow_sub:
  1869. case BuiltinProc_overflow_mul:
  1870. {
  1871. Type *main_type = tv.type;
  1872. Type *type = main_type;
  1873. if (is_type_tuple(main_type)) {
  1874. type = main_type->Tuple.variables[0]->type;
  1875. }
  1876. lbValue x = lb_build_expr(p, ce->args[0]);
  1877. lbValue y = lb_build_expr(p, ce->args[1]);
  1878. x = lb_emit_conv(p, x, type);
  1879. y = lb_emit_conv(p, y, type);
  1880. char const *name = nullptr;
  1881. if (is_type_unsigned(type)) {
  1882. switch (id) {
  1883. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1884. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1885. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1886. }
  1887. } else {
  1888. switch (id) {
  1889. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1890. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1891. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1892. }
  1893. }
  1894. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1895. LLVMValueRef args[2] = { x.value, y.value };
  1896. lbValue res = {};
  1897. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1898. if (is_type_tuple(main_type)) {
  1899. Type *res_type = nullptr;
  1900. gbAllocator a = permanent_allocator();
  1901. res_type = alloc_type_tuple();
  1902. slice_init(&res_type->Tuple.variables, a, 2);
  1903. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1904. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1905. res.type = res_type;
  1906. } else {
  1907. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1908. res.type = type;
  1909. }
  1910. return res;
  1911. }
  1912. case BuiltinProc_sqrt:
  1913. {
  1914. Type *type = tv.type;
  1915. lbValue x = lb_build_expr(p, ce->args[0]);
  1916. x = lb_emit_conv(p, x, type);
  1917. char const *name = "llvm.sqrt";
  1918. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1919. LLVMValueRef args[1] = { x.value };
  1920. lbValue res = {};
  1921. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1922. res.type = type;
  1923. return res;
  1924. }
  1925. case BuiltinProc_fused_mul_add:
  1926. {
  1927. Type *type = tv.type;
  1928. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), type);
  1929. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), type);
  1930. lbValue z = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), type);
  1931. char const *name = "llvm.fma";
  1932. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1933. LLVMValueRef args[3] = { x.value, y.value, z.value };
  1934. lbValue res = {};
  1935. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1936. res.type = type;
  1937. return res;
  1938. }
  1939. case BuiltinProc_mem_copy:
  1940. {
  1941. lbValue dst = lb_build_expr(p, ce->args[0]);
  1942. lbValue src = lb_build_expr(p, ce->args[1]);
  1943. lbValue len = lb_build_expr(p, ce->args[2]);
  1944. lb_mem_copy_overlapping(p, dst, src, len, false);
  1945. return {};
  1946. }
  1947. case BuiltinProc_mem_copy_non_overlapping:
  1948. {
  1949. lbValue dst = lb_build_expr(p, ce->args[0]);
  1950. lbValue src = lb_build_expr(p, ce->args[1]);
  1951. lbValue len = lb_build_expr(p, ce->args[2]);
  1952. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  1953. return {};
  1954. }
  1955. case BuiltinProc_mem_zero:
  1956. {
  1957. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1958. lbValue len = lb_build_expr(p, ce->args[1]);
  1959. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1960. len = lb_emit_conv(p, len, t_int);
  1961. unsigned alignment = 1;
  1962. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  1963. return {};
  1964. }
  1965. case BuiltinProc_mem_zero_volatile:
  1966. {
  1967. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1968. lbValue len = lb_build_expr(p, ce->args[1]);
  1969. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1970. len = lb_emit_conv(p, len, t_int);
  1971. unsigned alignment = 1;
  1972. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  1973. return {};
  1974. }
  1975. case BuiltinProc_ptr_offset:
  1976. {
  1977. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1978. lbValue len = lb_build_expr(p, ce->args[1]);
  1979. len = lb_emit_conv(p, len, t_int);
  1980. return lb_emit_ptr_offset(p, ptr, len);
  1981. }
  1982. case BuiltinProc_ptr_sub:
  1983. {
  1984. Type *elem0 = type_deref(type_of_expr(ce->args[0]));
  1985. Type *elem1 = type_deref(type_of_expr(ce->args[1]));
  1986. GB_ASSERT(are_types_identical(elem0, elem1));
  1987. Type *elem = elem0;
  1988. lbValue ptr0 = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr);
  1989. lbValue ptr1 = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr);
  1990. lbValue diff = lb_emit_arith(p, Token_Sub, ptr0, ptr1, t_uintptr);
  1991. diff = lb_emit_conv(p, diff, t_int);
  1992. return lb_emit_arith(p, Token_Quo, diff, lb_const_int(p->module, t_int, type_size_of(elem)), t_int);
  1993. }
  1994. // TODO(bill): Which is correct?
  1995. case BuiltinProc_atomic_thread_fence:
  1996. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  1997. return {};
  1998. case BuiltinProc_atomic_signal_fence:
  1999. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  2000. return {};
  2001. case BuiltinProc_volatile_store:
  2002. case BuiltinProc_non_temporal_store:
  2003. case BuiltinProc_atomic_store:
  2004. case BuiltinProc_atomic_store_explicit: {
  2005. lbValue dst = lb_build_expr(p, ce->args[0]);
  2006. lbValue val = lb_build_expr(p, ce->args[1]);
  2007. val = lb_emit_conv(p, val, type_deref(dst.type));
  2008. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  2009. switch (id) {
  2010. case BuiltinProc_non_temporal_store:
  2011. {
  2012. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2013. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2014. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2015. }
  2016. break;
  2017. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  2018. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2019. case BuiltinProc_atomic_store_explicit:
  2020. {
  2021. auto ordering = llvm_atomic_ordering_from_odin(ce->args[2]);
  2022. LLVMSetOrdering(instr, ordering);
  2023. if (ordering == LLVMAtomicOrderingUnordered) {
  2024. LLVMSetVolatile(instr, true);
  2025. }
  2026. }
  2027. break;
  2028. }
  2029. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2030. return {};
  2031. }
  2032. case BuiltinProc_volatile_load:
  2033. case BuiltinProc_non_temporal_load:
  2034. case BuiltinProc_atomic_load:
  2035. case BuiltinProc_atomic_load_explicit: {
  2036. lbValue dst = lb_build_expr(p, ce->args[0]);
  2037. LLVMValueRef instr = LLVMBuildLoad2(p->builder, lb_type(p->module, type_deref(dst.type)), dst.value, "");
  2038. switch (id) {
  2039. case BuiltinProc_non_temporal_load:
  2040. {
  2041. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2042. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2043. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2044. }
  2045. break;
  2046. break;
  2047. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  2048. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2049. case BuiltinProc_atomic_load_explicit:
  2050. {
  2051. auto ordering = llvm_atomic_ordering_from_odin(ce->args[1]);
  2052. LLVMSetOrdering(instr, ordering);
  2053. if (ordering == LLVMAtomicOrderingUnordered) {
  2054. LLVMSetVolatile(instr, true);
  2055. }
  2056. }
  2057. break;
  2058. }
  2059. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2060. lbValue res = {};
  2061. res.value = instr;
  2062. res.type = type_deref(dst.type);
  2063. return res;
  2064. }
  2065. case BuiltinProc_unaligned_store:
  2066. {
  2067. lbValue dst = lb_build_expr(p, ce->args[0]);
  2068. lbValue src = lb_build_expr(p, ce->args[1]);
  2069. Type *t = type_deref(dst.type);
  2070. if (is_type_simd_vector(t)) {
  2071. LLVMValueRef store = LLVMBuildStore(p->builder, src.value, dst.value);
  2072. LLVMSetAlignment(store, 1);
  2073. } else {
  2074. src = lb_address_from_load_or_generate_local(p, src);
  2075. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2076. }
  2077. return {};
  2078. }
  2079. case BuiltinProc_unaligned_load:
  2080. {
  2081. lbValue src = lb_build_expr(p, ce->args[0]);
  2082. Type *t = type_deref(src.type);
  2083. if (is_type_simd_vector(t)) {
  2084. lbValue res = {};
  2085. res.type = t;
  2086. res.value = LLVMBuildLoad2(p->builder, lb_type(p->module, t), src.value, "");
  2087. LLVMSetAlignment(res.value, 1);
  2088. return res;
  2089. } else {
  2090. lbAddr dst = lb_add_local_generated(p, t, false);
  2091. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2092. return lb_addr_load(p, dst);
  2093. }
  2094. }
  2095. case BuiltinProc_atomic_add:
  2096. case BuiltinProc_atomic_sub:
  2097. case BuiltinProc_atomic_and:
  2098. case BuiltinProc_atomic_nand:
  2099. case BuiltinProc_atomic_or:
  2100. case BuiltinProc_atomic_xor:
  2101. case BuiltinProc_atomic_exchange:
  2102. case BuiltinProc_atomic_add_explicit:
  2103. case BuiltinProc_atomic_sub_explicit:
  2104. case BuiltinProc_atomic_and_explicit:
  2105. case BuiltinProc_atomic_nand_explicit:
  2106. case BuiltinProc_atomic_or_explicit:
  2107. case BuiltinProc_atomic_xor_explicit:
  2108. case BuiltinProc_atomic_exchange_explicit: {
  2109. lbValue dst = lb_build_expr(p, ce->args[0]);
  2110. lbValue val = lb_build_expr(p, ce->args[1]);
  2111. val = lb_emit_conv(p, val, type_deref(dst.type));
  2112. LLVMAtomicRMWBinOp op = {};
  2113. LLVMAtomicOrdering ordering = {};
  2114. switch (id) {
  2115. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2116. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2117. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2118. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2119. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2120. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2121. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2122. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2123. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2124. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2125. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2126. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2127. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2128. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2129. }
  2130. lbValue res = {};
  2131. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  2132. res.type = tv.type;
  2133. if (ordering == LLVMAtomicOrderingUnordered) {
  2134. LLVMSetVolatile(res.value, true);
  2135. }
  2136. return res;
  2137. }
  2138. case BuiltinProc_atomic_compare_exchange_strong:
  2139. case BuiltinProc_atomic_compare_exchange_weak:
  2140. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  2141. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  2142. lbValue address = lb_build_expr(p, ce->args[0]);
  2143. Type *elem = type_deref(address.type);
  2144. lbValue old_value = lb_build_expr(p, ce->args[1]);
  2145. lbValue new_value = lb_build_expr(p, ce->args[2]);
  2146. old_value = lb_emit_conv(p, old_value, elem);
  2147. new_value = lb_emit_conv(p, new_value, elem);
  2148. LLVMAtomicOrdering success_ordering = {};
  2149. LLVMAtomicOrdering failure_ordering = {};
  2150. LLVMBool weak = false;
  2151. switch (id) {
  2152. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  2153. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  2154. case BuiltinProc_atomic_compare_exchange_strong_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = false; break;
  2155. case BuiltinProc_atomic_compare_exchange_weak_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = true; break;
  2156. }
  2157. LLVMBool single_threaded = false;
  2158. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  2159. p->builder, address.value,
  2160. old_value.value, new_value.value,
  2161. success_ordering,
  2162. failure_ordering,
  2163. single_threaded
  2164. );
  2165. LLVMSetWeak(value, weak);
  2166. if (success_ordering == LLVMAtomicOrderingUnordered || failure_ordering == LLVMAtomicOrderingUnordered) {
  2167. LLVMSetVolatile(value, true);
  2168. }
  2169. if (is_type_tuple(tv.type)) {
  2170. Type *fix_typed = alloc_type_tuple();
  2171. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  2172. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  2173. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2174. lbValue res = {};
  2175. res.value = value;
  2176. res.type = fix_typed;
  2177. return res;
  2178. } else {
  2179. lbValue res = {};
  2180. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  2181. res.type = tv.type;
  2182. return res;
  2183. }
  2184. }
  2185. case BuiltinProc_type_equal_proc:
  2186. return lb_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  2187. case BuiltinProc_type_hasher_proc:
  2188. return lb_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  2189. case BuiltinProc_type_map_info:
  2190. return lb_gen_map_info_ptr(p->module, ce->args[0]->tav.type);
  2191. case BuiltinProc_type_map_cell_info:
  2192. return lb_gen_map_cell_info_ptr(p->module, ce->args[0]->tav.type);
  2193. case BuiltinProc_fixed_point_mul:
  2194. case BuiltinProc_fixed_point_div:
  2195. case BuiltinProc_fixed_point_mul_sat:
  2196. case BuiltinProc_fixed_point_div_sat:
  2197. {
  2198. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  2199. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  2200. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  2201. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  2202. char const *name = nullptr;
  2203. if (is_type_unsigned(tv.type)) {
  2204. switch (id) {
  2205. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  2206. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  2207. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  2208. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  2209. }
  2210. } else {
  2211. switch (id) {
  2212. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  2213. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  2214. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  2215. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  2216. }
  2217. }
  2218. GB_ASSERT(name != nullptr);
  2219. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  2220. lbValue res = {};
  2221. LLVMValueRef args[3] = {
  2222. x.value,
  2223. y.value,
  2224. scale.value };
  2225. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2226. res.type = platform_type;
  2227. return lb_emit_conv(p, res, tv.type);
  2228. }
  2229. case BuiltinProc_expect:
  2230. {
  2231. Type *t = default_type(tv.type);
  2232. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  2233. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  2234. char const *name = "llvm.expect";
  2235. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  2236. lbValue res = {};
  2237. LLVMValueRef args[2] = { x.value, y.value };
  2238. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2239. res.type = t;
  2240. return lb_emit_conv(p, res, t);
  2241. }
  2242. case BuiltinProc_prefetch_read_instruction:
  2243. case BuiltinProc_prefetch_read_data:
  2244. case BuiltinProc_prefetch_write_instruction:
  2245. case BuiltinProc_prefetch_write_data:
  2246. {
  2247. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  2248. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  2249. unsigned long long rw = 0;
  2250. unsigned long long cache = 0;
  2251. switch (id) {
  2252. case BuiltinProc_prefetch_read_instruction:
  2253. rw = 0;
  2254. cache = 0;
  2255. break;
  2256. case BuiltinProc_prefetch_read_data:
  2257. rw = 0;
  2258. cache = 1;
  2259. break;
  2260. case BuiltinProc_prefetch_write_instruction:
  2261. rw = 1;
  2262. cache = 0;
  2263. break;
  2264. case BuiltinProc_prefetch_write_data:
  2265. rw = 1;
  2266. cache = 1;
  2267. break;
  2268. }
  2269. char const *name = "llvm.prefetch";
  2270. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  2271. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  2272. LLVMValueRef args[4] = {};
  2273. args[0] = ptr.value;
  2274. args[1] = LLVMConstInt(llvm_i32, rw, false);
  2275. args[2] = LLVMConstInt(llvm_i32, locality, false);
  2276. args[3] = LLVMConstInt(llvm_i32, cache, false);
  2277. lbValue res = {};
  2278. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2279. res.type = nullptr;
  2280. return res;
  2281. }
  2282. case BuiltinProc___entry_point:
  2283. if (p->module->info->entry_point) {
  2284. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  2285. GB_ASSERT(entry_point.value != nullptr);
  2286. lb_emit_call(p, entry_point, {});
  2287. }
  2288. return {};
  2289. case BuiltinProc_syscall:
  2290. {
  2291. unsigned arg_count = cast(unsigned)ce->args.count;
  2292. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2293. for_array(i, ce->args) {
  2294. lbValue arg = lb_build_expr(p, ce->args[i]);
  2295. arg = lb_emit_conv(p, arg, t_uintptr);
  2296. args[i] = arg.value;
  2297. }
  2298. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2299. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2300. for (unsigned i = 0; i < arg_count; i++) {
  2301. llvm_arg_types[i] = llvm_uintptr;
  2302. }
  2303. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  2304. LLVMValueRef inline_asm = nullptr;
  2305. switch (build_context.metrics.arch) {
  2306. case TargetArch_amd64:
  2307. {
  2308. GB_ASSERT(arg_count <= 7);
  2309. // FreeBSD additionally clobbers r8, r9, r10, but they
  2310. // can also be used to pass in arguments, so this needs
  2311. // to be handled in two parts.
  2312. bool clobber_arg_regs[7] = {
  2313. false, false, false, false, false, false, false
  2314. };
  2315. if (build_context.metrics.os == TargetOs_freebsd) {
  2316. clobber_arg_regs[4] = true; // r10
  2317. clobber_arg_regs[5] = true; // r8
  2318. clobber_arg_regs[6] = true; // r9
  2319. }
  2320. char asm_string[] = "syscall";
  2321. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  2322. for (unsigned i = 0; i < arg_count; i++) {
  2323. if (!clobber_arg_regs[i]) {
  2324. constraints = gb_string_appendc(constraints, ",{");
  2325. } else {
  2326. constraints = gb_string_appendc(constraints, ",+{");
  2327. }
  2328. static char const *regs[] = {
  2329. "rax",
  2330. "rdi",
  2331. "rsi",
  2332. "rdx",
  2333. "r10",
  2334. "r8",
  2335. "r9"
  2336. };
  2337. constraints = gb_string_appendc(constraints, regs[i]);
  2338. constraints = gb_string_appendc(constraints, "}");
  2339. }
  2340. // The SYSCALL instruction stores the address of the
  2341. // following instruction into RCX, and RFLAGS in R11.
  2342. //
  2343. // RSP is not saved, but at least on Linux it appears
  2344. // that the kernel system-call handler does the right
  2345. // thing.
  2346. //
  2347. // Some but not all system calls will additionally
  2348. // clobber memory.
  2349. //
  2350. // As a fix for CVE-2019-5595, FreeBSD started
  2351. // clobbering R8, R9, and R10, instead of restoring
  2352. // them. Additionally unlike Linux, instead of
  2353. // returning negative errno, positive errno is
  2354. // returned and CF is set.
  2355. //
  2356. // TODO:
  2357. // * Figure out what Darwin does.
  2358. // * Add some extra handling to propagate CF back
  2359. // up to the caller on FreeBSD systems so that
  2360. // the caller knows that the return value is
  2361. // positive errno.
  2362. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  2363. if (build_context.metrics.os == TargetOs_freebsd) {
  2364. // Second half of dealing with FreeBSD's system
  2365. // call semantics. Explicitly clobber the registers
  2366. // that were not used to pass in arguments, and
  2367. // then clobber RFLAGS.
  2368. if (arg_count < 5) {
  2369. constraints = gb_string_appendc(constraints, ",~{r10}");
  2370. }
  2371. if (arg_count < 6) {
  2372. constraints = gb_string_appendc(constraints, ",~{r8}");
  2373. }
  2374. if (arg_count < 7) {
  2375. constraints = gb_string_appendc(constraints, ",~{r9}");
  2376. }
  2377. constraints = gb_string_appendc(constraints, ",~{cc}");
  2378. }
  2379. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2380. }
  2381. break;
  2382. case TargetArch_i386:
  2383. {
  2384. GB_ASSERT(arg_count <= 7);
  2385. char asm_string_default[] = "int $0x80";
  2386. char *asm_string = asm_string_default;
  2387. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  2388. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  2389. constraints = gb_string_appendc(constraints, ",{");
  2390. static char const *regs[] = {
  2391. "eax",
  2392. "ebx",
  2393. "ecx",
  2394. "edx",
  2395. "esi",
  2396. "edi",
  2397. };
  2398. constraints = gb_string_appendc(constraints, regs[i]);
  2399. constraints = gb_string_appendc(constraints, "}");
  2400. }
  2401. if (arg_count == 7) {
  2402. char asm_string7[] = "push %[arg6]\npush %%ebp\nmov 4(%%esp), %%ebp\nint $0x80\npop %%ebp\nadd $4, %%esp";
  2403. asm_string = asm_string7;
  2404. constraints = gb_string_appendc(constraints, ",rm");
  2405. }
  2406. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2407. }
  2408. break;
  2409. case TargetArch_arm64:
  2410. {
  2411. GB_ASSERT(arg_count <= 7);
  2412. if(build_context.metrics.os == TargetOs_darwin) {
  2413. char asm_string[] = "svc #0x80";
  2414. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2415. for (unsigned i = 0; i < arg_count; i++) {
  2416. constraints = gb_string_appendc(constraints, ",{");
  2417. static char const *regs[] = {
  2418. "x16",
  2419. "x0",
  2420. "x1",
  2421. "x2",
  2422. "x3",
  2423. "x4",
  2424. "x5",
  2425. };
  2426. constraints = gb_string_appendc(constraints, regs[i]);
  2427. constraints = gb_string_appendc(constraints, "}");
  2428. }
  2429. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2430. } else {
  2431. char asm_string[] = "svc #0";
  2432. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2433. for (unsigned i = 0; i < arg_count; i++) {
  2434. constraints = gb_string_appendc(constraints, ",{");
  2435. static char const *regs[] = {
  2436. "x8",
  2437. "x0",
  2438. "x1",
  2439. "x2",
  2440. "x3",
  2441. "x4",
  2442. "x5",
  2443. };
  2444. constraints = gb_string_appendc(constraints, regs[i]);
  2445. constraints = gb_string_appendc(constraints, "}");
  2446. }
  2447. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2448. }
  2449. }
  2450. break;
  2451. case TargetArch_arm32:
  2452. {
  2453. // TODO(bill): Check this is correct
  2454. GB_ASSERT(arg_count <= 7);
  2455. char asm_string[] = "svc #0";
  2456. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  2457. for (unsigned i = 0; i < arg_count; i++) {
  2458. constraints = gb_string_appendc(constraints, ",{");
  2459. static char const *regs[] = {
  2460. "r8",
  2461. "r0",
  2462. "r1",
  2463. "r2",
  2464. "r3",
  2465. "r4",
  2466. "r5",
  2467. };
  2468. constraints = gb_string_appendc(constraints, regs[i]);
  2469. constraints = gb_string_appendc(constraints, "}");
  2470. }
  2471. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2472. }
  2473. break;
  2474. default:
  2475. GB_PANIC("Unsupported platform");
  2476. }
  2477. lbValue res = {};
  2478. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2479. res.type = t_uintptr;
  2480. return res;
  2481. }
  2482. case BuiltinProc_objc_send:
  2483. return lb_handle_objc_send(p, expr);
  2484. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  2485. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  2486. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  2487. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  2488. case BuiltinProc_constant_utf16_cstring:
  2489. {
  2490. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  2491. if (r < 0x10000 || r > 0x10ffff) {
  2492. *r1 = 0xfffd;
  2493. *r2 = 0xfffd;
  2494. } else {
  2495. r -= 0x10000;
  2496. *r1 = 0xd800 + ((r>>10)&0x3ff);
  2497. *r2 = 0xdc00 + (r&0x3ff);
  2498. }
  2499. };
  2500. lbModule *m = p->module;
  2501. auto tav = type_and_value_of_expr(ce->args[0]);
  2502. GB_ASSERT(tav.value.kind == ExactValue_String);
  2503. String value = tav.value.value_string;
  2504. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  2505. isize max_len = value.len*2 + 1;
  2506. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  2507. isize n = 0;
  2508. while (value.len > 0) {
  2509. Rune r = 0;
  2510. isize w = gb_utf8_decode(value.text, value.len, &r);
  2511. value.text += w;
  2512. value.len -= w;
  2513. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  2514. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  2515. } else if (0x10000 <= r && r <= 0x10ffff) {
  2516. u16 r1, r2;
  2517. encode_surrogate_pair(r, &r1, &r2);
  2518. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  2519. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  2520. } else {
  2521. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  2522. }
  2523. }
  2524. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  2525. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  2526. char *name = nullptr;
  2527. {
  2528. isize max_len = 7+8+1;
  2529. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2530. u32 id = m->gen->global_array_index.fetch_add(1);
  2531. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2532. len -= 1;
  2533. }
  2534. LLVMTypeRef type = LLVMTypeOf(array);
  2535. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2536. LLVMSetInitializer(global_data, array);
  2537. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  2538. LLVMValueRef indices[] = {
  2539. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2540. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2541. };
  2542. lbValue res = {};
  2543. res.type = tv.type;
  2544. res.value = LLVMBuildInBoundsGEP2(p->builder, type, global_data, indices, gb_count_of(indices), "");
  2545. return res;
  2546. }
  2547. case BuiltinProc_wasm_memory_grow:
  2548. {
  2549. char const *name = "llvm.wasm.memory.grow";
  2550. LLVMTypeRef types[1] = {
  2551. lb_type(p->module, t_i32),
  2552. };
  2553. LLVMValueRef args[2] = {};
  2554. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2555. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  2556. lbValue res = {};
  2557. res.type = t_i32;
  2558. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2559. return lb_emit_conv(p, res, tv.type);
  2560. }
  2561. case BuiltinProc_wasm_memory_size:
  2562. {
  2563. char const *name = "llvm.wasm.memory.size";
  2564. LLVMTypeRef types[1] = {
  2565. lb_type(p->module, t_i32),
  2566. };
  2567. LLVMValueRef args[1] = {};
  2568. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2569. lbValue res = {};
  2570. res.type = t_i32;
  2571. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2572. return lb_emit_conv(p, res, tv.type);
  2573. }
  2574. case BuiltinProc_wasm_memory_atomic_wait32:
  2575. {
  2576. char const *name = "llvm.wasm.memory.atomic.wait32";
  2577. LLVMTypeRef types[1] = {
  2578. lb_type(p->module, t_u32),
  2579. };
  2580. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2581. LLVMValueRef args[3] = {};
  2582. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  2583. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2584. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  2585. lbValue res = {};
  2586. res.type = tv.type;
  2587. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2588. return res;
  2589. }
  2590. case BuiltinProc_wasm_memory_atomic_notify32:
  2591. {
  2592. char const *name = "llvm.wasm.memory.atomic.notify";
  2593. LLVMTypeRef types[1] = {
  2594. lb_type(p->module, t_u32),
  2595. };
  2596. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2597. LLVMValueRef args[2] = {
  2598. lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value,
  2599. lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value };
  2600. lbValue res = {};
  2601. res.type = tv.type;
  2602. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2603. return res;
  2604. }
  2605. case BuiltinProc_x86_cpuid:
  2606. {
  2607. Type *param_types[2] = {t_u32, t_u32};
  2608. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), tv.type, false, ProcCC_None);
  2609. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2610. LLVMValueRef the_asm = llvm_get_inline_asm(
  2611. func_type,
  2612. str_lit("cpuid"),
  2613. str_lit("={ax},={bx},={cx},={dx},{ax},{cx}"),
  2614. true
  2615. );
  2616. GB_ASSERT(the_asm != nullptr);
  2617. LLVMValueRef args[2] = {};
  2618. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2619. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2620. lbValue res = {};
  2621. res.type = tv.type;
  2622. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2623. return res;
  2624. }
  2625. case BuiltinProc_x86_xgetbv:
  2626. {
  2627. Type *type = alloc_type_proc_from_types(&t_u32, 1, tv.type, false, ProcCC_None);
  2628. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2629. LLVMValueRef the_asm = llvm_get_inline_asm(
  2630. func_type,
  2631. str_lit("xgetbv"),
  2632. str_lit("={ax},={dx},{cx}"),
  2633. true
  2634. );
  2635. GB_ASSERT(the_asm != nullptr);
  2636. LLVMValueRef args[1] = {};
  2637. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2638. lbValue res = {};
  2639. res.type = tv.type;
  2640. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2641. return res;
  2642. }
  2643. case BuiltinProc_valgrind_client_request:
  2644. {
  2645. lbValue args[7] = {};
  2646. for (isize i = 0; i < 7; i++) {
  2647. args[i] = lb_emit_conv(p, lb_build_expr(p, ce->args[i]), t_uintptr);
  2648. }
  2649. if (!build_context.ODIN_VALGRIND_SUPPORT) {
  2650. return args[0];
  2651. }
  2652. lbValue array = lb_generate_local_array(p, t_uintptr, 6, false);
  2653. for (isize i = 0; i < 6; i++) {
  2654. lbValue gep = lb_emit_array_epi(p, array, i);
  2655. lb_emit_store(p, gep, args[i+1]);
  2656. }
  2657. switch (build_context.metrics.arch) {
  2658. case TargetArch_amd64:
  2659. {
  2660. Type *param_types[2] = {};
  2661. param_types[0] = t_uintptr;
  2662. param_types[1] = array.type;
  2663. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), t_uintptr, false, ProcCC_None);
  2664. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2665. LLVMValueRef the_asm = llvm_get_inline_asm(
  2666. func_type,
  2667. str_lit("rolq $$3, %rdi; rolq $$13, %rdi\n rolq $$61, %rdi; rolq $$51, %rdi\n xchgq %rbx, %rbx"),
  2668. str_lit("={rdx},{rdx},{rax},~{cc},~{memory}"),
  2669. true
  2670. );
  2671. LLVMValueRef asm_args[2] = {};
  2672. asm_args[0] = args[0].value;
  2673. asm_args[1] = array.value;
  2674. lbValue res = {};
  2675. res.type = t_uintptr;
  2676. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, asm_args, gb_count_of(asm_args), "");
  2677. return res;
  2678. }
  2679. break;
  2680. default:
  2681. GB_PANIC("Unsupported architecture: %.*s", LIT(target_arch_names[build_context.metrics.arch]));
  2682. break;
  2683. }
  2684. }
  2685. }
  2686. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  2687. return {};
  2688. }
  2689. gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  2690. switch (param_value.kind) {
  2691. case ParameterValue_Constant:
  2692. if (is_type_constant_type(parameter_type)) {
  2693. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  2694. return res;
  2695. } else {
  2696. ExactValue ev = param_value.value;
  2697. lbValue arg = {};
  2698. Type *type = type_of_expr(param_value.original_ast_expr);
  2699. if (type != nullptr) {
  2700. arg = lb_const_value(p->module, type, ev);
  2701. } else {
  2702. arg = lb_const_value(p->module, parameter_type, param_value.value);
  2703. }
  2704. return lb_emit_conv(p, arg, parameter_type);
  2705. }
  2706. case ParameterValue_Nil:
  2707. return lb_const_nil(p->module, parameter_type);
  2708. case ParameterValue_Location:
  2709. {
  2710. String proc_name = {};
  2711. if (p->entity != nullptr) {
  2712. proc_name = p->entity->token.string;
  2713. }
  2714. return lb_emit_source_code_location_as_global(p, proc_name, pos);
  2715. }
  2716. case ParameterValue_Value:
  2717. return lb_build_expr(p, param_value.ast_value);
  2718. }
  2719. return lb_const_nil(p->module, parameter_type);
  2720. }
  2721. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  2722. gb_internal lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  2723. expr = unparen_expr(expr);
  2724. ast_node(ce, CallExpr, expr);
  2725. lbValue res = lb_build_call_expr_internal(p, expr);
  2726. if (ce->optional_ok_one) {
  2727. GB_ASSERT(is_type_tuple(res.type));
  2728. GB_ASSERT(res.type->Tuple.variables.count == 2);
  2729. return lb_emit_struct_ev(p, res, 0);
  2730. }
  2731. return res;
  2732. }
  2733. gb_internal void lb_add_values_to_array(lbProcedure *p, Array<lbValue> *args, lbValue value) {
  2734. if (is_type_tuple(value.type)) {
  2735. for_array(i, value.type->Tuple.variables) {
  2736. lbValue sub_value = lb_emit_struct_ev(p, value, cast(i32)i);
  2737. array_add(args, sub_value);
  2738. }
  2739. } else {
  2740. array_add(args, value);
  2741. }
  2742. }
  2743. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  2744. lbModule *m = p->module;
  2745. TypeAndValue tv = type_and_value_of_expr(expr);
  2746. ast_node(ce, CallExpr, expr);
  2747. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  2748. AddressingMode proc_mode = proc_tv.mode;
  2749. if (proc_mode == Addressing_Type) {
  2750. GB_ASSERT(ce->args.count == 1);
  2751. lbValue x = lb_build_expr(p, ce->args[0]);
  2752. lbValue y = lb_emit_conv(p, x, tv.type);
  2753. return y;
  2754. }
  2755. Ast *proc_expr = unparen_expr(ce->proc);
  2756. if (proc_mode == Addressing_Builtin) {
  2757. Entity *e = entity_of_node(proc_expr);
  2758. BuiltinProcId id = BuiltinProc_Invalid;
  2759. if (e != nullptr) {
  2760. id = cast(BuiltinProcId)e->Builtin.id;
  2761. } else {
  2762. id = BuiltinProc_DIRECTIVE;
  2763. }
  2764. return lb_build_builtin_proc(p, expr, tv, id);
  2765. }
  2766. // NOTE(bill): Regular call
  2767. lbValue value = {};
  2768. Entity *proc_entity = entity_of_node(proc_expr);
  2769. if (proc_entity != nullptr) {
  2770. if (proc_entity->flags & EntityFlag_Disabled) {
  2771. GB_ASSERT(tv.type == nullptr);
  2772. return {};
  2773. }
  2774. }
  2775. if (proc_expr->tav.mode == Addressing_Constant) {
  2776. ExactValue v = proc_expr->tav.value;
  2777. switch (v.kind) {
  2778. case ExactValue_Integer:
  2779. {
  2780. u64 u = big_int_to_u64(&v.value_integer);
  2781. lbValue x = {};
  2782. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2783. x.type = t_uintptr;
  2784. x = lb_emit_conv(p, x, t_rawptr);
  2785. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2786. break;
  2787. }
  2788. case ExactValue_Pointer:
  2789. {
  2790. u64 u = cast(u64)v.value_pointer;
  2791. lbValue x = {};
  2792. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2793. x.type = t_uintptr;
  2794. x = lb_emit_conv(p, x, t_rawptr);
  2795. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2796. break;
  2797. }
  2798. }
  2799. }
  2800. if (value.value == nullptr) {
  2801. value = lb_build_expr(p, proc_expr);
  2802. }
  2803. GB_ASSERT(value.value != nullptr);
  2804. Type *proc_type_ = base_type(value.type);
  2805. GB_ASSERT(proc_type_->kind == Type_Proc);
  2806. TypeProc *pt = &proc_type_->Proc;
  2807. GB_ASSERT(ce->split_args != nullptr);
  2808. auto args = array_make<lbValue>(permanent_allocator(), 0, pt->param_count);
  2809. bool vari_expand = (ce->ellipsis.pos.line != 0);
  2810. bool is_c_vararg = pt->c_vararg;
  2811. for_array(i, ce->split_args->positional) {
  2812. Entity *e = pt->params->Tuple.variables[i];
  2813. if (e->kind == Entity_TypeName) {
  2814. array_add(&args, lb_const_nil(p->module, e->type));
  2815. continue;
  2816. } else if (e->kind == Entity_Constant) {
  2817. array_add(&args, lb_const_value(p->module, e->type, e->Constant.value));
  2818. continue;
  2819. }
  2820. GB_ASSERT(e->kind == Entity_Variable);
  2821. if (pt->variadic && pt->variadic_index == i) {
  2822. lbValue variadic_args = lb_const_nil(p->module, e->type);
  2823. auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count);
  2824. if (variadic.count != 0) {
  2825. // variadic call argument generation
  2826. Type *slice_type = e->type;
  2827. GB_ASSERT(slice_type->kind == Type_Slice);
  2828. if (is_c_vararg) {
  2829. GB_ASSERT(!vari_expand);
  2830. Type *elem_type = slice_type->Slice.elem;
  2831. for (Ast *var_arg : variadic) {
  2832. lbValue arg = lb_build_expr(p, var_arg);
  2833. if (is_type_any(elem_type)) {
  2834. array_add(&args, lb_emit_conv(p, arg, default_type(arg.type)));
  2835. } else {
  2836. array_add(&args, lb_emit_conv(p, arg, elem_type));
  2837. }
  2838. }
  2839. break;
  2840. } else if (vari_expand) {
  2841. GB_ASSERT(variadic.count == 1);
  2842. variadic_args = lb_build_expr(p, variadic[0]);
  2843. variadic_args = lb_emit_conv(p, variadic_args, slice_type);
  2844. } else {
  2845. Type *elem_type = slice_type->Slice.elem;
  2846. auto var_args = array_make<lbValue>(heap_allocator(), 0, variadic.count);
  2847. defer (array_free(&var_args));
  2848. for (Ast *var_arg : variadic) {
  2849. lbValue v = lb_build_expr(p, var_arg);
  2850. lb_add_values_to_array(p, &var_args, v);
  2851. }
  2852. isize slice_len = var_args.count;
  2853. if (slice_len > 0) {
  2854. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  2855. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  2856. for (isize i = 0; i < var_args.count; i++) {
  2857. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)i);
  2858. lbValue var_arg = var_args[i];
  2859. var_arg = lb_emit_conv(p, var_arg, elem_type);
  2860. lb_emit_store(p, addr, var_arg);
  2861. }
  2862. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  2863. lbValue len = lb_const_int(p->module, t_int, slice_len);
  2864. lb_fill_slice(p, slice, base_elem, len);
  2865. variadic_args = lb_addr_load(p, slice);
  2866. }
  2867. }
  2868. }
  2869. array_add(&args, variadic_args);
  2870. break;
  2871. } else {
  2872. lbValue value = lb_build_expr(p, ce->split_args->positional[i]);
  2873. lb_add_values_to_array(p, &args, value);
  2874. }
  2875. }
  2876. if (!is_c_vararg) {
  2877. array_resize(&args, pt->param_count);
  2878. }
  2879. for (Ast *arg : ce->split_args->named) {
  2880. ast_node(fv, FieldValue, arg);
  2881. GB_ASSERT(fv->field->kind == Ast_Ident);
  2882. String name = fv->field->Ident.token.string;
  2883. gb_unused(name);
  2884. isize param_index = lookup_procedure_parameter(pt, name);
  2885. GB_ASSERT(param_index >= 0);
  2886. Entity *e = pt->params->Tuple.variables[param_index];
  2887. if (e->kind == Entity_TypeName) {
  2888. lbValue value = lb_const_nil(p->module, e->type);
  2889. args[param_index] = value;
  2890. } else {
  2891. lbValue value = lb_build_expr(p, fv->value);
  2892. GB_ASSERT(!is_type_tuple(value.type));
  2893. args[param_index] = value;
  2894. }
  2895. }
  2896. TokenPos pos = ast_token(ce->proc).pos;
  2897. if (pt->params != nullptr) {
  2898. isize min_count = pt->params->Tuple.variables.count;
  2899. if (is_c_vararg) {
  2900. min_count -= 1;
  2901. }
  2902. GB_ASSERT(args.count >= min_count);
  2903. for_array(arg_index, pt->params->Tuple.variables) {
  2904. Entity *e = pt->params->Tuple.variables[arg_index];
  2905. if (pt->variadic && arg_index == pt->variadic_index) {
  2906. if (!is_c_vararg && args[arg_index].value == 0) {
  2907. args[arg_index] = lb_const_nil(p->module, e->type);
  2908. }
  2909. continue;
  2910. }
  2911. lbValue arg = args[arg_index];
  2912. if (arg.value == nullptr) {
  2913. switch (e->kind) {
  2914. case Entity_TypeName:
  2915. args[arg_index] = lb_const_nil(p->module, e->type);
  2916. break;
  2917. case Entity_Variable:
  2918. args[arg_index] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  2919. break;
  2920. case Entity_Constant:
  2921. args[arg_index] = lb_const_value(p->module, e->type, e->Constant.value);
  2922. break;
  2923. default:
  2924. GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind]));
  2925. }
  2926. } else {
  2927. args[arg_index] = lb_emit_conv(p, arg, e->type);
  2928. }
  2929. }
  2930. }
  2931. isize final_count = is_c_vararg ? args.count : pt->param_count;
  2932. auto call_args = array_slice(args, 0, final_count);
  2933. return lb_emit_call(p, value, call_args, ce->inlining);
  2934. }