CGCall.cpp 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575
  1. //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // These classes wrap the information about a call or function
  10. // definition used to handle ABI compliancy.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCall.h"
  14. #include "ABIInfo.h"
  15. #include "CGBlocks.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCleanup.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/Basic/CodeGenOptions.h"
  25. #include "clang/Basic/TargetBuiltins.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "clang/CodeGen/SwiftCallingConv.h"
  29. #include "llvm/ADT/StringExtras.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/IR/Attributes.h"
  33. #include "llvm/IR/CallingConv.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/InlineAsm.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. using namespace clang;
  39. using namespace CodeGen;
  40. /***/
  41. unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
  42. switch (CC) {
  43. default: return llvm::CallingConv::C;
  44. case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
  45. case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
  46. case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
  47. case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
  48. case CC_Win64: return llvm::CallingConv::Win64;
  49. case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
  50. case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
  51. case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  52. case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
  53. // TODO: Add support for __pascal to LLVM.
  54. case CC_X86Pascal: return llvm::CallingConv::C;
  55. // TODO: Add support for __vectorcall to LLVM.
  56. case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
  57. case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
  58. case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
  59. case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
  60. case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
  61. case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
  62. case CC_Swift: return llvm::CallingConv::Swift;
  63. }
  64. }
  65. /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
  66. /// qualification. Either or both of RD and MD may be null. A null RD indicates
  67. /// that there is no meaningful 'this' type, and a null MD can occur when
  68. /// calling a method pointer.
  69. CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
  70. const CXXMethodDecl *MD) {
  71. QualType RecTy;
  72. if (RD)
  73. RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
  74. else
  75. RecTy = Context.VoidTy;
  76. if (MD)
  77. RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
  78. return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
  79. }
  80. /// Returns the canonical formal type of the given C++ method.
  81. static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
  82. return MD->getType()->getCanonicalTypeUnqualified()
  83. .getAs<FunctionProtoType>();
  84. }
  85. /// Returns the "extra-canonicalized" return type, which discards
  86. /// qualifiers on the return type. Codegen doesn't care about them,
  87. /// and it makes ABI code a little easier to be able to assume that
  88. /// all parameter and return types are top-level unqualified.
  89. static CanQualType GetReturnType(QualType RetTy) {
  90. return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
  91. }
  92. /// Arrange the argument and result information for a value of the given
  93. /// unprototyped freestanding function type.
  94. const CGFunctionInfo &
  95. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
  96. // When translating an unprototyped function type, always use a
  97. // variadic type.
  98. return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
  99. /*instanceMethod=*/false,
  100. /*chainCall=*/false, None,
  101. FTNP->getExtInfo(), {}, RequiredArgs(0));
  102. }
  103. static void addExtParameterInfosForCall(
  104. llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  105. const FunctionProtoType *proto,
  106. unsigned prefixArgs,
  107. unsigned totalArgs) {
  108. assert(proto->hasExtParameterInfos());
  109. assert(paramInfos.size() <= prefixArgs);
  110. assert(proto->getNumParams() + prefixArgs <= totalArgs);
  111. paramInfos.reserve(totalArgs);
  112. // Add default infos for any prefix args that don't already have infos.
  113. paramInfos.resize(prefixArgs);
  114. // Add infos for the prototype.
  115. for (const auto &ParamInfo : proto->getExtParameterInfos()) {
  116. paramInfos.push_back(ParamInfo);
  117. // pass_object_size params have no parameter info.
  118. if (ParamInfo.hasPassObjectSize())
  119. paramInfos.emplace_back();
  120. }
  121. assert(paramInfos.size() <= totalArgs &&
  122. "Did we forget to insert pass_object_size args?");
  123. // Add default infos for the variadic and/or suffix arguments.
  124. paramInfos.resize(totalArgs);
  125. }
  126. /// Adds the formal parameters in FPT to the given prefix. If any parameter in
  127. /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
  128. static void appendParameterTypes(const CodeGenTypes &CGT,
  129. SmallVectorImpl<CanQualType> &prefix,
  130. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  131. CanQual<FunctionProtoType> FPT) {
  132. // Fast path: don't touch param info if we don't need to.
  133. if (!FPT->hasExtParameterInfos()) {
  134. assert(paramInfos.empty() &&
  135. "We have paramInfos, but the prototype doesn't?");
  136. prefix.append(FPT->param_type_begin(), FPT->param_type_end());
  137. return;
  138. }
  139. unsigned PrefixSize = prefix.size();
  140. // In the vast majority of cases, we'll have precisely FPT->getNumParams()
  141. // parameters; the only thing that can change this is the presence of
  142. // pass_object_size. So, we preallocate for the common case.
  143. prefix.reserve(prefix.size() + FPT->getNumParams());
  144. auto ExtInfos = FPT->getExtParameterInfos();
  145. assert(ExtInfos.size() == FPT->getNumParams());
  146. for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
  147. prefix.push_back(FPT->getParamType(I));
  148. if (ExtInfos[I].hasPassObjectSize())
  149. prefix.push_back(CGT.getContext().getSizeType());
  150. }
  151. addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
  152. prefix.size());
  153. }
  154. /// Arrange the LLVM function layout for a value of the given function
  155. /// type, on top of any implicit parameters already stored.
  156. static const CGFunctionInfo &
  157. arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
  158. SmallVectorImpl<CanQualType> &prefix,
  159. CanQual<FunctionProtoType> FTP) {
  160. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  161. RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
  162. // FIXME: Kill copy.
  163. appendParameterTypes(CGT, prefix, paramInfos, FTP);
  164. CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
  165. return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
  166. /*chainCall=*/false, prefix,
  167. FTP->getExtInfo(), paramInfos,
  168. Required);
  169. }
  170. /// Arrange the argument and result information for a value of the
  171. /// given freestanding function type.
  172. const CGFunctionInfo &
  173. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
  174. SmallVector<CanQualType, 16> argTypes;
  175. return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
  176. FTP);
  177. }
  178. static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
  179. // Set the appropriate calling convention for the Function.
  180. if (D->hasAttr<StdCallAttr>())
  181. return CC_X86StdCall;
  182. if (D->hasAttr<FastCallAttr>())
  183. return CC_X86FastCall;
  184. if (D->hasAttr<RegCallAttr>())
  185. return CC_X86RegCall;
  186. if (D->hasAttr<ThisCallAttr>())
  187. return CC_X86ThisCall;
  188. if (D->hasAttr<VectorCallAttr>())
  189. return CC_X86VectorCall;
  190. if (D->hasAttr<PascalAttr>())
  191. return CC_X86Pascal;
  192. if (PcsAttr *PCS = D->getAttr<PcsAttr>())
  193. return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
  194. if (D->hasAttr<AArch64VectorPcsAttr>())
  195. return CC_AArch64VectorCall;
  196. if (D->hasAttr<IntelOclBiccAttr>())
  197. return CC_IntelOclBicc;
  198. if (D->hasAttr<MSABIAttr>())
  199. return IsWindows ? CC_C : CC_Win64;
  200. if (D->hasAttr<SysVABIAttr>())
  201. return IsWindows ? CC_X86_64SysV : CC_C;
  202. if (D->hasAttr<PreserveMostAttr>())
  203. return CC_PreserveMost;
  204. if (D->hasAttr<PreserveAllAttr>())
  205. return CC_PreserveAll;
  206. return CC_C;
  207. }
  208. /// Arrange the argument and result information for a call to an
  209. /// unknown C++ non-static member function of the given abstract type.
  210. /// (A null RD means we don't have any meaningful "this" argument type,
  211. /// so fall back to a generic pointer type).
  212. /// The member function must be an ordinary function, i.e. not a
  213. /// constructor or destructor.
  214. const CGFunctionInfo &
  215. CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
  216. const FunctionProtoType *FTP,
  217. const CXXMethodDecl *MD) {
  218. SmallVector<CanQualType, 16> argTypes;
  219. // Add the 'this' pointer.
  220. argTypes.push_back(DeriveThisType(RD, MD));
  221. return ::arrangeLLVMFunctionInfo(
  222. *this, true, argTypes,
  223. FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
  224. }
  225. /// Set calling convention for CUDA/HIP kernel.
  226. static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
  227. const FunctionDecl *FD) {
  228. if (FD->hasAttr<CUDAGlobalAttr>()) {
  229. const FunctionType *FT = FTy->getAs<FunctionType>();
  230. CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
  231. FTy = FT->getCanonicalTypeUnqualified();
  232. }
  233. }
  234. /// Arrange the argument and result information for a declaration or
  235. /// definition of the given C++ non-static member function. The
  236. /// member function must be an ordinary function, i.e. not a
  237. /// constructor or destructor.
  238. const CGFunctionInfo &
  239. CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
  240. assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
  241. assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
  242. CanQualType FT = GetFormalType(MD).getAs<Type>();
  243. setCUDAKernelCallingConvention(FT, CGM, MD);
  244. auto prototype = FT.getAs<FunctionProtoType>();
  245. if (MD->isInstance()) {
  246. // The abstract case is perfectly fine.
  247. const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
  248. return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
  249. }
  250. return arrangeFreeFunctionType(prototype);
  251. }
  252. bool CodeGenTypes::inheritingCtorHasParams(
  253. const InheritedConstructor &Inherited, CXXCtorType Type) {
  254. // Parameters are unnecessary if we're constructing a base class subobject
  255. // and the inherited constructor lives in a virtual base.
  256. return Type == Ctor_Complete ||
  257. !Inherited.getShadowDecl()->constructsVirtualBase() ||
  258. !Target.getCXXABI().hasConstructorVariants();
  259. }
  260. const CGFunctionInfo &
  261. CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
  262. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  263. SmallVector<CanQualType, 16> argTypes;
  264. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  265. argTypes.push_back(DeriveThisType(MD->getParent(), MD));
  266. bool PassParams = true;
  267. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  268. // A base class inheriting constructor doesn't get forwarded arguments
  269. // needed to construct a virtual base (or base class thereof).
  270. if (auto Inherited = CD->getInheritedConstructor())
  271. PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
  272. }
  273. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  274. // Add the formal parameters.
  275. if (PassParams)
  276. appendParameterTypes(*this, argTypes, paramInfos, FTP);
  277. CGCXXABI::AddedStructorArgs AddedArgs =
  278. TheCXXABI.buildStructorSignature(GD, argTypes);
  279. if (!paramInfos.empty()) {
  280. // Note: prefix implies after the first param.
  281. if (AddedArgs.Prefix)
  282. paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
  283. FunctionProtoType::ExtParameterInfo{});
  284. if (AddedArgs.Suffix)
  285. paramInfos.append(AddedArgs.Suffix,
  286. FunctionProtoType::ExtParameterInfo{});
  287. }
  288. RequiredArgs required =
  289. (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
  290. : RequiredArgs::All);
  291. FunctionType::ExtInfo extInfo = FTP->getExtInfo();
  292. CanQualType resultType = TheCXXABI.HasThisReturn(GD)
  293. ? argTypes.front()
  294. : TheCXXABI.hasMostDerivedReturn(GD)
  295. ? CGM.getContext().VoidPtrTy
  296. : Context.VoidTy;
  297. return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
  298. /*chainCall=*/false, argTypes, extInfo,
  299. paramInfos, required);
  300. }
  301. static SmallVector<CanQualType, 16>
  302. getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
  303. SmallVector<CanQualType, 16> argTypes;
  304. for (auto &arg : args)
  305. argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
  306. return argTypes;
  307. }
  308. static SmallVector<CanQualType, 16>
  309. getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
  310. SmallVector<CanQualType, 16> argTypes;
  311. for (auto &arg : args)
  312. argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
  313. return argTypes;
  314. }
  315. static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
  316. getExtParameterInfosForCall(const FunctionProtoType *proto,
  317. unsigned prefixArgs, unsigned totalArgs) {
  318. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
  319. if (proto->hasExtParameterInfos()) {
  320. addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
  321. }
  322. return result;
  323. }
  324. /// Arrange a call to a C++ method, passing the given arguments.
  325. ///
  326. /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
  327. /// parameter.
  328. /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
  329. /// args.
  330. /// PassProtoArgs indicates whether `args` has args for the parameters in the
  331. /// given CXXConstructorDecl.
  332. const CGFunctionInfo &
  333. CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
  334. const CXXConstructorDecl *D,
  335. CXXCtorType CtorKind,
  336. unsigned ExtraPrefixArgs,
  337. unsigned ExtraSuffixArgs,
  338. bool PassProtoArgs) {
  339. // FIXME: Kill copy.
  340. SmallVector<CanQualType, 16> ArgTypes;
  341. for (const auto &Arg : args)
  342. ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  343. // +1 for implicit this, which should always be args[0].
  344. unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
  345. CanQual<FunctionProtoType> FPT = GetFormalType(D);
  346. RequiredArgs Required = PassProtoArgs
  347. ? RequiredArgs::forPrototypePlus(
  348. FPT, TotalPrefixArgs + ExtraSuffixArgs)
  349. : RequiredArgs::All;
  350. GlobalDecl GD(D, CtorKind);
  351. CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
  352. ? ArgTypes.front()
  353. : TheCXXABI.hasMostDerivedReturn(GD)
  354. ? CGM.getContext().VoidPtrTy
  355. : Context.VoidTy;
  356. FunctionType::ExtInfo Info = FPT->getExtInfo();
  357. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
  358. // If the prototype args are elided, we should only have ABI-specific args,
  359. // which never have param info.
  360. if (PassProtoArgs && FPT->hasExtParameterInfos()) {
  361. // ABI-specific suffix arguments are treated the same as variadic arguments.
  362. addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
  363. ArgTypes.size());
  364. }
  365. return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  366. /*chainCall=*/false, ArgTypes, Info,
  367. ParamInfos, Required);
  368. }
  369. /// Arrange the argument and result information for the declaration or
  370. /// definition of the given function.
  371. const CGFunctionInfo &
  372. CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
  373. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  374. if (MD->isInstance())
  375. return arrangeCXXMethodDeclaration(MD);
  376. CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
  377. assert(isa<FunctionType>(FTy));
  378. setCUDAKernelCallingConvention(FTy, CGM, FD);
  379. // When declaring a function without a prototype, always use a
  380. // non-variadic type.
  381. if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
  382. return arrangeLLVMFunctionInfo(
  383. noProto->getReturnType(), /*instanceMethod=*/false,
  384. /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
  385. }
  386. return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
  387. }
  388. /// Arrange the argument and result information for the declaration or
  389. /// definition of an Objective-C method.
  390. const CGFunctionInfo &
  391. CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
  392. // It happens that this is the same as a call with no optional
  393. // arguments, except also using the formal 'self' type.
  394. return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
  395. }
  396. /// Arrange the argument and result information for the function type
  397. /// through which to perform a send to the given Objective-C method,
  398. /// using the given receiver type. The receiver type is not always
  399. /// the 'self' type of the method or even an Objective-C pointer type.
  400. /// This is *not* the right method for actually performing such a
  401. /// message send, due to the possibility of optional arguments.
  402. const CGFunctionInfo &
  403. CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
  404. QualType receiverType) {
  405. SmallVector<CanQualType, 16> argTys;
  406. SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
  407. argTys.push_back(Context.getCanonicalParamType(receiverType));
  408. argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
  409. // FIXME: Kill copy?
  410. for (const auto *I : MD->parameters()) {
  411. argTys.push_back(Context.getCanonicalParamType(I->getType()));
  412. auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
  413. I->hasAttr<NoEscapeAttr>());
  414. extParamInfos.push_back(extParamInfo);
  415. }
  416. FunctionType::ExtInfo einfo;
  417. bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
  418. einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
  419. if (getContext().getLangOpts().ObjCAutoRefCount &&
  420. MD->hasAttr<NSReturnsRetainedAttr>())
  421. einfo = einfo.withProducesResult(true);
  422. RequiredArgs required =
  423. (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
  424. return arrangeLLVMFunctionInfo(
  425. GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
  426. /*chainCall=*/false, argTys, einfo, extParamInfos, required);
  427. }
  428. const CGFunctionInfo &
  429. CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
  430. const CallArgList &args) {
  431. auto argTypes = getArgTypesForCall(Context, args);
  432. FunctionType::ExtInfo einfo;
  433. return arrangeLLVMFunctionInfo(
  434. GetReturnType(returnType), /*instanceMethod=*/false,
  435. /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
  436. }
  437. const CGFunctionInfo &
  438. CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
  439. // FIXME: Do we need to handle ObjCMethodDecl?
  440. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  441. if (isa<CXXConstructorDecl>(GD.getDecl()) ||
  442. isa<CXXDestructorDecl>(GD.getDecl()))
  443. return arrangeCXXStructorDeclaration(GD);
  444. return arrangeFunctionDeclaration(FD);
  445. }
  446. /// Arrange a thunk that takes 'this' as the first parameter followed by
  447. /// varargs. Return a void pointer, regardless of the actual return type.
  448. /// The body of the thunk will end in a musttail call to a function of the
  449. /// correct type, and the caller will bitcast the function to the correct
  450. /// prototype.
  451. const CGFunctionInfo &
  452. CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
  453. assert(MD->isVirtual() && "only methods have thunks");
  454. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  455. CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
  456. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
  457. /*chainCall=*/false, ArgTys,
  458. FTP->getExtInfo(), {}, RequiredArgs(1));
  459. }
  460. const CGFunctionInfo &
  461. CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
  462. CXXCtorType CT) {
  463. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  464. CanQual<FunctionProtoType> FTP = GetFormalType(CD);
  465. SmallVector<CanQualType, 2> ArgTys;
  466. const CXXRecordDecl *RD = CD->getParent();
  467. ArgTys.push_back(DeriveThisType(RD, CD));
  468. if (CT == Ctor_CopyingClosure)
  469. ArgTys.push_back(*FTP->param_type_begin());
  470. if (RD->getNumVBases() > 0)
  471. ArgTys.push_back(Context.IntTy);
  472. CallingConv CC = Context.getDefaultCallingConvention(
  473. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  474. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
  475. /*chainCall=*/false, ArgTys,
  476. FunctionType::ExtInfo(CC), {},
  477. RequiredArgs::All);
  478. }
  479. /// Arrange a call as unto a free function, except possibly with an
  480. /// additional number of formal parameters considered required.
  481. static const CGFunctionInfo &
  482. arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
  483. CodeGenModule &CGM,
  484. const CallArgList &args,
  485. const FunctionType *fnType,
  486. unsigned numExtraRequiredArgs,
  487. bool chainCall) {
  488. assert(args.size() >= numExtraRequiredArgs);
  489. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  490. // In most cases, there are no optional arguments.
  491. RequiredArgs required = RequiredArgs::All;
  492. // If we have a variadic prototype, the required arguments are the
  493. // extra prefix plus the arguments in the prototype.
  494. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
  495. if (proto->isVariadic())
  496. required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
  497. if (proto->hasExtParameterInfos())
  498. addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
  499. args.size());
  500. // If we don't have a prototype at all, but we're supposed to
  501. // explicitly use the variadic convention for unprototyped calls,
  502. // treat all of the arguments as required but preserve the nominal
  503. // possibility of variadics.
  504. } else if (CGM.getTargetCodeGenInfo()
  505. .isNoProtoCallVariadic(args,
  506. cast<FunctionNoProtoType>(fnType))) {
  507. required = RequiredArgs(args.size());
  508. }
  509. // FIXME: Kill copy.
  510. SmallVector<CanQualType, 16> argTypes;
  511. for (const auto &arg : args)
  512. argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
  513. return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
  514. /*instanceMethod=*/false, chainCall,
  515. argTypes, fnType->getExtInfo(), paramInfos,
  516. required);
  517. }
  518. /// Figure out the rules for calling a function with the given formal
  519. /// type using the given arguments. The arguments are necessary
  520. /// because the function might be unprototyped, in which case it's
  521. /// target-dependent in crazy ways.
  522. const CGFunctionInfo &
  523. CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
  524. const FunctionType *fnType,
  525. bool chainCall) {
  526. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
  527. chainCall ? 1 : 0, chainCall);
  528. }
  529. /// A block function is essentially a free function with an
  530. /// extra implicit argument.
  531. const CGFunctionInfo &
  532. CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
  533. const FunctionType *fnType) {
  534. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
  535. /*chainCall=*/false);
  536. }
  537. const CGFunctionInfo &
  538. CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
  539. const FunctionArgList &params) {
  540. auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
  541. auto argTypes = getArgTypesForDeclaration(Context, params);
  542. return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
  543. /*instanceMethod*/ false, /*chainCall*/ false,
  544. argTypes, proto->getExtInfo(), paramInfos,
  545. RequiredArgs::forPrototypePlus(proto, 1));
  546. }
  547. const CGFunctionInfo &
  548. CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
  549. const CallArgList &args) {
  550. // FIXME: Kill copy.
  551. SmallVector<CanQualType, 16> argTypes;
  552. for (const auto &Arg : args)
  553. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  554. return arrangeLLVMFunctionInfo(
  555. GetReturnType(resultType), /*instanceMethod=*/false,
  556. /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
  557. /*paramInfos=*/ {}, RequiredArgs::All);
  558. }
  559. const CGFunctionInfo &
  560. CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
  561. const FunctionArgList &args) {
  562. auto argTypes = getArgTypesForDeclaration(Context, args);
  563. return arrangeLLVMFunctionInfo(
  564. GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
  565. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  566. }
  567. const CGFunctionInfo &
  568. CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
  569. ArrayRef<CanQualType> argTypes) {
  570. return arrangeLLVMFunctionInfo(
  571. resultType, /*instanceMethod=*/false, /*chainCall=*/false,
  572. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  573. }
  574. /// Arrange a call to a C++ method, passing the given arguments.
  575. ///
  576. /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
  577. /// does not count `this`.
  578. const CGFunctionInfo &
  579. CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
  580. const FunctionProtoType *proto,
  581. RequiredArgs required,
  582. unsigned numPrefixArgs) {
  583. assert(numPrefixArgs + 1 <= args.size() &&
  584. "Emitting a call with less args than the required prefix?");
  585. // Add one to account for `this`. It's a bit awkward here, but we don't count
  586. // `this` in similar places elsewhere.
  587. auto paramInfos =
  588. getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
  589. // FIXME: Kill copy.
  590. auto argTypes = getArgTypesForCall(Context, args);
  591. FunctionType::ExtInfo info = proto->getExtInfo();
  592. return arrangeLLVMFunctionInfo(
  593. GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
  594. /*chainCall=*/false, argTypes, info, paramInfos, required);
  595. }
  596. const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
  597. return arrangeLLVMFunctionInfo(
  598. getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
  599. None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  600. }
  601. const CGFunctionInfo &
  602. CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
  603. const CallArgList &args) {
  604. assert(signature.arg_size() <= args.size());
  605. if (signature.arg_size() == args.size())
  606. return signature;
  607. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  608. auto sigParamInfos = signature.getExtParameterInfos();
  609. if (!sigParamInfos.empty()) {
  610. paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
  611. paramInfos.resize(args.size());
  612. }
  613. auto argTypes = getArgTypesForCall(Context, args);
  614. assert(signature.getRequiredArgs().allowsOptionalArgs());
  615. return arrangeLLVMFunctionInfo(signature.getReturnType(),
  616. signature.isInstanceMethod(),
  617. signature.isChainCall(),
  618. argTypes,
  619. signature.getExtInfo(),
  620. paramInfos,
  621. signature.getRequiredArgs());
  622. }
  623. namespace clang {
  624. namespace CodeGen {
  625. void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
  626. }
  627. }
  628. /// Arrange the argument and result information for an abstract value
  629. /// of a given function type. This is the method which all of the
  630. /// above functions ultimately defer to.
  631. const CGFunctionInfo &
  632. CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
  633. bool instanceMethod,
  634. bool chainCall,
  635. ArrayRef<CanQualType> argTypes,
  636. FunctionType::ExtInfo info,
  637. ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
  638. RequiredArgs required) {
  639. assert(llvm::all_of(argTypes,
  640. [](CanQualType T) { return T.isCanonicalAsParam(); }));
  641. // Lookup or create unique function info.
  642. llvm::FoldingSetNodeID ID;
  643. CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
  644. required, resultType, argTypes);
  645. void *insertPos = nullptr;
  646. CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
  647. if (FI)
  648. return *FI;
  649. unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
  650. // Construct the function info. We co-allocate the ArgInfos.
  651. FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
  652. paramInfos, resultType, argTypes, required);
  653. FunctionInfos.InsertNode(FI, insertPos);
  654. bool inserted = FunctionsBeingProcessed.insert(FI).second;
  655. (void)inserted;
  656. assert(inserted && "Recursively being processed?");
  657. // Compute ABI information.
  658. if (CC == llvm::CallingConv::SPIR_KERNEL) {
  659. // Force target independent argument handling for the host visible
  660. // kernel functions.
  661. computeSPIRKernelABIInfo(CGM, *FI);
  662. } else if (info.getCC() == CC_Swift) {
  663. swiftcall::computeABIInfo(CGM, *FI);
  664. } else {
  665. getABIInfo().computeInfo(*FI);
  666. }
  667. // Loop over all of the computed argument and return value info. If any of
  668. // them are direct or extend without a specified coerce type, specify the
  669. // default now.
  670. ABIArgInfo &retInfo = FI->getReturnInfo();
  671. if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
  672. retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
  673. for (auto &I : FI->arguments())
  674. if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
  675. I.info.setCoerceToType(ConvertType(I.type));
  676. bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
  677. assert(erased && "Not in set?");
  678. return *FI;
  679. }
  680. CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
  681. bool instanceMethod,
  682. bool chainCall,
  683. const FunctionType::ExtInfo &info,
  684. ArrayRef<ExtParameterInfo> paramInfos,
  685. CanQualType resultType,
  686. ArrayRef<CanQualType> argTypes,
  687. RequiredArgs required) {
  688. assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
  689. assert(!required.allowsOptionalArgs() ||
  690. required.getNumRequiredArgs() <= argTypes.size());
  691. void *buffer =
  692. operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
  693. argTypes.size() + 1, paramInfos.size()));
  694. CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
  695. FI->CallingConvention = llvmCC;
  696. FI->EffectiveCallingConvention = llvmCC;
  697. FI->ASTCallingConvention = info.getCC();
  698. FI->InstanceMethod = instanceMethod;
  699. FI->ChainCall = chainCall;
  700. FI->NoReturn = info.getNoReturn();
  701. FI->ReturnsRetained = info.getProducesResult();
  702. FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
  703. FI->NoCfCheck = info.getNoCfCheck();
  704. FI->Required = required;
  705. FI->HasRegParm = info.getHasRegParm();
  706. FI->RegParm = info.getRegParm();
  707. FI->ArgStruct = nullptr;
  708. FI->ArgStructAlign = 0;
  709. FI->NumArgs = argTypes.size();
  710. FI->HasExtParameterInfos = !paramInfos.empty();
  711. FI->getArgsBuffer()[0].type = resultType;
  712. for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
  713. FI->getArgsBuffer()[i + 1].type = argTypes[i];
  714. for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
  715. FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
  716. return FI;
  717. }
  718. /***/
  719. namespace {
  720. // ABIArgInfo::Expand implementation.
  721. // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
  722. struct TypeExpansion {
  723. enum TypeExpansionKind {
  724. // Elements of constant arrays are expanded recursively.
  725. TEK_ConstantArray,
  726. // Record fields are expanded recursively (but if record is a union, only
  727. // the field with the largest size is expanded).
  728. TEK_Record,
  729. // For complex types, real and imaginary parts are expanded recursively.
  730. TEK_Complex,
  731. // All other types are not expandable.
  732. TEK_None
  733. };
  734. const TypeExpansionKind Kind;
  735. TypeExpansion(TypeExpansionKind K) : Kind(K) {}
  736. virtual ~TypeExpansion() {}
  737. };
  738. struct ConstantArrayExpansion : TypeExpansion {
  739. QualType EltTy;
  740. uint64_t NumElts;
  741. ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
  742. : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
  743. static bool classof(const TypeExpansion *TE) {
  744. return TE->Kind == TEK_ConstantArray;
  745. }
  746. };
  747. struct RecordExpansion : TypeExpansion {
  748. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  749. SmallVector<const FieldDecl *, 1> Fields;
  750. RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
  751. SmallVector<const FieldDecl *, 1> &&Fields)
  752. : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
  753. Fields(std::move(Fields)) {}
  754. static bool classof(const TypeExpansion *TE) {
  755. return TE->Kind == TEK_Record;
  756. }
  757. };
  758. struct ComplexExpansion : TypeExpansion {
  759. QualType EltTy;
  760. ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
  761. static bool classof(const TypeExpansion *TE) {
  762. return TE->Kind == TEK_Complex;
  763. }
  764. };
  765. struct NoExpansion : TypeExpansion {
  766. NoExpansion() : TypeExpansion(TEK_None) {}
  767. static bool classof(const TypeExpansion *TE) {
  768. return TE->Kind == TEK_None;
  769. }
  770. };
  771. } // namespace
  772. static std::unique_ptr<TypeExpansion>
  773. getTypeExpansion(QualType Ty, const ASTContext &Context) {
  774. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  775. return llvm::make_unique<ConstantArrayExpansion>(
  776. AT->getElementType(), AT->getSize().getZExtValue());
  777. }
  778. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  779. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  780. SmallVector<const FieldDecl *, 1> Fields;
  781. const RecordDecl *RD = RT->getDecl();
  782. assert(!RD->hasFlexibleArrayMember() &&
  783. "Cannot expand structure with flexible array.");
  784. if (RD->isUnion()) {
  785. // Unions can be here only in degenerative cases - all the fields are same
  786. // after flattening. Thus we have to use the "largest" field.
  787. const FieldDecl *LargestFD = nullptr;
  788. CharUnits UnionSize = CharUnits::Zero();
  789. for (const auto *FD : RD->fields()) {
  790. if (FD->isZeroLengthBitField(Context))
  791. continue;
  792. assert(!FD->isBitField() &&
  793. "Cannot expand structure with bit-field members.");
  794. CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  795. if (UnionSize < FieldSize) {
  796. UnionSize = FieldSize;
  797. LargestFD = FD;
  798. }
  799. }
  800. if (LargestFD)
  801. Fields.push_back(LargestFD);
  802. } else {
  803. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  804. assert(!CXXRD->isDynamicClass() &&
  805. "cannot expand vtable pointers in dynamic classes");
  806. for (const CXXBaseSpecifier &BS : CXXRD->bases())
  807. Bases.push_back(&BS);
  808. }
  809. for (const auto *FD : RD->fields()) {
  810. if (FD->isZeroLengthBitField(Context))
  811. continue;
  812. assert(!FD->isBitField() &&
  813. "Cannot expand structure with bit-field members.");
  814. Fields.push_back(FD);
  815. }
  816. }
  817. return llvm::make_unique<RecordExpansion>(std::move(Bases),
  818. std::move(Fields));
  819. }
  820. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  821. return llvm::make_unique<ComplexExpansion>(CT->getElementType());
  822. }
  823. return llvm::make_unique<NoExpansion>();
  824. }
  825. static int getExpansionSize(QualType Ty, const ASTContext &Context) {
  826. auto Exp = getTypeExpansion(Ty, Context);
  827. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  828. return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
  829. }
  830. if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  831. int Res = 0;
  832. for (auto BS : RExp->Bases)
  833. Res += getExpansionSize(BS->getType(), Context);
  834. for (auto FD : RExp->Fields)
  835. Res += getExpansionSize(FD->getType(), Context);
  836. return Res;
  837. }
  838. if (isa<ComplexExpansion>(Exp.get()))
  839. return 2;
  840. assert(isa<NoExpansion>(Exp.get()));
  841. return 1;
  842. }
  843. void
  844. CodeGenTypes::getExpandedTypes(QualType Ty,
  845. SmallVectorImpl<llvm::Type *>::iterator &TI) {
  846. auto Exp = getTypeExpansion(Ty, Context);
  847. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  848. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  849. getExpandedTypes(CAExp->EltTy, TI);
  850. }
  851. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  852. for (auto BS : RExp->Bases)
  853. getExpandedTypes(BS->getType(), TI);
  854. for (auto FD : RExp->Fields)
  855. getExpandedTypes(FD->getType(), TI);
  856. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  857. llvm::Type *EltTy = ConvertType(CExp->EltTy);
  858. *TI++ = EltTy;
  859. *TI++ = EltTy;
  860. } else {
  861. assert(isa<NoExpansion>(Exp.get()));
  862. *TI++ = ConvertType(Ty);
  863. }
  864. }
  865. static void forConstantArrayExpansion(CodeGenFunction &CGF,
  866. ConstantArrayExpansion *CAE,
  867. Address BaseAddr,
  868. llvm::function_ref<void(Address)> Fn) {
  869. CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
  870. CharUnits EltAlign =
  871. BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
  872. for (int i = 0, n = CAE->NumElts; i < n; i++) {
  873. llvm::Value *EltAddr =
  874. CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
  875. Fn(Address(EltAddr, EltAlign));
  876. }
  877. }
  878. void CodeGenFunction::ExpandTypeFromArgs(
  879. QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
  880. assert(LV.isSimple() &&
  881. "Unexpected non-simple lvalue during struct expansion.");
  882. auto Exp = getTypeExpansion(Ty, getContext());
  883. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  884. forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
  885. [&](Address EltAddr) {
  886. LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
  887. ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
  888. });
  889. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  890. Address This = LV.getAddress();
  891. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  892. // Perform a single step derived-to-base conversion.
  893. Address Base =
  894. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  895. /*NullCheckValue=*/false, SourceLocation());
  896. LValue SubLV = MakeAddrLValue(Base, BS->getType());
  897. // Recurse onto bases.
  898. ExpandTypeFromArgs(BS->getType(), SubLV, AI);
  899. }
  900. for (auto FD : RExp->Fields) {
  901. // FIXME: What are the right qualifiers here?
  902. LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
  903. ExpandTypeFromArgs(FD->getType(), SubLV, AI);
  904. }
  905. } else if (isa<ComplexExpansion>(Exp.get())) {
  906. auto realValue = *AI++;
  907. auto imagValue = *AI++;
  908. EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
  909. } else {
  910. assert(isa<NoExpansion>(Exp.get()));
  911. EmitStoreThroughLValue(RValue::get(*AI++), LV);
  912. }
  913. }
  914. void CodeGenFunction::ExpandTypeToArgs(
  915. QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  916. SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
  917. auto Exp = getTypeExpansion(Ty, getContext());
  918. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  919. Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
  920. : Arg.getKnownRValue().getAggregateAddress();
  921. forConstantArrayExpansion(
  922. *this, CAExp, Addr, [&](Address EltAddr) {
  923. CallArg EltArg = CallArg(
  924. convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
  925. CAExp->EltTy);
  926. ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
  927. IRCallArgPos);
  928. });
  929. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  930. Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
  931. : Arg.getKnownRValue().getAggregateAddress();
  932. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  933. // Perform a single step derived-to-base conversion.
  934. Address Base =
  935. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  936. /*NullCheckValue=*/false, SourceLocation());
  937. CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
  938. // Recurse onto bases.
  939. ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
  940. IRCallArgPos);
  941. }
  942. LValue LV = MakeAddrLValue(This, Ty);
  943. for (auto FD : RExp->Fields) {
  944. CallArg FldArg =
  945. CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
  946. ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
  947. IRCallArgPos);
  948. }
  949. } else if (isa<ComplexExpansion>(Exp.get())) {
  950. ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
  951. IRCallArgs[IRCallArgPos++] = CV.first;
  952. IRCallArgs[IRCallArgPos++] = CV.second;
  953. } else {
  954. assert(isa<NoExpansion>(Exp.get()));
  955. auto RV = Arg.getKnownRValue();
  956. assert(RV.isScalar() &&
  957. "Unexpected non-scalar rvalue during struct expansion.");
  958. // Insert a bitcast as needed.
  959. llvm::Value *V = RV.getScalarVal();
  960. if (IRCallArgPos < IRFuncTy->getNumParams() &&
  961. V->getType() != IRFuncTy->getParamType(IRCallArgPos))
  962. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
  963. IRCallArgs[IRCallArgPos++] = V;
  964. }
  965. }
  966. /// Create a temporary allocation for the purposes of coercion.
  967. static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
  968. CharUnits MinAlign) {
  969. // Don't use an alignment that's worse than what LLVM would prefer.
  970. auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
  971. CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
  972. return CGF.CreateTempAlloca(Ty, Align);
  973. }
  974. /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
  975. /// accessing some number of bytes out of it, try to gep into the struct to get
  976. /// at its inner goodness. Dive as deep as possible without entering an element
  977. /// with an in-memory size smaller than DstSize.
  978. static Address
  979. EnterStructPointerForCoercedAccess(Address SrcPtr,
  980. llvm::StructType *SrcSTy,
  981. uint64_t DstSize, CodeGenFunction &CGF) {
  982. // We can't dive into a zero-element struct.
  983. if (SrcSTy->getNumElements() == 0) return SrcPtr;
  984. llvm::Type *FirstElt = SrcSTy->getElementType(0);
  985. // If the first elt is at least as large as what we're looking for, or if the
  986. // first element is the same size as the whole struct, we can enter it. The
  987. // comparison must be made on the store size and not the alloca size. Using
  988. // the alloca size may overstate the size of the load.
  989. uint64_t FirstEltSize =
  990. CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
  991. if (FirstEltSize < DstSize &&
  992. FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
  993. return SrcPtr;
  994. // GEP into the first element.
  995. SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
  996. // If the first element is a struct, recurse.
  997. llvm::Type *SrcTy = SrcPtr.getElementType();
  998. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
  999. return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  1000. return SrcPtr;
  1001. }
  1002. /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
  1003. /// are either integers or pointers. This does a truncation of the value if it
  1004. /// is too large or a zero extension if it is too small.
  1005. ///
  1006. /// This behaves as if the value were coerced through memory, so on big-endian
  1007. /// targets the high bits are preserved in a truncation, while little-endian
  1008. /// targets preserve the low bits.
  1009. static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
  1010. llvm::Type *Ty,
  1011. CodeGenFunction &CGF) {
  1012. if (Val->getType() == Ty)
  1013. return Val;
  1014. if (isa<llvm::PointerType>(Val->getType())) {
  1015. // If this is Pointer->Pointer avoid conversion to and from int.
  1016. if (isa<llvm::PointerType>(Ty))
  1017. return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
  1018. // Convert the pointer to an integer so we can play with its width.
  1019. Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
  1020. }
  1021. llvm::Type *DestIntTy = Ty;
  1022. if (isa<llvm::PointerType>(DestIntTy))
  1023. DestIntTy = CGF.IntPtrTy;
  1024. if (Val->getType() != DestIntTy) {
  1025. const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
  1026. if (DL.isBigEndian()) {
  1027. // Preserve the high bits on big-endian targets.
  1028. // That is what memory coercion does.
  1029. uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
  1030. uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
  1031. if (SrcSize > DstSize) {
  1032. Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
  1033. Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
  1034. } else {
  1035. Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
  1036. Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
  1037. }
  1038. } else {
  1039. // Little-endian targets preserve the low bits. No shifts required.
  1040. Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
  1041. }
  1042. }
  1043. if (isa<llvm::PointerType>(Ty))
  1044. Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
  1045. return Val;
  1046. }
  1047. /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
  1048. /// a pointer to an object of type \arg Ty, known to be aligned to
  1049. /// \arg SrcAlign bytes.
  1050. ///
  1051. /// This safely handles the case when the src type is smaller than the
  1052. /// destination type; in this situation the values of bits which not
  1053. /// present in the src are undefined.
  1054. static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
  1055. CodeGenFunction &CGF) {
  1056. llvm::Type *SrcTy = Src.getElementType();
  1057. // If SrcTy and Ty are the same, just do a load.
  1058. if (SrcTy == Ty)
  1059. return CGF.Builder.CreateLoad(Src);
  1060. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
  1061. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
  1062. Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
  1063. SrcTy = Src.getType()->getElementType();
  1064. }
  1065. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1066. // If the source and destination are integer or pointer types, just do an
  1067. // extension or truncation to the desired type.
  1068. if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
  1069. (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
  1070. llvm::Value *Load = CGF.Builder.CreateLoad(Src);
  1071. return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
  1072. }
  1073. // If load is legal, just bitcast the src pointer.
  1074. if (SrcSize >= DstSize) {
  1075. // Generally SrcSize is never greater than DstSize, since this means we are
  1076. // losing bits. However, this can happen in cases where the structure has
  1077. // additional padding, for example due to a user specified alignment.
  1078. //
  1079. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1080. // to that information.
  1081. Src = CGF.Builder.CreateBitCast(Src,
  1082. Ty->getPointerTo(Src.getAddressSpace()));
  1083. return CGF.Builder.CreateLoad(Src);
  1084. }
  1085. // Otherwise do coercion through memory. This is stupid, but simple.
  1086. Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
  1087. Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
  1088. Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty);
  1089. CGF.Builder.CreateMemCpy(Casted, SrcCasted,
  1090. llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
  1091. false);
  1092. return CGF.Builder.CreateLoad(Tmp);
  1093. }
  1094. // Function to store a first-class aggregate into memory. We prefer to
  1095. // store the elements rather than the aggregate to be more friendly to
  1096. // fast-isel.
  1097. // FIXME: Do we need to recurse here?
  1098. static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
  1099. Address Dest, bool DestIsVolatile) {
  1100. // Prefer scalar stores to first-class aggregate stores.
  1101. if (llvm::StructType *STy =
  1102. dyn_cast<llvm::StructType>(Val->getType())) {
  1103. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1104. Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i);
  1105. llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
  1106. CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
  1107. }
  1108. } else {
  1109. CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
  1110. }
  1111. }
  1112. /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
  1113. /// where the source and destination may have different types. The
  1114. /// destination is known to be aligned to \arg DstAlign bytes.
  1115. ///
  1116. /// This safely handles the case when the src type is larger than the
  1117. /// destination type; the upper bits of the src will be lost.
  1118. static void CreateCoercedStore(llvm::Value *Src,
  1119. Address Dst,
  1120. bool DstIsVolatile,
  1121. CodeGenFunction &CGF) {
  1122. llvm::Type *SrcTy = Src->getType();
  1123. llvm::Type *DstTy = Dst.getType()->getElementType();
  1124. if (SrcTy == DstTy) {
  1125. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1126. return;
  1127. }
  1128. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1129. if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
  1130. Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
  1131. DstTy = Dst.getType()->getElementType();
  1132. }
  1133. // If the source and destination are integer or pointer types, just do an
  1134. // extension or truncation to the desired type.
  1135. if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
  1136. (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
  1137. Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
  1138. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1139. return;
  1140. }
  1141. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
  1142. // If store is legal, just bitcast the src pointer.
  1143. if (SrcSize <= DstSize) {
  1144. Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
  1145. BuildAggStore(CGF, Src, Dst, DstIsVolatile);
  1146. } else {
  1147. // Otherwise do coercion through memory. This is stupid, but
  1148. // simple.
  1149. // Generally SrcSize is never greater than DstSize, since this means we are
  1150. // losing bits. However, this can happen in cases where the structure has
  1151. // additional padding, for example due to a user specified alignment.
  1152. //
  1153. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1154. // to that information.
  1155. Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
  1156. CGF.Builder.CreateStore(Src, Tmp);
  1157. Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
  1158. Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty);
  1159. CGF.Builder.CreateMemCpy(DstCasted, Casted,
  1160. llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
  1161. false);
  1162. }
  1163. }
  1164. static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
  1165. const ABIArgInfo &info) {
  1166. if (unsigned offset = info.getDirectOffset()) {
  1167. addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
  1168. addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
  1169. CharUnits::fromQuantity(offset));
  1170. addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
  1171. }
  1172. return addr;
  1173. }
  1174. namespace {
  1175. /// Encapsulates information about the way function arguments from
  1176. /// CGFunctionInfo should be passed to actual LLVM IR function.
  1177. class ClangToLLVMArgMapping {
  1178. static const unsigned InvalidIndex = ~0U;
  1179. unsigned InallocaArgNo;
  1180. unsigned SRetArgNo;
  1181. unsigned TotalIRArgs;
  1182. /// Arguments of LLVM IR function corresponding to single Clang argument.
  1183. struct IRArgs {
  1184. unsigned PaddingArgIndex;
  1185. // Argument is expanded to IR arguments at positions
  1186. // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
  1187. unsigned FirstArgIndex;
  1188. unsigned NumberOfArgs;
  1189. IRArgs()
  1190. : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
  1191. NumberOfArgs(0) {}
  1192. };
  1193. SmallVector<IRArgs, 8> ArgInfo;
  1194. public:
  1195. ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
  1196. bool OnlyRequiredArgs = false)
  1197. : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
  1198. ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
  1199. construct(Context, FI, OnlyRequiredArgs);
  1200. }
  1201. bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
  1202. unsigned getInallocaArgNo() const {
  1203. assert(hasInallocaArg());
  1204. return InallocaArgNo;
  1205. }
  1206. bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
  1207. unsigned getSRetArgNo() const {
  1208. assert(hasSRetArg());
  1209. return SRetArgNo;
  1210. }
  1211. unsigned totalIRArgs() const { return TotalIRArgs; }
  1212. bool hasPaddingArg(unsigned ArgNo) const {
  1213. assert(ArgNo < ArgInfo.size());
  1214. return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
  1215. }
  1216. unsigned getPaddingArgNo(unsigned ArgNo) const {
  1217. assert(hasPaddingArg(ArgNo));
  1218. return ArgInfo[ArgNo].PaddingArgIndex;
  1219. }
  1220. /// Returns index of first IR argument corresponding to ArgNo, and their
  1221. /// quantity.
  1222. std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
  1223. assert(ArgNo < ArgInfo.size());
  1224. return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
  1225. ArgInfo[ArgNo].NumberOfArgs);
  1226. }
  1227. private:
  1228. void construct(const ASTContext &Context, const CGFunctionInfo &FI,
  1229. bool OnlyRequiredArgs);
  1230. };
  1231. void ClangToLLVMArgMapping::construct(const ASTContext &Context,
  1232. const CGFunctionInfo &FI,
  1233. bool OnlyRequiredArgs) {
  1234. unsigned IRArgNo = 0;
  1235. bool SwapThisWithSRet = false;
  1236. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1237. if (RetAI.getKind() == ABIArgInfo::Indirect) {
  1238. SwapThisWithSRet = RetAI.isSRetAfterThis();
  1239. SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
  1240. }
  1241. unsigned ArgNo = 0;
  1242. unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
  1243. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
  1244. ++I, ++ArgNo) {
  1245. assert(I != FI.arg_end());
  1246. QualType ArgType = I->type;
  1247. const ABIArgInfo &AI = I->info;
  1248. // Collect data about IR arguments corresponding to Clang argument ArgNo.
  1249. auto &IRArgs = ArgInfo[ArgNo];
  1250. if (AI.getPaddingType())
  1251. IRArgs.PaddingArgIndex = IRArgNo++;
  1252. switch (AI.getKind()) {
  1253. case ABIArgInfo::Extend:
  1254. case ABIArgInfo::Direct: {
  1255. // FIXME: handle sseregparm someday...
  1256. llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
  1257. if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
  1258. IRArgs.NumberOfArgs = STy->getNumElements();
  1259. } else {
  1260. IRArgs.NumberOfArgs = 1;
  1261. }
  1262. break;
  1263. }
  1264. case ABIArgInfo::Indirect:
  1265. IRArgs.NumberOfArgs = 1;
  1266. break;
  1267. case ABIArgInfo::Ignore:
  1268. case ABIArgInfo::InAlloca:
  1269. // ignore and inalloca doesn't have matching LLVM parameters.
  1270. IRArgs.NumberOfArgs = 0;
  1271. break;
  1272. case ABIArgInfo::CoerceAndExpand:
  1273. IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
  1274. break;
  1275. case ABIArgInfo::Expand:
  1276. IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
  1277. break;
  1278. }
  1279. if (IRArgs.NumberOfArgs > 0) {
  1280. IRArgs.FirstArgIndex = IRArgNo;
  1281. IRArgNo += IRArgs.NumberOfArgs;
  1282. }
  1283. // Skip over the sret parameter when it comes second. We already handled it
  1284. // above.
  1285. if (IRArgNo == 1 && SwapThisWithSRet)
  1286. IRArgNo++;
  1287. }
  1288. assert(ArgNo == ArgInfo.size());
  1289. if (FI.usesInAlloca())
  1290. InallocaArgNo = IRArgNo++;
  1291. TotalIRArgs = IRArgNo;
  1292. }
  1293. } // namespace
  1294. /***/
  1295. bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
  1296. const auto &RI = FI.getReturnInfo();
  1297. return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
  1298. }
  1299. bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
  1300. return ReturnTypeUsesSRet(FI) &&
  1301. getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
  1302. }
  1303. bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
  1304. if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
  1305. switch (BT->getKind()) {
  1306. default:
  1307. return false;
  1308. case BuiltinType::Float:
  1309. return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
  1310. case BuiltinType::Double:
  1311. return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
  1312. case BuiltinType::LongDouble:
  1313. return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
  1314. }
  1315. }
  1316. return false;
  1317. }
  1318. bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
  1319. if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
  1320. if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
  1321. if (BT->getKind() == BuiltinType::LongDouble)
  1322. return getTarget().useObjCFP2RetForComplexLongDouble();
  1323. }
  1324. }
  1325. return false;
  1326. }
  1327. llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
  1328. const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
  1329. return GetFunctionType(FI);
  1330. }
  1331. llvm::FunctionType *
  1332. CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  1333. bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
  1334. (void)Inserted;
  1335. assert(Inserted && "Recursively being processed?");
  1336. llvm::Type *resultType = nullptr;
  1337. const ABIArgInfo &retAI = FI.getReturnInfo();
  1338. switch (retAI.getKind()) {
  1339. case ABIArgInfo::Expand:
  1340. llvm_unreachable("Invalid ABI kind for return argument");
  1341. case ABIArgInfo::Extend:
  1342. case ABIArgInfo::Direct:
  1343. resultType = retAI.getCoerceToType();
  1344. break;
  1345. case ABIArgInfo::InAlloca:
  1346. if (retAI.getInAllocaSRet()) {
  1347. // sret things on win32 aren't void, they return the sret pointer.
  1348. QualType ret = FI.getReturnType();
  1349. llvm::Type *ty = ConvertType(ret);
  1350. unsigned addressSpace = Context.getTargetAddressSpace(ret);
  1351. resultType = llvm::PointerType::get(ty, addressSpace);
  1352. } else {
  1353. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1354. }
  1355. break;
  1356. case ABIArgInfo::Indirect:
  1357. case ABIArgInfo::Ignore:
  1358. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1359. break;
  1360. case ABIArgInfo::CoerceAndExpand:
  1361. resultType = retAI.getUnpaddedCoerceAndExpandType();
  1362. break;
  1363. }
  1364. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
  1365. SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
  1366. // Add type for sret argument.
  1367. if (IRFunctionArgs.hasSRetArg()) {
  1368. QualType Ret = FI.getReturnType();
  1369. llvm::Type *Ty = ConvertType(Ret);
  1370. unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
  1371. ArgTypes[IRFunctionArgs.getSRetArgNo()] =
  1372. llvm::PointerType::get(Ty, AddressSpace);
  1373. }
  1374. // Add type for inalloca argument.
  1375. if (IRFunctionArgs.hasInallocaArg()) {
  1376. auto ArgStruct = FI.getArgStruct();
  1377. assert(ArgStruct);
  1378. ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
  1379. }
  1380. // Add in all of the required arguments.
  1381. unsigned ArgNo = 0;
  1382. CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
  1383. ie = it + FI.getNumRequiredArgs();
  1384. for (; it != ie; ++it, ++ArgNo) {
  1385. const ABIArgInfo &ArgInfo = it->info;
  1386. // Insert a padding type to ensure proper alignment.
  1387. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  1388. ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1389. ArgInfo.getPaddingType();
  1390. unsigned FirstIRArg, NumIRArgs;
  1391. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1392. switch (ArgInfo.getKind()) {
  1393. case ABIArgInfo::Ignore:
  1394. case ABIArgInfo::InAlloca:
  1395. assert(NumIRArgs == 0);
  1396. break;
  1397. case ABIArgInfo::Indirect: {
  1398. assert(NumIRArgs == 1);
  1399. // indirect arguments are always on the stack, which is alloca addr space.
  1400. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1401. ArgTypes[FirstIRArg] = LTy->getPointerTo(
  1402. CGM.getDataLayout().getAllocaAddrSpace());
  1403. break;
  1404. }
  1405. case ABIArgInfo::Extend:
  1406. case ABIArgInfo::Direct: {
  1407. // Fast-isel and the optimizer generally like scalar values better than
  1408. // FCAs, so we flatten them if this is safe to do for this argument.
  1409. llvm::Type *argType = ArgInfo.getCoerceToType();
  1410. llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
  1411. if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  1412. assert(NumIRArgs == st->getNumElements());
  1413. for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
  1414. ArgTypes[FirstIRArg + i] = st->getElementType(i);
  1415. } else {
  1416. assert(NumIRArgs == 1);
  1417. ArgTypes[FirstIRArg] = argType;
  1418. }
  1419. break;
  1420. }
  1421. case ABIArgInfo::CoerceAndExpand: {
  1422. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1423. for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
  1424. *ArgTypesIter++ = EltTy;
  1425. }
  1426. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1427. break;
  1428. }
  1429. case ABIArgInfo::Expand:
  1430. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1431. getExpandedTypes(it->type, ArgTypesIter);
  1432. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1433. break;
  1434. }
  1435. }
  1436. bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
  1437. assert(Erased && "Not in set?");
  1438. return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
  1439. }
  1440. llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
  1441. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1442. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1443. if (!isFuncTypeConvertible(FPT))
  1444. return llvm::StructType::get(getLLVMContext());
  1445. return GetFunctionType(GD);
  1446. }
  1447. static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
  1448. llvm::AttrBuilder &FuncAttrs,
  1449. const FunctionProtoType *FPT) {
  1450. if (!FPT)
  1451. return;
  1452. if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  1453. FPT->isNothrow())
  1454. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1455. }
  1456. void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
  1457. bool AttrOnCallSite,
  1458. llvm::AttrBuilder &FuncAttrs) {
  1459. // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
  1460. if (!HasOptnone) {
  1461. if (CodeGenOpts.OptimizeSize)
  1462. FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
  1463. if (CodeGenOpts.OptimizeSize == 2)
  1464. FuncAttrs.addAttribute(llvm::Attribute::MinSize);
  1465. }
  1466. if (CodeGenOpts.DisableRedZone)
  1467. FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
  1468. if (CodeGenOpts.IndirectTlsSegRefs)
  1469. FuncAttrs.addAttribute("indirect-tls-seg-refs");
  1470. if (CodeGenOpts.NoImplicitFloat)
  1471. FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
  1472. if (AttrOnCallSite) {
  1473. // Attributes that should go on the call site only.
  1474. if (!CodeGenOpts.SimplifyLibCalls ||
  1475. CodeGenOpts.isNoBuiltinFunc(Name.data()))
  1476. FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
  1477. if (!CodeGenOpts.TrapFuncName.empty())
  1478. FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
  1479. } else {
  1480. // Attributes that should go on the function, but not the call site.
  1481. if (!CodeGenOpts.DisableFPElim) {
  1482. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1483. } else if (CodeGenOpts.OmitLeafFramePointer) {
  1484. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1485. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1486. } else {
  1487. FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
  1488. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1489. }
  1490. FuncAttrs.addAttribute("less-precise-fpmad",
  1491. llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
  1492. if (CodeGenOpts.NullPointerIsValid)
  1493. FuncAttrs.addAttribute("null-pointer-is-valid", "true");
  1494. if (!CodeGenOpts.FPDenormalMode.empty())
  1495. FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
  1496. FuncAttrs.addAttribute("no-trapping-math",
  1497. llvm::toStringRef(CodeGenOpts.NoTrappingMath));
  1498. // Strict (compliant) code is the default, so only add this attribute to
  1499. // indicate that we are trying to workaround a problem case.
  1500. if (!CodeGenOpts.StrictFloatCastOverflow)
  1501. FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
  1502. // TODO: Are these all needed?
  1503. // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
  1504. FuncAttrs.addAttribute("no-infs-fp-math",
  1505. llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
  1506. FuncAttrs.addAttribute("no-nans-fp-math",
  1507. llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
  1508. FuncAttrs.addAttribute("unsafe-fp-math",
  1509. llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
  1510. FuncAttrs.addAttribute("use-soft-float",
  1511. llvm::toStringRef(CodeGenOpts.SoftFloat));
  1512. FuncAttrs.addAttribute("stack-protector-buffer-size",
  1513. llvm::utostr(CodeGenOpts.SSPBufferSize));
  1514. FuncAttrs.addAttribute("no-signed-zeros-fp-math",
  1515. llvm::toStringRef(CodeGenOpts.NoSignedZeros));
  1516. FuncAttrs.addAttribute(
  1517. "correctly-rounded-divide-sqrt-fp-math",
  1518. llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
  1519. if (getLangOpts().OpenCL)
  1520. FuncAttrs.addAttribute("denorms-are-zero",
  1521. llvm::toStringRef(CodeGenOpts.FlushDenorm));
  1522. // TODO: Reciprocal estimate codegen options should apply to instructions?
  1523. const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
  1524. if (!Recips.empty())
  1525. FuncAttrs.addAttribute("reciprocal-estimates",
  1526. llvm::join(Recips, ","));
  1527. if (!CodeGenOpts.PreferVectorWidth.empty() &&
  1528. CodeGenOpts.PreferVectorWidth != "none")
  1529. FuncAttrs.addAttribute("prefer-vector-width",
  1530. CodeGenOpts.PreferVectorWidth);
  1531. if (CodeGenOpts.StackRealignment)
  1532. FuncAttrs.addAttribute("stackrealign");
  1533. if (CodeGenOpts.Backchain)
  1534. FuncAttrs.addAttribute("backchain");
  1535. if (CodeGenOpts.SpeculativeLoadHardening)
  1536. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1537. }
  1538. if (getLangOpts().assumeFunctionsAreConvergent()) {
  1539. // Conservatively, mark all functions and calls in CUDA and OpenCL as
  1540. // convergent (meaning, they may call an intrinsically convergent op, such
  1541. // as __syncthreads() / barrier(), and so can't have certain optimizations
  1542. // applied around them). LLVM will remove this attribute where it safely
  1543. // can.
  1544. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1545. }
  1546. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  1547. // Exceptions aren't supported in CUDA device code.
  1548. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1549. // Respect -fcuda-flush-denormals-to-zero.
  1550. if (CodeGenOpts.FlushDenorm)
  1551. FuncAttrs.addAttribute("nvptx-f32ftz", "true");
  1552. }
  1553. for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
  1554. StringRef Var, Value;
  1555. std::tie(Var, Value) = Attr.split('=');
  1556. FuncAttrs.addAttribute(Var, Value);
  1557. }
  1558. }
  1559. void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
  1560. llvm::AttrBuilder FuncAttrs;
  1561. ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(),
  1562. /* AttrOnCallsite = */ false, FuncAttrs);
  1563. F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
  1564. }
  1565. void CodeGenModule::ConstructAttributeList(
  1566. StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
  1567. llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
  1568. llvm::AttrBuilder FuncAttrs;
  1569. llvm::AttrBuilder RetAttrs;
  1570. CallingConv = FI.getEffectiveCallingConvention();
  1571. if (FI.isNoReturn())
  1572. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1573. // If we have information about the function prototype, we can learn
  1574. // attributes from there.
  1575. AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
  1576. CalleeInfo.getCalleeFunctionProtoType());
  1577. const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
  1578. bool HasOptnone = false;
  1579. // FIXME: handle sseregparm someday...
  1580. if (TargetDecl) {
  1581. if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
  1582. FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
  1583. if (TargetDecl->hasAttr<NoThrowAttr>())
  1584. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1585. if (TargetDecl->hasAttr<NoReturnAttr>())
  1586. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1587. if (TargetDecl->hasAttr<ColdAttr>())
  1588. FuncAttrs.addAttribute(llvm::Attribute::Cold);
  1589. if (TargetDecl->hasAttr<NoDuplicateAttr>())
  1590. FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
  1591. if (TargetDecl->hasAttr<ConvergentAttr>())
  1592. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1593. if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1594. AddAttributesFromFunctionProtoType(
  1595. getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
  1596. // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
  1597. // These attributes are not inherited by overloads.
  1598. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
  1599. if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
  1600. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1601. }
  1602. // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
  1603. if (TargetDecl->hasAttr<ConstAttr>()) {
  1604. FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
  1605. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1606. } else if (TargetDecl->hasAttr<PureAttr>()) {
  1607. FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
  1608. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1609. } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
  1610. FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
  1611. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1612. }
  1613. if (TargetDecl->hasAttr<RestrictAttr>())
  1614. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1615. if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
  1616. !CodeGenOpts.NullPointerIsValid)
  1617. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1618. if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
  1619. FuncAttrs.addAttribute("no_caller_saved_registers");
  1620. if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
  1621. FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
  1622. HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
  1623. if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
  1624. Optional<unsigned> NumElemsParam;
  1625. if (AllocSize->getNumElemsParam().isValid())
  1626. NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
  1627. FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
  1628. NumElemsParam);
  1629. }
  1630. }
  1631. ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
  1632. // This must run after constructing the default function attribute list
  1633. // to ensure that the speculative load hardening attribute is removed
  1634. // in the case where the -mspeculative-load-hardening flag was passed.
  1635. if (TargetDecl) {
  1636. if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
  1637. FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1638. if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
  1639. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1640. }
  1641. if (CodeGenOpts.EnableSegmentedStacks &&
  1642. !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
  1643. FuncAttrs.addAttribute("split-stack");
  1644. // Add NonLazyBind attribute to function declarations when -fno-plt
  1645. // is used.
  1646. if (TargetDecl && CodeGenOpts.NoPLT) {
  1647. if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1648. if (!Fn->isDefined() && !AttrOnCallSite) {
  1649. FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
  1650. }
  1651. }
  1652. }
  1653. if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
  1654. if (getLangOpts().OpenCLVersion <= 120) {
  1655. // OpenCL v1.2 Work groups are always uniform
  1656. FuncAttrs.addAttribute("uniform-work-group-size", "true");
  1657. } else {
  1658. // OpenCL v2.0 Work groups may be whether uniform or not.
  1659. // '-cl-uniform-work-group-size' compile option gets a hint
  1660. // to the compiler that the global work-size be a multiple of
  1661. // the work-group size specified to clEnqueueNDRangeKernel
  1662. // (i.e. work groups are uniform).
  1663. FuncAttrs.addAttribute("uniform-work-group-size",
  1664. llvm::toStringRef(CodeGenOpts.UniformWGSize));
  1665. }
  1666. }
  1667. if (!AttrOnCallSite) {
  1668. bool DisableTailCalls = false;
  1669. if (CodeGenOpts.DisableTailCalls)
  1670. DisableTailCalls = true;
  1671. else if (TargetDecl) {
  1672. if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
  1673. TargetDecl->hasAttr<AnyX86InterruptAttr>())
  1674. DisableTailCalls = true;
  1675. else if (CodeGenOpts.NoEscapingBlockTailCalls) {
  1676. if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
  1677. if (!BD->doesNotEscape())
  1678. DisableTailCalls = true;
  1679. }
  1680. }
  1681. FuncAttrs.addAttribute("disable-tail-calls",
  1682. llvm::toStringRef(DisableTailCalls));
  1683. GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
  1684. }
  1685. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
  1686. QualType RetTy = FI.getReturnType();
  1687. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1688. switch (RetAI.getKind()) {
  1689. case ABIArgInfo::Extend:
  1690. if (RetAI.isSignExt())
  1691. RetAttrs.addAttribute(llvm::Attribute::SExt);
  1692. else
  1693. RetAttrs.addAttribute(llvm::Attribute::ZExt);
  1694. LLVM_FALLTHROUGH;
  1695. case ABIArgInfo::Direct:
  1696. if (RetAI.getInReg())
  1697. RetAttrs.addAttribute(llvm::Attribute::InReg);
  1698. break;
  1699. case ABIArgInfo::Ignore:
  1700. break;
  1701. case ABIArgInfo::InAlloca:
  1702. case ABIArgInfo::Indirect: {
  1703. // inalloca and sret disable readnone and readonly
  1704. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1705. .removeAttribute(llvm::Attribute::ReadNone);
  1706. break;
  1707. }
  1708. case ABIArgInfo::CoerceAndExpand:
  1709. break;
  1710. case ABIArgInfo::Expand:
  1711. llvm_unreachable("Invalid ABI kind for return argument");
  1712. }
  1713. if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
  1714. QualType PTy = RefTy->getPointeeType();
  1715. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1716. RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1717. .getQuantity());
  1718. else if (getContext().getTargetAddressSpace(PTy) == 0 &&
  1719. !CodeGenOpts.NullPointerIsValid)
  1720. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1721. }
  1722. bool hasUsedSRet = false;
  1723. SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
  1724. // Attach attributes to sret.
  1725. if (IRFunctionArgs.hasSRetArg()) {
  1726. llvm::AttrBuilder SRETAttrs;
  1727. if (!RetAI.getSuppressSRet())
  1728. SRETAttrs.addAttribute(llvm::Attribute::StructRet);
  1729. hasUsedSRet = true;
  1730. if (RetAI.getInReg())
  1731. SRETAttrs.addAttribute(llvm::Attribute::InReg);
  1732. ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
  1733. llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
  1734. }
  1735. // Attach attributes to inalloca argument.
  1736. if (IRFunctionArgs.hasInallocaArg()) {
  1737. llvm::AttrBuilder Attrs;
  1738. Attrs.addAttribute(llvm::Attribute::InAlloca);
  1739. ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
  1740. llvm::AttributeSet::get(getLLVMContext(), Attrs);
  1741. }
  1742. unsigned ArgNo = 0;
  1743. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
  1744. E = FI.arg_end();
  1745. I != E; ++I, ++ArgNo) {
  1746. QualType ParamType = I->type;
  1747. const ABIArgInfo &AI = I->info;
  1748. llvm::AttrBuilder Attrs;
  1749. // Add attribute for padding argument, if necessary.
  1750. if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
  1751. if (AI.getPaddingInReg()) {
  1752. ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1753. llvm::AttributeSet::get(
  1754. getLLVMContext(),
  1755. llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
  1756. }
  1757. }
  1758. // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
  1759. // have the corresponding parameter variable. It doesn't make
  1760. // sense to do it here because parameters are so messed up.
  1761. switch (AI.getKind()) {
  1762. case ABIArgInfo::Extend:
  1763. if (AI.isSignExt())
  1764. Attrs.addAttribute(llvm::Attribute::SExt);
  1765. else
  1766. Attrs.addAttribute(llvm::Attribute::ZExt);
  1767. LLVM_FALLTHROUGH;
  1768. case ABIArgInfo::Direct:
  1769. if (ArgNo == 0 && FI.isChainCall())
  1770. Attrs.addAttribute(llvm::Attribute::Nest);
  1771. else if (AI.getInReg())
  1772. Attrs.addAttribute(llvm::Attribute::InReg);
  1773. break;
  1774. case ABIArgInfo::Indirect: {
  1775. if (AI.getInReg())
  1776. Attrs.addAttribute(llvm::Attribute::InReg);
  1777. if (AI.getIndirectByVal())
  1778. Attrs.addAttribute(llvm::Attribute::ByVal);
  1779. CharUnits Align = AI.getIndirectAlign();
  1780. // In a byval argument, it is important that the required
  1781. // alignment of the type is honored, as LLVM might be creating a
  1782. // *new* stack object, and needs to know what alignment to give
  1783. // it. (Sometimes it can deduce a sensible alignment on its own,
  1784. // but not if clang decides it must emit a packed struct, or the
  1785. // user specifies increased alignment requirements.)
  1786. //
  1787. // This is different from indirect *not* byval, where the object
  1788. // exists already, and the align attribute is purely
  1789. // informative.
  1790. assert(!Align.isZero());
  1791. // For now, only add this when we have a byval argument.
  1792. // TODO: be less lazy about updating test cases.
  1793. if (AI.getIndirectByVal())
  1794. Attrs.addAlignmentAttr(Align.getQuantity());
  1795. // byval disables readnone and readonly.
  1796. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1797. .removeAttribute(llvm::Attribute::ReadNone);
  1798. break;
  1799. }
  1800. case ABIArgInfo::Ignore:
  1801. case ABIArgInfo::Expand:
  1802. case ABIArgInfo::CoerceAndExpand:
  1803. break;
  1804. case ABIArgInfo::InAlloca:
  1805. // inalloca disables readnone and readonly.
  1806. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1807. .removeAttribute(llvm::Attribute::ReadNone);
  1808. continue;
  1809. }
  1810. if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
  1811. QualType PTy = RefTy->getPointeeType();
  1812. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1813. Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1814. .getQuantity());
  1815. else if (getContext().getTargetAddressSpace(PTy) == 0 &&
  1816. !CodeGenOpts.NullPointerIsValid)
  1817. Attrs.addAttribute(llvm::Attribute::NonNull);
  1818. }
  1819. switch (FI.getExtParameterInfo(ArgNo).getABI()) {
  1820. case ParameterABI::Ordinary:
  1821. break;
  1822. case ParameterABI::SwiftIndirectResult: {
  1823. // Add 'sret' if we haven't already used it for something, but
  1824. // only if the result is void.
  1825. if (!hasUsedSRet && RetTy->isVoidType()) {
  1826. Attrs.addAttribute(llvm::Attribute::StructRet);
  1827. hasUsedSRet = true;
  1828. }
  1829. // Add 'noalias' in either case.
  1830. Attrs.addAttribute(llvm::Attribute::NoAlias);
  1831. // Add 'dereferenceable' and 'alignment'.
  1832. auto PTy = ParamType->getPointeeType();
  1833. if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
  1834. auto info = getContext().getTypeInfoInChars(PTy);
  1835. Attrs.addDereferenceableAttr(info.first.getQuantity());
  1836. Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
  1837. info.second.getQuantity()));
  1838. }
  1839. break;
  1840. }
  1841. case ParameterABI::SwiftErrorResult:
  1842. Attrs.addAttribute(llvm::Attribute::SwiftError);
  1843. break;
  1844. case ParameterABI::SwiftContext:
  1845. Attrs.addAttribute(llvm::Attribute::SwiftSelf);
  1846. break;
  1847. }
  1848. if (FI.getExtParameterInfo(ArgNo).isNoEscape())
  1849. Attrs.addAttribute(llvm::Attribute::NoCapture);
  1850. if (Attrs.hasAttributes()) {
  1851. unsigned FirstIRArg, NumIRArgs;
  1852. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1853. for (unsigned i = 0; i < NumIRArgs; i++)
  1854. ArgAttrs[FirstIRArg + i] =
  1855. llvm::AttributeSet::get(getLLVMContext(), Attrs);
  1856. }
  1857. }
  1858. assert(ArgNo == FI.arg_size());
  1859. AttrList = llvm::AttributeList::get(
  1860. getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
  1861. llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
  1862. }
  1863. /// An argument came in as a promoted argument; demote it back to its
  1864. /// declared type.
  1865. static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
  1866. const VarDecl *var,
  1867. llvm::Value *value) {
  1868. llvm::Type *varType = CGF.ConvertType(var->getType());
  1869. // This can happen with promotions that actually don't change the
  1870. // underlying type, like the enum promotions.
  1871. if (value->getType() == varType) return value;
  1872. assert((varType->isIntegerTy() || varType->isFloatingPointTy())
  1873. && "unexpected promotion type");
  1874. if (isa<llvm::IntegerType>(varType))
  1875. return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
  1876. return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
  1877. }
  1878. /// Returns the attribute (either parameter attribute, or function
  1879. /// attribute), which declares argument ArgNo to be non-null.
  1880. static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
  1881. QualType ArgType, unsigned ArgNo) {
  1882. // FIXME: __attribute__((nonnull)) can also be applied to:
  1883. // - references to pointers, where the pointee is known to be
  1884. // nonnull (apparently a Clang extension)
  1885. // - transparent unions containing pointers
  1886. // In the former case, LLVM IR cannot represent the constraint. In
  1887. // the latter case, we have no guarantee that the transparent union
  1888. // is in fact passed as a pointer.
  1889. if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
  1890. return nullptr;
  1891. // First, check attribute on parameter itself.
  1892. if (PVD) {
  1893. if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
  1894. return ParmNNAttr;
  1895. }
  1896. // Check function attributes.
  1897. if (!FD)
  1898. return nullptr;
  1899. for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
  1900. if (NNAttr->isNonNull(ArgNo))
  1901. return NNAttr;
  1902. }
  1903. return nullptr;
  1904. }
  1905. namespace {
  1906. struct CopyBackSwiftError final : EHScopeStack::Cleanup {
  1907. Address Temp;
  1908. Address Arg;
  1909. CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
  1910. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1911. llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
  1912. CGF.Builder.CreateStore(errorValue, Arg);
  1913. }
  1914. };
  1915. }
  1916. void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
  1917. llvm::Function *Fn,
  1918. const FunctionArgList &Args) {
  1919. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
  1920. // Naked functions don't have prologues.
  1921. return;
  1922. // If this is an implicit-return-zero function, go ahead and
  1923. // initialize the return value. TODO: it might be nice to have
  1924. // a more general mechanism for this that didn't require synthesized
  1925. // return statements.
  1926. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  1927. if (FD->hasImplicitReturnZero()) {
  1928. QualType RetTy = FD->getReturnType().getUnqualifiedType();
  1929. llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
  1930. llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
  1931. Builder.CreateStore(Zero, ReturnValue);
  1932. }
  1933. }
  1934. // FIXME: We no longer need the types from FunctionArgList; lift up and
  1935. // simplify.
  1936. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
  1937. // Flattened function arguments.
  1938. SmallVector<llvm::Value *, 16> FnArgs;
  1939. FnArgs.reserve(IRFunctionArgs.totalIRArgs());
  1940. for (auto &Arg : Fn->args()) {
  1941. FnArgs.push_back(&Arg);
  1942. }
  1943. assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
  1944. // If we're using inalloca, all the memory arguments are GEPs off of the last
  1945. // parameter, which is a pointer to the complete memory area.
  1946. Address ArgStruct = Address::invalid();
  1947. if (IRFunctionArgs.hasInallocaArg()) {
  1948. ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
  1949. FI.getArgStructAlignment());
  1950. assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
  1951. }
  1952. // Name the struct return parameter.
  1953. if (IRFunctionArgs.hasSRetArg()) {
  1954. auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
  1955. AI->setName("agg.result");
  1956. AI->addAttr(llvm::Attribute::NoAlias);
  1957. }
  1958. // Track if we received the parameter as a pointer (indirect, byval, or
  1959. // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
  1960. // into a local alloca for us.
  1961. SmallVector<ParamValue, 16> ArgVals;
  1962. ArgVals.reserve(Args.size());
  1963. // Create a pointer value for every parameter declaration. This usually
  1964. // entails copying one or more LLVM IR arguments into an alloca. Don't push
  1965. // any cleanups or do anything that might unwind. We do that separately, so
  1966. // we can push the cleanups in the correct order for the ABI.
  1967. assert(FI.arg_size() == Args.size() &&
  1968. "Mismatch between function signature & arguments.");
  1969. unsigned ArgNo = 0;
  1970. CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
  1971. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1972. i != e; ++i, ++info_it, ++ArgNo) {
  1973. const VarDecl *Arg = *i;
  1974. const ABIArgInfo &ArgI = info_it->info;
  1975. bool isPromoted =
  1976. isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
  1977. // We are converting from ABIArgInfo type to VarDecl type directly, unless
  1978. // the parameter is promoted. In this case we convert to
  1979. // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
  1980. QualType Ty = isPromoted ? info_it->type : Arg->getType();
  1981. assert(hasScalarEvaluationKind(Ty) ==
  1982. hasScalarEvaluationKind(Arg->getType()));
  1983. unsigned FirstIRArg, NumIRArgs;
  1984. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1985. switch (ArgI.getKind()) {
  1986. case ABIArgInfo::InAlloca: {
  1987. assert(NumIRArgs == 0);
  1988. auto FieldIndex = ArgI.getInAllocaFieldIndex();
  1989. Address V =
  1990. Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
  1991. ArgVals.push_back(ParamValue::forIndirect(V));
  1992. break;
  1993. }
  1994. case ABIArgInfo::Indirect: {
  1995. assert(NumIRArgs == 1);
  1996. Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
  1997. if (!hasScalarEvaluationKind(Ty)) {
  1998. // Aggregates and complex variables are accessed by reference. All we
  1999. // need to do is realign the value, if requested.
  2000. Address V = ParamAddr;
  2001. if (ArgI.getIndirectRealign()) {
  2002. Address AlignedTemp = CreateMemTemp(Ty, "coerce");
  2003. // Copy from the incoming argument pointer to the temporary with the
  2004. // appropriate alignment.
  2005. //
  2006. // FIXME: We should have a common utility for generating an aggregate
  2007. // copy.
  2008. CharUnits Size = getContext().getTypeSizeInChars(Ty);
  2009. auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
  2010. Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
  2011. Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
  2012. Builder.CreateMemCpy(Dst, Src, SizeVal, false);
  2013. V = AlignedTemp;
  2014. }
  2015. ArgVals.push_back(ParamValue::forIndirect(V));
  2016. } else {
  2017. // Load scalar value from indirect argument.
  2018. llvm::Value *V =
  2019. EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
  2020. if (isPromoted)
  2021. V = emitArgumentDemotion(*this, Arg, V);
  2022. ArgVals.push_back(ParamValue::forDirect(V));
  2023. }
  2024. break;
  2025. }
  2026. case ABIArgInfo::Extend:
  2027. case ABIArgInfo::Direct: {
  2028. // If we have the trivial case, handle it with no muss and fuss.
  2029. if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
  2030. ArgI.getCoerceToType() == ConvertType(Ty) &&
  2031. ArgI.getDirectOffset() == 0) {
  2032. assert(NumIRArgs == 1);
  2033. llvm::Value *V = FnArgs[FirstIRArg];
  2034. auto AI = cast<llvm::Argument>(V);
  2035. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
  2036. if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
  2037. PVD->getFunctionScopeIndex()) &&
  2038. !CGM.getCodeGenOpts().NullPointerIsValid)
  2039. AI->addAttr(llvm::Attribute::NonNull);
  2040. QualType OTy = PVD->getOriginalType();
  2041. if (const auto *ArrTy =
  2042. getContext().getAsConstantArrayType(OTy)) {
  2043. // A C99 array parameter declaration with the static keyword also
  2044. // indicates dereferenceability, and if the size is constant we can
  2045. // use the dereferenceable attribute (which requires the size in
  2046. // bytes).
  2047. if (ArrTy->getSizeModifier() == ArrayType::Static) {
  2048. QualType ETy = ArrTy->getElementType();
  2049. uint64_t ArrSize = ArrTy->getSize().getZExtValue();
  2050. if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
  2051. ArrSize) {
  2052. llvm::AttrBuilder Attrs;
  2053. Attrs.addDereferenceableAttr(
  2054. getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
  2055. AI->addAttrs(Attrs);
  2056. } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
  2057. !CGM.getCodeGenOpts().NullPointerIsValid) {
  2058. AI->addAttr(llvm::Attribute::NonNull);
  2059. }
  2060. }
  2061. } else if (const auto *ArrTy =
  2062. getContext().getAsVariableArrayType(OTy)) {
  2063. // For C99 VLAs with the static keyword, we don't know the size so
  2064. // we can't use the dereferenceable attribute, but in addrspace(0)
  2065. // we know that it must be nonnull.
  2066. if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
  2067. !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
  2068. !CGM.getCodeGenOpts().NullPointerIsValid)
  2069. AI->addAttr(llvm::Attribute::NonNull);
  2070. }
  2071. const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
  2072. if (!AVAttr)
  2073. if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
  2074. AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
  2075. if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
  2076. // If alignment-assumption sanitizer is enabled, we do *not* add
  2077. // alignment attribute here, but emit normal alignment assumption,
  2078. // so the UBSAN check could function.
  2079. llvm::Value *AlignmentValue =
  2080. EmitScalarExpr(AVAttr->getAlignment());
  2081. llvm::ConstantInt *AlignmentCI =
  2082. cast<llvm::ConstantInt>(AlignmentValue);
  2083. unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
  2084. +llvm::Value::MaximumAlignment);
  2085. AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
  2086. }
  2087. }
  2088. if (Arg->getType().isRestrictQualified())
  2089. AI->addAttr(llvm::Attribute::NoAlias);
  2090. // LLVM expects swifterror parameters to be used in very restricted
  2091. // ways. Copy the value into a less-restricted temporary.
  2092. if (FI.getExtParameterInfo(ArgNo).getABI()
  2093. == ParameterABI::SwiftErrorResult) {
  2094. QualType pointeeTy = Ty->getPointeeType();
  2095. assert(pointeeTy->isPointerType());
  2096. Address temp =
  2097. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  2098. Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
  2099. llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
  2100. Builder.CreateStore(incomingErrorValue, temp);
  2101. V = temp.getPointer();
  2102. // Push a cleanup to copy the value back at the end of the function.
  2103. // The convention does not guarantee that the value will be written
  2104. // back if the function exits with an unwind exception.
  2105. EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
  2106. }
  2107. // Ensure the argument is the correct type.
  2108. if (V->getType() != ArgI.getCoerceToType())
  2109. V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
  2110. if (isPromoted)
  2111. V = emitArgumentDemotion(*this, Arg, V);
  2112. // Because of merging of function types from multiple decls it is
  2113. // possible for the type of an argument to not match the corresponding
  2114. // type in the function type. Since we are codegening the callee
  2115. // in here, add a cast to the argument type.
  2116. llvm::Type *LTy = ConvertType(Arg->getType());
  2117. if (V->getType() != LTy)
  2118. V = Builder.CreateBitCast(V, LTy);
  2119. ArgVals.push_back(ParamValue::forDirect(V));
  2120. break;
  2121. }
  2122. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  2123. Arg->getName());
  2124. // Pointer to store into.
  2125. Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
  2126. // Fast-isel and the optimizer generally like scalar values better than
  2127. // FCAs, so we flatten them if this is safe to do for this argument.
  2128. llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
  2129. if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
  2130. STy->getNumElements() > 1) {
  2131. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
  2132. llvm::Type *DstTy = Ptr.getElementType();
  2133. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
  2134. Address AddrToStoreInto = Address::invalid();
  2135. if (SrcSize <= DstSize) {
  2136. AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
  2137. } else {
  2138. AddrToStoreInto =
  2139. CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
  2140. }
  2141. assert(STy->getNumElements() == NumIRArgs);
  2142. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2143. auto AI = FnArgs[FirstIRArg + i];
  2144. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  2145. Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
  2146. Builder.CreateStore(AI, EltPtr);
  2147. }
  2148. if (SrcSize > DstSize) {
  2149. Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
  2150. }
  2151. } else {
  2152. // Simple case, just do a coerced store of the argument into the alloca.
  2153. assert(NumIRArgs == 1);
  2154. auto AI = FnArgs[FirstIRArg];
  2155. AI->setName(Arg->getName() + ".coerce");
  2156. CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
  2157. }
  2158. // Match to what EmitParmDecl is expecting for this type.
  2159. if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
  2160. llvm::Value *V =
  2161. EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
  2162. if (isPromoted)
  2163. V = emitArgumentDemotion(*this, Arg, V);
  2164. ArgVals.push_back(ParamValue::forDirect(V));
  2165. } else {
  2166. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2167. }
  2168. break;
  2169. }
  2170. case ABIArgInfo::CoerceAndExpand: {
  2171. // Reconstruct into a temporary.
  2172. Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2173. ArgVals.push_back(ParamValue::forIndirect(alloca));
  2174. auto coercionType = ArgI.getCoerceAndExpandType();
  2175. alloca = Builder.CreateElementBitCast(alloca, coercionType);
  2176. unsigned argIndex = FirstIRArg;
  2177. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  2178. llvm::Type *eltType = coercionType->getElementType(i);
  2179. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
  2180. continue;
  2181. auto eltAddr = Builder.CreateStructGEP(alloca, i);
  2182. auto elt = FnArgs[argIndex++];
  2183. Builder.CreateStore(elt, eltAddr);
  2184. }
  2185. assert(argIndex == FirstIRArg + NumIRArgs);
  2186. break;
  2187. }
  2188. case ABIArgInfo::Expand: {
  2189. // If this structure was expanded into multiple arguments then
  2190. // we need to create a temporary and reconstruct it from the
  2191. // arguments.
  2192. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2193. LValue LV = MakeAddrLValue(Alloca, Ty);
  2194. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2195. auto FnArgIter = FnArgs.begin() + FirstIRArg;
  2196. ExpandTypeFromArgs(Ty, LV, FnArgIter);
  2197. assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
  2198. for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
  2199. auto AI = FnArgs[FirstIRArg + i];
  2200. AI->setName(Arg->getName() + "." + Twine(i));
  2201. }
  2202. break;
  2203. }
  2204. case ABIArgInfo::Ignore:
  2205. assert(NumIRArgs == 0);
  2206. // Initialize the local variable appropriately.
  2207. if (!hasScalarEvaluationKind(Ty)) {
  2208. ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
  2209. } else {
  2210. llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
  2211. ArgVals.push_back(ParamValue::forDirect(U));
  2212. }
  2213. break;
  2214. }
  2215. }
  2216. if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2217. for (int I = Args.size() - 1; I >= 0; --I)
  2218. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2219. } else {
  2220. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  2221. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2222. }
  2223. }
  2224. static void eraseUnusedBitCasts(llvm::Instruction *insn) {
  2225. while (insn->use_empty()) {
  2226. llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
  2227. if (!bitcast) return;
  2228. // This is "safe" because we would have used a ConstantExpr otherwise.
  2229. insn = cast<llvm::Instruction>(bitcast->getOperand(0));
  2230. bitcast->eraseFromParent();
  2231. }
  2232. }
  2233. /// Try to emit a fused autorelease of a return result.
  2234. static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
  2235. llvm::Value *result) {
  2236. // We must be immediately followed the cast.
  2237. llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
  2238. if (BB->empty()) return nullptr;
  2239. if (&BB->back() != result) return nullptr;
  2240. llvm::Type *resultType = result->getType();
  2241. // result is in a BasicBlock and is therefore an Instruction.
  2242. llvm::Instruction *generator = cast<llvm::Instruction>(result);
  2243. SmallVector<llvm::Instruction *, 4> InstsToKill;
  2244. // Look for:
  2245. // %generator = bitcast %type1* %generator2 to %type2*
  2246. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
  2247. // We would have emitted this as a constant if the operand weren't
  2248. // an Instruction.
  2249. generator = cast<llvm::Instruction>(bitcast->getOperand(0));
  2250. // Require the generator to be immediately followed by the cast.
  2251. if (generator->getNextNode() != bitcast)
  2252. return nullptr;
  2253. InstsToKill.push_back(bitcast);
  2254. }
  2255. // Look for:
  2256. // %generator = call i8* @objc_retain(i8* %originalResult)
  2257. // or
  2258. // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
  2259. llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
  2260. if (!call) return nullptr;
  2261. bool doRetainAutorelease;
  2262. if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
  2263. doRetainAutorelease = true;
  2264. } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
  2265. .objc_retainAutoreleasedReturnValue) {
  2266. doRetainAutorelease = false;
  2267. // If we emitted an assembly marker for this call (and the
  2268. // ARCEntrypoints field should have been set if so), go looking
  2269. // for that call. If we can't find it, we can't do this
  2270. // optimization. But it should always be the immediately previous
  2271. // instruction, unless we needed bitcasts around the call.
  2272. if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
  2273. llvm::Instruction *prev = call->getPrevNode();
  2274. assert(prev);
  2275. if (isa<llvm::BitCastInst>(prev)) {
  2276. prev = prev->getPrevNode();
  2277. assert(prev);
  2278. }
  2279. assert(isa<llvm::CallInst>(prev));
  2280. assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
  2281. CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
  2282. InstsToKill.push_back(prev);
  2283. }
  2284. } else {
  2285. return nullptr;
  2286. }
  2287. result = call->getArgOperand(0);
  2288. InstsToKill.push_back(call);
  2289. // Keep killing bitcasts, for sanity. Note that we no longer care
  2290. // about precise ordering as long as there's exactly one use.
  2291. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
  2292. if (!bitcast->hasOneUse()) break;
  2293. InstsToKill.push_back(bitcast);
  2294. result = bitcast->getOperand(0);
  2295. }
  2296. // Delete all the unnecessary instructions, from latest to earliest.
  2297. for (auto *I : InstsToKill)
  2298. I->eraseFromParent();
  2299. // Do the fused retain/autorelease if we were asked to.
  2300. if (doRetainAutorelease)
  2301. result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
  2302. // Cast back to the result type.
  2303. return CGF.Builder.CreateBitCast(result, resultType);
  2304. }
  2305. /// If this is a +1 of the value of an immutable 'self', remove it.
  2306. static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
  2307. llvm::Value *result) {
  2308. // This is only applicable to a method with an immutable 'self'.
  2309. const ObjCMethodDecl *method =
  2310. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
  2311. if (!method) return nullptr;
  2312. const VarDecl *self = method->getSelfDecl();
  2313. if (!self->getType().isConstQualified()) return nullptr;
  2314. // Look for a retain call.
  2315. llvm::CallInst *retainCall =
  2316. dyn_cast<llvm::CallInst>(result->stripPointerCasts());
  2317. if (!retainCall ||
  2318. retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
  2319. return nullptr;
  2320. // Look for an ordinary load of 'self'.
  2321. llvm::Value *retainedValue = retainCall->getArgOperand(0);
  2322. llvm::LoadInst *load =
  2323. dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
  2324. if (!load || load->isAtomic() || load->isVolatile() ||
  2325. load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
  2326. return nullptr;
  2327. // Okay! Burn it all down. This relies for correctness on the
  2328. // assumption that the retain is emitted as part of the return and
  2329. // that thereafter everything is used "linearly".
  2330. llvm::Type *resultType = result->getType();
  2331. eraseUnusedBitCasts(cast<llvm::Instruction>(result));
  2332. assert(retainCall->use_empty());
  2333. retainCall->eraseFromParent();
  2334. eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
  2335. return CGF.Builder.CreateBitCast(load, resultType);
  2336. }
  2337. /// Emit an ARC autorelease of the result of a function.
  2338. ///
  2339. /// \return the value to actually return from the function
  2340. static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
  2341. llvm::Value *result) {
  2342. // If we're returning 'self', kill the initial retain. This is a
  2343. // heuristic attempt to "encourage correctness" in the really unfortunate
  2344. // case where we have a return of self during a dealloc and we desperately
  2345. // need to avoid the possible autorelease.
  2346. if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
  2347. return self;
  2348. // At -O0, try to emit a fused retain/autorelease.
  2349. if (CGF.shouldUseFusedARCCalls())
  2350. if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
  2351. return fused;
  2352. return CGF.EmitARCAutoreleaseReturnValue(result);
  2353. }
  2354. /// Heuristically search for a dominating store to the return-value slot.
  2355. static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
  2356. // Check if a User is a store which pointerOperand is the ReturnValue.
  2357. // We are looking for stores to the ReturnValue, not for stores of the
  2358. // ReturnValue to some other location.
  2359. auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
  2360. auto *SI = dyn_cast<llvm::StoreInst>(U);
  2361. if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
  2362. return nullptr;
  2363. // These aren't actually possible for non-coerced returns, and we
  2364. // only care about non-coerced returns on this code path.
  2365. assert(!SI->isAtomic() && !SI->isVolatile());
  2366. return SI;
  2367. };
  2368. // If there are multiple uses of the return-value slot, just check
  2369. // for something immediately preceding the IP. Sometimes this can
  2370. // happen with how we generate implicit-returns; it can also happen
  2371. // with noreturn cleanups.
  2372. if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
  2373. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2374. if (IP->empty()) return nullptr;
  2375. llvm::Instruction *I = &IP->back();
  2376. // Skip lifetime markers
  2377. for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
  2378. IE = IP->rend();
  2379. II != IE; ++II) {
  2380. if (llvm::IntrinsicInst *Intrinsic =
  2381. dyn_cast<llvm::IntrinsicInst>(&*II)) {
  2382. if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
  2383. const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
  2384. ++II;
  2385. if (II == IE)
  2386. break;
  2387. if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
  2388. continue;
  2389. }
  2390. }
  2391. I = &*II;
  2392. break;
  2393. }
  2394. return GetStoreIfValid(I);
  2395. }
  2396. llvm::StoreInst *store =
  2397. GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
  2398. if (!store) return nullptr;
  2399. // Now do a first-and-dirty dominance check: just walk up the
  2400. // single-predecessors chain from the current insertion point.
  2401. llvm::BasicBlock *StoreBB = store->getParent();
  2402. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2403. while (IP != StoreBB) {
  2404. if (!(IP = IP->getSinglePredecessor()))
  2405. return nullptr;
  2406. }
  2407. // Okay, the store's basic block dominates the insertion point; we
  2408. // can do our thing.
  2409. return store;
  2410. }
  2411. void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
  2412. bool EmitRetDbgLoc,
  2413. SourceLocation EndLoc) {
  2414. if (FI.isNoReturn()) {
  2415. // Noreturn functions don't return.
  2416. EmitUnreachable(EndLoc);
  2417. return;
  2418. }
  2419. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
  2420. // Naked functions don't have epilogues.
  2421. Builder.CreateUnreachable();
  2422. return;
  2423. }
  2424. // Functions with no result always return void.
  2425. if (!ReturnValue.isValid()) {
  2426. Builder.CreateRetVoid();
  2427. return;
  2428. }
  2429. llvm::DebugLoc RetDbgLoc;
  2430. llvm::Value *RV = nullptr;
  2431. QualType RetTy = FI.getReturnType();
  2432. const ABIArgInfo &RetAI = FI.getReturnInfo();
  2433. switch (RetAI.getKind()) {
  2434. case ABIArgInfo::InAlloca:
  2435. // Aggregrates get evaluated directly into the destination. Sometimes we
  2436. // need to return the sret value in a register, though.
  2437. assert(hasAggregateEvaluationKind(RetTy));
  2438. if (RetAI.getInAllocaSRet()) {
  2439. llvm::Function::arg_iterator EI = CurFn->arg_end();
  2440. --EI;
  2441. llvm::Value *ArgStruct = &*EI;
  2442. llvm::Value *SRet = Builder.CreateStructGEP(
  2443. nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
  2444. RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
  2445. }
  2446. break;
  2447. case ABIArgInfo::Indirect: {
  2448. auto AI = CurFn->arg_begin();
  2449. if (RetAI.isSRetAfterThis())
  2450. ++AI;
  2451. switch (getEvaluationKind(RetTy)) {
  2452. case TEK_Complex: {
  2453. ComplexPairTy RT =
  2454. EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
  2455. EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
  2456. /*isInit*/ true);
  2457. break;
  2458. }
  2459. case TEK_Aggregate:
  2460. // Do nothing; aggregrates get evaluated directly into the destination.
  2461. break;
  2462. case TEK_Scalar:
  2463. EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
  2464. MakeNaturalAlignAddrLValue(&*AI, RetTy),
  2465. /*isInit*/ true);
  2466. break;
  2467. }
  2468. break;
  2469. }
  2470. case ABIArgInfo::Extend:
  2471. case ABIArgInfo::Direct:
  2472. if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
  2473. RetAI.getDirectOffset() == 0) {
  2474. // The internal return value temp always will have pointer-to-return-type
  2475. // type, just do a load.
  2476. // If there is a dominating store to ReturnValue, we can elide
  2477. // the load, zap the store, and usually zap the alloca.
  2478. if (llvm::StoreInst *SI =
  2479. findDominatingStoreToReturnValue(*this)) {
  2480. // Reuse the debug location from the store unless there is
  2481. // cleanup code to be emitted between the store and return
  2482. // instruction.
  2483. if (EmitRetDbgLoc && !AutoreleaseResult)
  2484. RetDbgLoc = SI->getDebugLoc();
  2485. // Get the stored value and nuke the now-dead store.
  2486. RV = SI->getValueOperand();
  2487. SI->eraseFromParent();
  2488. // Otherwise, we have to do a simple load.
  2489. } else {
  2490. RV = Builder.CreateLoad(ReturnValue);
  2491. }
  2492. } else {
  2493. // If the value is offset in memory, apply the offset now.
  2494. Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
  2495. RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
  2496. }
  2497. // In ARC, end functions that return a retainable type with a call
  2498. // to objc_autoreleaseReturnValue.
  2499. if (AutoreleaseResult) {
  2500. #ifndef NDEBUG
  2501. // Type::isObjCRetainabletype has to be called on a QualType that hasn't
  2502. // been stripped of the typedefs, so we cannot use RetTy here. Get the
  2503. // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
  2504. // CurCodeDecl or BlockInfo.
  2505. QualType RT;
  2506. if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
  2507. RT = FD->getReturnType();
  2508. else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
  2509. RT = MD->getReturnType();
  2510. else if (isa<BlockDecl>(CurCodeDecl))
  2511. RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
  2512. else
  2513. llvm_unreachable("Unexpected function/method type");
  2514. assert(getLangOpts().ObjCAutoRefCount &&
  2515. !FI.isReturnsRetained() &&
  2516. RT->isObjCRetainableType());
  2517. #endif
  2518. RV = emitAutoreleaseOfResult(*this, RV);
  2519. }
  2520. break;
  2521. case ABIArgInfo::Ignore:
  2522. break;
  2523. case ABIArgInfo::CoerceAndExpand: {
  2524. auto coercionType = RetAI.getCoerceAndExpandType();
  2525. // Load all of the coerced elements out into results.
  2526. llvm::SmallVector<llvm::Value*, 4> results;
  2527. Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
  2528. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  2529. auto coercedEltType = coercionType->getElementType(i);
  2530. if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
  2531. continue;
  2532. auto eltAddr = Builder.CreateStructGEP(addr, i);
  2533. auto elt = Builder.CreateLoad(eltAddr);
  2534. results.push_back(elt);
  2535. }
  2536. // If we have one result, it's the single direct result type.
  2537. if (results.size() == 1) {
  2538. RV = results[0];
  2539. // Otherwise, we need to make a first-class aggregate.
  2540. } else {
  2541. // Construct a return type that lacks padding elements.
  2542. llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
  2543. RV = llvm::UndefValue::get(returnType);
  2544. for (unsigned i = 0, e = results.size(); i != e; ++i) {
  2545. RV = Builder.CreateInsertValue(RV, results[i], i);
  2546. }
  2547. }
  2548. break;
  2549. }
  2550. case ABIArgInfo::Expand:
  2551. llvm_unreachable("Invalid ABI kind for return argument");
  2552. }
  2553. llvm::Instruction *Ret;
  2554. if (RV) {
  2555. EmitReturnValueCheck(RV);
  2556. Ret = Builder.CreateRet(RV);
  2557. } else {
  2558. Ret = Builder.CreateRetVoid();
  2559. }
  2560. if (RetDbgLoc)
  2561. Ret->setDebugLoc(std::move(RetDbgLoc));
  2562. }
  2563. void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
  2564. // A current decl may not be available when emitting vtable thunks.
  2565. if (!CurCodeDecl)
  2566. return;
  2567. ReturnsNonNullAttr *RetNNAttr = nullptr;
  2568. if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
  2569. RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
  2570. if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
  2571. return;
  2572. // Prefer the returns_nonnull attribute if it's present.
  2573. SourceLocation AttrLoc;
  2574. SanitizerMask CheckKind;
  2575. SanitizerHandler Handler;
  2576. if (RetNNAttr) {
  2577. assert(!requiresReturnValueNullabilityCheck() &&
  2578. "Cannot check nullability and the nonnull attribute");
  2579. AttrLoc = RetNNAttr->getLocation();
  2580. CheckKind = SanitizerKind::ReturnsNonnullAttribute;
  2581. Handler = SanitizerHandler::NonnullReturn;
  2582. } else {
  2583. if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
  2584. if (auto *TSI = DD->getTypeSourceInfo())
  2585. if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
  2586. AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
  2587. CheckKind = SanitizerKind::NullabilityReturn;
  2588. Handler = SanitizerHandler::NullabilityReturn;
  2589. }
  2590. SanitizerScope SanScope(this);
  2591. // Make sure the "return" source location is valid. If we're checking a
  2592. // nullability annotation, make sure the preconditions for the check are met.
  2593. llvm::BasicBlock *Check = createBasicBlock("nullcheck");
  2594. llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
  2595. llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
  2596. llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
  2597. if (requiresReturnValueNullabilityCheck())
  2598. CanNullCheck =
  2599. Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
  2600. Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
  2601. EmitBlock(Check);
  2602. // Now do the null check.
  2603. llvm::Value *Cond = Builder.CreateIsNotNull(RV);
  2604. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
  2605. llvm::Value *DynamicData[] = {SLocPtr};
  2606. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
  2607. EmitBlock(NoCheck);
  2608. #ifndef NDEBUG
  2609. // The return location should not be used after the check has been emitted.
  2610. ReturnLocation = Address::invalid();
  2611. #endif
  2612. }
  2613. static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
  2614. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2615. return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
  2616. }
  2617. static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
  2618. QualType Ty) {
  2619. // FIXME: Generate IR in one pass, rather than going back and fixing up these
  2620. // placeholders.
  2621. llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
  2622. llvm::Type *IRPtrTy = IRTy->getPointerTo();
  2623. llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
  2624. // FIXME: When we generate this IR in one pass, we shouldn't need
  2625. // this win32-specific alignment hack.
  2626. CharUnits Align = CharUnits::fromQuantity(4);
  2627. Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
  2628. return AggValueSlot::forAddr(Address(Placeholder, Align),
  2629. Ty.getQualifiers(),
  2630. AggValueSlot::IsNotDestructed,
  2631. AggValueSlot::DoesNotNeedGCBarriers,
  2632. AggValueSlot::IsNotAliased,
  2633. AggValueSlot::DoesNotOverlap);
  2634. }
  2635. void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
  2636. const VarDecl *param,
  2637. SourceLocation loc) {
  2638. // StartFunction converted the ABI-lowered parameter(s) into a
  2639. // local alloca. We need to turn that into an r-value suitable
  2640. // for EmitCall.
  2641. Address local = GetAddrOfLocalVar(param);
  2642. QualType type = param->getType();
  2643. if (isInAllocaArgument(CGM.getCXXABI(), type)) {
  2644. CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
  2645. }
  2646. // GetAddrOfLocalVar returns a pointer-to-pointer for references,
  2647. // but the argument needs to be the original pointer.
  2648. if (type->isReferenceType()) {
  2649. args.add(RValue::get(Builder.CreateLoad(local)), type);
  2650. // In ARC, move out of consumed arguments so that the release cleanup
  2651. // entered by StartFunction doesn't cause an over-release. This isn't
  2652. // optimal -O0 code generation, but it should get cleaned up when
  2653. // optimization is enabled. This also assumes that delegate calls are
  2654. // performed exactly once for a set of arguments, but that should be safe.
  2655. } else if (getLangOpts().ObjCAutoRefCount &&
  2656. param->hasAttr<NSConsumedAttr>() &&
  2657. type->isObjCRetainableType()) {
  2658. llvm::Value *ptr = Builder.CreateLoad(local);
  2659. auto null =
  2660. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
  2661. Builder.CreateStore(null, local);
  2662. args.add(RValue::get(ptr), type);
  2663. // For the most part, we just need to load the alloca, except that
  2664. // aggregate r-values are actually pointers to temporaries.
  2665. } else {
  2666. args.add(convertTempToRValue(local, type, loc), type);
  2667. }
  2668. // Deactivate the cleanup for the callee-destructed param that was pushed.
  2669. if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
  2670. type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
  2671. type.isDestructedType()) {
  2672. EHScopeStack::stable_iterator cleanup =
  2673. CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
  2674. assert(cleanup.isValid() &&
  2675. "cleanup for callee-destructed param not recorded");
  2676. // This unreachable is a temporary marker which will be removed later.
  2677. llvm::Instruction *isActive = Builder.CreateUnreachable();
  2678. args.addArgCleanupDeactivation(cleanup, isActive);
  2679. }
  2680. }
  2681. static bool isProvablyNull(llvm::Value *addr) {
  2682. return isa<llvm::ConstantPointerNull>(addr);
  2683. }
  2684. /// Emit the actual writing-back of a writeback.
  2685. static void emitWriteback(CodeGenFunction &CGF,
  2686. const CallArgList::Writeback &writeback) {
  2687. const LValue &srcLV = writeback.Source;
  2688. Address srcAddr = srcLV.getAddress();
  2689. assert(!isProvablyNull(srcAddr.getPointer()) &&
  2690. "shouldn't have writeback for provably null argument");
  2691. llvm::BasicBlock *contBB = nullptr;
  2692. // If the argument wasn't provably non-null, we need to null check
  2693. // before doing the store.
  2694. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  2695. CGF.CGM.getDataLayout());
  2696. if (!provablyNonNull) {
  2697. llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
  2698. contBB = CGF.createBasicBlock("icr.done");
  2699. llvm::Value *isNull =
  2700. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2701. CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
  2702. CGF.EmitBlock(writebackBB);
  2703. }
  2704. // Load the value to writeback.
  2705. llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
  2706. // Cast it back, in case we're writing an id to a Foo* or something.
  2707. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
  2708. "icr.writeback-cast");
  2709. // Perform the writeback.
  2710. // If we have a "to use" value, it's something we need to emit a use
  2711. // of. This has to be carefully threaded in: if it's done after the
  2712. // release it's potentially undefined behavior (and the optimizer
  2713. // will ignore it), and if it happens before the retain then the
  2714. // optimizer could move the release there.
  2715. if (writeback.ToUse) {
  2716. assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
  2717. // Retain the new value. No need to block-copy here: the block's
  2718. // being passed up the stack.
  2719. value = CGF.EmitARCRetainNonBlock(value);
  2720. // Emit the intrinsic use here.
  2721. CGF.EmitARCIntrinsicUse(writeback.ToUse);
  2722. // Load the old value (primitively).
  2723. llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
  2724. // Put the new value in place (primitively).
  2725. CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
  2726. // Release the old value.
  2727. CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
  2728. // Otherwise, we can just do a normal lvalue store.
  2729. } else {
  2730. CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
  2731. }
  2732. // Jump to the continuation block.
  2733. if (!provablyNonNull)
  2734. CGF.EmitBlock(contBB);
  2735. }
  2736. static void emitWritebacks(CodeGenFunction &CGF,
  2737. const CallArgList &args) {
  2738. for (const auto &I : args.writebacks())
  2739. emitWriteback(CGF, I);
  2740. }
  2741. static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
  2742. const CallArgList &CallArgs) {
  2743. ArrayRef<CallArgList::CallArgCleanup> Cleanups =
  2744. CallArgs.getCleanupsToDeactivate();
  2745. // Iterate in reverse to increase the likelihood of popping the cleanup.
  2746. for (const auto &I : llvm::reverse(Cleanups)) {
  2747. CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
  2748. I.IsActiveIP->eraseFromParent();
  2749. }
  2750. }
  2751. static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
  2752. if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
  2753. if (uop->getOpcode() == UO_AddrOf)
  2754. return uop->getSubExpr();
  2755. return nullptr;
  2756. }
  2757. /// Emit an argument that's being passed call-by-writeback. That is,
  2758. /// we are passing the address of an __autoreleased temporary; it
  2759. /// might be copy-initialized with the current value of the given
  2760. /// address, but it will definitely be copied out of after the call.
  2761. static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
  2762. const ObjCIndirectCopyRestoreExpr *CRE) {
  2763. LValue srcLV;
  2764. // Make an optimistic effort to emit the address as an l-value.
  2765. // This can fail if the argument expression is more complicated.
  2766. if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
  2767. srcLV = CGF.EmitLValue(lvExpr);
  2768. // Otherwise, just emit it as a scalar.
  2769. } else {
  2770. Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
  2771. QualType srcAddrType =
  2772. CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2773. srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
  2774. }
  2775. Address srcAddr = srcLV.getAddress();
  2776. // The dest and src types don't necessarily match in LLVM terms
  2777. // because of the crazy ObjC compatibility rules.
  2778. llvm::PointerType *destType =
  2779. cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
  2780. // If the address is a constant null, just pass the appropriate null.
  2781. if (isProvablyNull(srcAddr.getPointer())) {
  2782. args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
  2783. CRE->getType());
  2784. return;
  2785. }
  2786. // Create the temporary.
  2787. Address temp = CGF.CreateTempAlloca(destType->getElementType(),
  2788. CGF.getPointerAlign(),
  2789. "icr.temp");
  2790. // Loading an l-value can introduce a cleanup if the l-value is __weak,
  2791. // and that cleanup will be conditional if we can't prove that the l-value
  2792. // isn't null, so we need to register a dominating point so that the cleanups
  2793. // system will make valid IR.
  2794. CodeGenFunction::ConditionalEvaluation condEval(CGF);
  2795. // Zero-initialize it if we're not doing a copy-initialization.
  2796. bool shouldCopy = CRE->shouldCopy();
  2797. if (!shouldCopy) {
  2798. llvm::Value *null =
  2799. llvm::ConstantPointerNull::get(
  2800. cast<llvm::PointerType>(destType->getElementType()));
  2801. CGF.Builder.CreateStore(null, temp);
  2802. }
  2803. llvm::BasicBlock *contBB = nullptr;
  2804. llvm::BasicBlock *originBB = nullptr;
  2805. // If the address is *not* known to be non-null, we need to switch.
  2806. llvm::Value *finalArgument;
  2807. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  2808. CGF.CGM.getDataLayout());
  2809. if (provablyNonNull) {
  2810. finalArgument = temp.getPointer();
  2811. } else {
  2812. llvm::Value *isNull =
  2813. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2814. finalArgument = CGF.Builder.CreateSelect(isNull,
  2815. llvm::ConstantPointerNull::get(destType),
  2816. temp.getPointer(), "icr.argument");
  2817. // If we need to copy, then the load has to be conditional, which
  2818. // means we need control flow.
  2819. if (shouldCopy) {
  2820. originBB = CGF.Builder.GetInsertBlock();
  2821. contBB = CGF.createBasicBlock("icr.cont");
  2822. llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
  2823. CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
  2824. CGF.EmitBlock(copyBB);
  2825. condEval.begin(CGF);
  2826. }
  2827. }
  2828. llvm::Value *valueToUse = nullptr;
  2829. // Perform a copy if necessary.
  2830. if (shouldCopy) {
  2831. RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
  2832. assert(srcRV.isScalar());
  2833. llvm::Value *src = srcRV.getScalarVal();
  2834. src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
  2835. "icr.cast");
  2836. // Use an ordinary store, not a store-to-lvalue.
  2837. CGF.Builder.CreateStore(src, temp);
  2838. // If optimization is enabled, and the value was held in a
  2839. // __strong variable, we need to tell the optimizer that this
  2840. // value has to stay alive until we're doing the store back.
  2841. // This is because the temporary is effectively unretained,
  2842. // and so otherwise we can violate the high-level semantics.
  2843. if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2844. srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
  2845. valueToUse = src;
  2846. }
  2847. }
  2848. // Finish the control flow if we needed it.
  2849. if (shouldCopy && !provablyNonNull) {
  2850. llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
  2851. CGF.EmitBlock(contBB);
  2852. // Make a phi for the value to intrinsically use.
  2853. if (valueToUse) {
  2854. llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
  2855. "icr.to-use");
  2856. phiToUse->addIncoming(valueToUse, copyBB);
  2857. phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
  2858. originBB);
  2859. valueToUse = phiToUse;
  2860. }
  2861. condEval.end(CGF);
  2862. }
  2863. args.addWriteback(srcLV, temp, valueToUse);
  2864. args.add(RValue::get(finalArgument), CRE->getType());
  2865. }
  2866. void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
  2867. assert(!StackBase);
  2868. // Save the stack.
  2869. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  2870. StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
  2871. }
  2872. void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
  2873. if (StackBase) {
  2874. // Restore the stack after the call.
  2875. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  2876. CGF.Builder.CreateCall(F, StackBase);
  2877. }
  2878. }
  2879. void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
  2880. SourceLocation ArgLoc,
  2881. AbstractCallee AC,
  2882. unsigned ParmNum) {
  2883. if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
  2884. SanOpts.has(SanitizerKind::NullabilityArg)))
  2885. return;
  2886. // The param decl may be missing in a variadic function.
  2887. auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
  2888. unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
  2889. // Prefer the nonnull attribute if it's present.
  2890. const NonNullAttr *NNAttr = nullptr;
  2891. if (SanOpts.has(SanitizerKind::NonnullAttribute))
  2892. NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
  2893. bool CanCheckNullability = false;
  2894. if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
  2895. auto Nullability = PVD->getType()->getNullability(getContext());
  2896. CanCheckNullability = Nullability &&
  2897. *Nullability == NullabilityKind::NonNull &&
  2898. PVD->getTypeSourceInfo();
  2899. }
  2900. if (!NNAttr && !CanCheckNullability)
  2901. return;
  2902. SourceLocation AttrLoc;
  2903. SanitizerMask CheckKind;
  2904. SanitizerHandler Handler;
  2905. if (NNAttr) {
  2906. AttrLoc = NNAttr->getLocation();
  2907. CheckKind = SanitizerKind::NonnullAttribute;
  2908. Handler = SanitizerHandler::NonnullArg;
  2909. } else {
  2910. AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
  2911. CheckKind = SanitizerKind::NullabilityArg;
  2912. Handler = SanitizerHandler::NullabilityArg;
  2913. }
  2914. SanitizerScope SanScope(this);
  2915. assert(RV.isScalar());
  2916. llvm::Value *V = RV.getScalarVal();
  2917. llvm::Value *Cond =
  2918. Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
  2919. llvm::Constant *StaticData[] = {
  2920. EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
  2921. llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
  2922. };
  2923. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
  2924. }
  2925. void CodeGenFunction::EmitCallArgs(
  2926. CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2927. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2928. AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
  2929. assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
  2930. // We *have* to evaluate arguments from right to left in the MS C++ ABI,
  2931. // because arguments are destroyed left to right in the callee. As a special
  2932. // case, there are certain language constructs that require left-to-right
  2933. // evaluation, and in those cases we consider the evaluation order requirement
  2934. // to trump the "destruction order is reverse construction order" guarantee.
  2935. bool LeftToRight =
  2936. CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
  2937. ? Order == EvaluationOrder::ForceLeftToRight
  2938. : Order != EvaluationOrder::ForceRightToLeft;
  2939. auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
  2940. RValue EmittedArg) {
  2941. if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
  2942. return;
  2943. auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
  2944. if (PS == nullptr)
  2945. return;
  2946. const auto &Context = getContext();
  2947. auto SizeTy = Context.getSizeType();
  2948. auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
  2949. assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
  2950. llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
  2951. EmittedArg.getScalarVal(),
  2952. PS->isDynamic());
  2953. Args.add(RValue::get(V), SizeTy);
  2954. // If we're emitting args in reverse, be sure to do so with
  2955. // pass_object_size, as well.
  2956. if (!LeftToRight)
  2957. std::swap(Args.back(), *(&Args.back() - 1));
  2958. };
  2959. // Insert a stack save if we're going to need any inalloca args.
  2960. bool HasInAllocaArgs = false;
  2961. if (CGM.getTarget().getCXXABI().isMicrosoft()) {
  2962. for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
  2963. I != E && !HasInAllocaArgs; ++I)
  2964. HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
  2965. if (HasInAllocaArgs) {
  2966. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2967. Args.allocateArgumentMemory(*this);
  2968. }
  2969. }
  2970. // Evaluate each argument in the appropriate order.
  2971. size_t CallArgsStart = Args.size();
  2972. for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
  2973. unsigned Idx = LeftToRight ? I : E - I - 1;
  2974. CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
  2975. unsigned InitialArgSize = Args.size();
  2976. // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
  2977. // the argument and parameter match or the objc method is parameterized.
  2978. assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
  2979. getContext().hasSameUnqualifiedType((*Arg)->getType(),
  2980. ArgTypes[Idx]) ||
  2981. (isa<ObjCMethodDecl>(AC.getDecl()) &&
  2982. isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
  2983. "Argument and parameter types don't match");
  2984. EmitCallArg(Args, *Arg, ArgTypes[Idx]);
  2985. // In particular, we depend on it being the last arg in Args, and the
  2986. // objectsize bits depend on there only being one arg if !LeftToRight.
  2987. assert(InitialArgSize + 1 == Args.size() &&
  2988. "The code below depends on only adding one arg per EmitCallArg");
  2989. (void)InitialArgSize;
  2990. // Since pointer argument are never emitted as LValue, it is safe to emit
  2991. // non-null argument check for r-value only.
  2992. if (!Args.back().hasLValue()) {
  2993. RValue RVArg = Args.back().getKnownRValue();
  2994. EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
  2995. ParamsToSkip + Idx);
  2996. // @llvm.objectsize should never have side-effects and shouldn't need
  2997. // destruction/cleanups, so we can safely "emit" it after its arg,
  2998. // regardless of right-to-leftness
  2999. MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
  3000. }
  3001. }
  3002. if (!LeftToRight) {
  3003. // Un-reverse the arguments we just evaluated so they match up with the LLVM
  3004. // IR function.
  3005. std::reverse(Args.begin() + CallArgsStart, Args.end());
  3006. }
  3007. }
  3008. namespace {
  3009. struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
  3010. DestroyUnpassedArg(Address Addr, QualType Ty)
  3011. : Addr(Addr), Ty(Ty) {}
  3012. Address Addr;
  3013. QualType Ty;
  3014. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3015. QualType::DestructionKind DtorKind = Ty.isDestructedType();
  3016. if (DtorKind == QualType::DK_cxx_destructor) {
  3017. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  3018. assert(!Dtor->isTrivial());
  3019. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
  3020. /*Delegating=*/false, Addr);
  3021. } else {
  3022. CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
  3023. }
  3024. }
  3025. };
  3026. struct DisableDebugLocationUpdates {
  3027. CodeGenFunction &CGF;
  3028. bool disabledDebugInfo;
  3029. DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
  3030. if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
  3031. CGF.disableDebugInfo();
  3032. }
  3033. ~DisableDebugLocationUpdates() {
  3034. if (disabledDebugInfo)
  3035. CGF.enableDebugInfo();
  3036. }
  3037. };
  3038. } // end anonymous namespace
  3039. RValue CallArg::getRValue(CodeGenFunction &CGF) const {
  3040. if (!HasLV)
  3041. return RV;
  3042. LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
  3043. CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
  3044. LV.isVolatile());
  3045. IsUsed = true;
  3046. return RValue::getAggregate(Copy.getAddress());
  3047. }
  3048. void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
  3049. LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
  3050. if (!HasLV && RV.isScalar())
  3051. CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*init=*/true);
  3052. else if (!HasLV && RV.isComplex())
  3053. CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
  3054. else {
  3055. auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
  3056. LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
  3057. // We assume that call args are never copied into subobjects.
  3058. CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
  3059. HasLV ? LV.isVolatileQualified()
  3060. : RV.isVolatileQualified());
  3061. }
  3062. IsUsed = true;
  3063. }
  3064. void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
  3065. QualType type) {
  3066. DisableDebugLocationUpdates Dis(*this, E);
  3067. if (const ObjCIndirectCopyRestoreExpr *CRE
  3068. = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
  3069. assert(getLangOpts().ObjCAutoRefCount);
  3070. return emitWritebackArg(*this, args, CRE);
  3071. }
  3072. assert(type->isReferenceType() == E->isGLValue() &&
  3073. "reference binding to unmaterialized r-value!");
  3074. if (E->isGLValue()) {
  3075. assert(E->getObjectKind() == OK_Ordinary);
  3076. return args.add(EmitReferenceBindingToExpr(E), type);
  3077. }
  3078. bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
  3079. // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
  3080. // However, we still have to push an EH-only cleanup in case we unwind before
  3081. // we make it to the call.
  3082. if (HasAggregateEvalKind &&
  3083. type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  3084. // If we're using inalloca, use the argument memory. Otherwise, use a
  3085. // temporary.
  3086. AggValueSlot Slot;
  3087. if (args.isUsingInAlloca())
  3088. Slot = createPlaceholderSlot(*this, type);
  3089. else
  3090. Slot = CreateAggTemp(type, "agg.tmp");
  3091. bool DestroyedInCallee = true, NeedsEHCleanup = true;
  3092. if (const auto *RD = type->getAsCXXRecordDecl())
  3093. DestroyedInCallee = RD->hasNonTrivialDestructor();
  3094. else
  3095. NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
  3096. if (DestroyedInCallee)
  3097. Slot.setExternallyDestructed();
  3098. EmitAggExpr(E, Slot);
  3099. RValue RV = Slot.asRValue();
  3100. args.add(RV, type);
  3101. if (DestroyedInCallee && NeedsEHCleanup) {
  3102. // Create a no-op GEP between the placeholder and the cleanup so we can
  3103. // RAUW it successfully. It also serves as a marker of the first
  3104. // instruction where the cleanup is active.
  3105. pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
  3106. type);
  3107. // This unreachable is a temporary marker which will be removed later.
  3108. llvm::Instruction *IsActive = Builder.CreateUnreachable();
  3109. args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
  3110. }
  3111. return;
  3112. }
  3113. if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
  3114. cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
  3115. LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
  3116. assert(L.isSimple());
  3117. args.addUncopiedAggregate(L, type);
  3118. return;
  3119. }
  3120. args.add(EmitAnyExprToTemp(E), type);
  3121. }
  3122. QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
  3123. // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
  3124. // implicitly widens null pointer constants that are arguments to varargs
  3125. // functions to pointer-sized ints.
  3126. if (!getTarget().getTriple().isOSWindows())
  3127. return Arg->getType();
  3128. if (Arg->getType()->isIntegerType() &&
  3129. getContext().getTypeSize(Arg->getType()) <
  3130. getContext().getTargetInfo().getPointerWidth(0) &&
  3131. Arg->isNullPointerConstant(getContext(),
  3132. Expr::NPC_ValueDependentIsNotNull)) {
  3133. return getContext().getIntPtrType();
  3134. }
  3135. return Arg->getType();
  3136. }
  3137. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3138. // optimizer it can aggressively ignore unwind edges.
  3139. void
  3140. CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
  3141. if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  3142. !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  3143. Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
  3144. CGM.getNoObjCARCExceptionsMetadata());
  3145. }
  3146. /// Emits a call to the given no-arguments nounwind runtime function.
  3147. llvm::CallInst *
  3148. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3149. const llvm::Twine &name) {
  3150. return EmitNounwindRuntimeCall(callee, None, name);
  3151. }
  3152. /// Emits a call to the given nounwind runtime function.
  3153. llvm::CallInst *
  3154. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3155. ArrayRef<llvm::Value *> args,
  3156. const llvm::Twine &name) {
  3157. llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
  3158. call->setDoesNotThrow();
  3159. return call;
  3160. }
  3161. /// Emits a simple call (never an invoke) to the given no-arguments
  3162. /// runtime function.
  3163. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3164. const llvm::Twine &name) {
  3165. return EmitRuntimeCall(callee, None, name);
  3166. }
  3167. // Calls which may throw must have operand bundles indicating which funclet
  3168. // they are nested within.
  3169. SmallVector<llvm::OperandBundleDef, 1>
  3170. CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
  3171. SmallVector<llvm::OperandBundleDef, 1> BundleList;
  3172. // There is no need for a funclet operand bundle if we aren't inside a
  3173. // funclet.
  3174. if (!CurrentFuncletPad)
  3175. return BundleList;
  3176. // Skip intrinsics which cannot throw.
  3177. auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
  3178. if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
  3179. return BundleList;
  3180. BundleList.emplace_back("funclet", CurrentFuncletPad);
  3181. return BundleList;
  3182. }
  3183. /// Emits a simple call (never an invoke) to the given runtime function.
  3184. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3185. ArrayRef<llvm::Value *> args,
  3186. const llvm::Twine &name) {
  3187. llvm::CallInst *call = Builder.CreateCall(
  3188. callee, args, getBundlesForFunclet(callee.getCallee()), name);
  3189. call->setCallingConv(getRuntimeCC());
  3190. return call;
  3191. }
  3192. /// Emits a call or invoke to the given noreturn runtime function.
  3193. void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
  3194. llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
  3195. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3196. getBundlesForFunclet(callee.getCallee());
  3197. if (getInvokeDest()) {
  3198. llvm::InvokeInst *invoke =
  3199. Builder.CreateInvoke(callee,
  3200. getUnreachableBlock(),
  3201. getInvokeDest(),
  3202. args,
  3203. BundleList);
  3204. invoke->setDoesNotReturn();
  3205. invoke->setCallingConv(getRuntimeCC());
  3206. } else {
  3207. llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
  3208. call->setDoesNotReturn();
  3209. call->setCallingConv(getRuntimeCC());
  3210. Builder.CreateUnreachable();
  3211. }
  3212. }
  3213. /// Emits a call or invoke instruction to the given nullary runtime function.
  3214. llvm::CallBase *
  3215. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3216. const Twine &name) {
  3217. return EmitRuntimeCallOrInvoke(callee, None, name);
  3218. }
  3219. /// Emits a call or invoke instruction to the given runtime function.
  3220. llvm::CallBase *
  3221. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3222. ArrayRef<llvm::Value *> args,
  3223. const Twine &name) {
  3224. llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
  3225. call->setCallingConv(getRuntimeCC());
  3226. return call;
  3227. }
  3228. /// Emits a call or invoke instruction to the given function, depending
  3229. /// on the current state of the EH stack.
  3230. llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
  3231. ArrayRef<llvm::Value *> Args,
  3232. const Twine &Name) {
  3233. llvm::BasicBlock *InvokeDest = getInvokeDest();
  3234. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3235. getBundlesForFunclet(Callee.getCallee());
  3236. llvm::CallBase *Inst;
  3237. if (!InvokeDest)
  3238. Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
  3239. else {
  3240. llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
  3241. Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
  3242. Name);
  3243. EmitBlock(ContBB);
  3244. }
  3245. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3246. // optimizer it can aggressively ignore unwind edges.
  3247. if (CGM.getLangOpts().ObjCAutoRefCount)
  3248. AddObjCARCExceptionMetadata(Inst);
  3249. return Inst;
  3250. }
  3251. void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
  3252. llvm::Value *New) {
  3253. DeferredReplacements.push_back(std::make_pair(Old, New));
  3254. }
  3255. RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
  3256. const CGCallee &Callee,
  3257. ReturnValueSlot ReturnValue,
  3258. const CallArgList &CallArgs,
  3259. llvm::CallBase **callOrInvoke,
  3260. SourceLocation Loc) {
  3261. // FIXME: We no longer need the types from CallArgs; lift up and simplify.
  3262. assert(Callee.isOrdinary() || Callee.isVirtual());
  3263. // Handle struct-return functions by passing a pointer to the
  3264. // location that we would like to return into.
  3265. QualType RetTy = CallInfo.getReturnType();
  3266. const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
  3267. llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
  3268. #ifndef NDEBUG
  3269. if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
  3270. // For an inalloca varargs function, we don't expect CallInfo to match the
  3271. // function pointer's type, because the inalloca struct a will have extra
  3272. // fields in it for the varargs parameters. Code later in this function
  3273. // bitcasts the function pointer to the type derived from CallInfo.
  3274. //
  3275. // In other cases, we assert that the types match up (until pointers stop
  3276. // having pointee types).
  3277. llvm::Type *TypeFromVal;
  3278. if (Callee.isVirtual())
  3279. TypeFromVal = Callee.getVirtualFunctionType();
  3280. else
  3281. TypeFromVal =
  3282. Callee.getFunctionPointer()->getType()->getPointerElementType();
  3283. assert(IRFuncTy == TypeFromVal);
  3284. }
  3285. #endif
  3286. // 1. Set up the arguments.
  3287. // If we're using inalloca, insert the allocation after the stack save.
  3288. // FIXME: Do this earlier rather than hacking it in here!
  3289. Address ArgMemory = Address::invalid();
  3290. if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
  3291. const llvm::DataLayout &DL = CGM.getDataLayout();
  3292. llvm::Instruction *IP = CallArgs.getStackBase();
  3293. llvm::AllocaInst *AI;
  3294. if (IP) {
  3295. IP = IP->getNextNode();
  3296. AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
  3297. "argmem", IP);
  3298. } else {
  3299. AI = CreateTempAlloca(ArgStruct, "argmem");
  3300. }
  3301. auto Align = CallInfo.getArgStructAlignment();
  3302. AI->setAlignment(Align.getQuantity());
  3303. AI->setUsedWithInAlloca(true);
  3304. assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
  3305. ArgMemory = Address(AI, Align);
  3306. }
  3307. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
  3308. SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
  3309. // If the call returns a temporary with struct return, create a temporary
  3310. // alloca to hold the result, unless one is given to us.
  3311. Address SRetPtr = Address::invalid();
  3312. Address SRetAlloca = Address::invalid();
  3313. llvm::Value *UnusedReturnSizePtr = nullptr;
  3314. if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
  3315. if (!ReturnValue.isNull()) {
  3316. SRetPtr = ReturnValue.getValue();
  3317. } else {
  3318. SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
  3319. if (HaveInsertPoint() && ReturnValue.isUnused()) {
  3320. uint64_t size =
  3321. CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
  3322. UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
  3323. }
  3324. }
  3325. if (IRFunctionArgs.hasSRetArg()) {
  3326. IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
  3327. } else if (RetAI.isInAlloca()) {
  3328. Address Addr =
  3329. Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
  3330. Builder.CreateStore(SRetPtr.getPointer(), Addr);
  3331. }
  3332. }
  3333. Address swiftErrorTemp = Address::invalid();
  3334. Address swiftErrorArg = Address::invalid();
  3335. // Translate all of the arguments as necessary to match the IR lowering.
  3336. assert(CallInfo.arg_size() == CallArgs.size() &&
  3337. "Mismatch between function signature & arguments.");
  3338. unsigned ArgNo = 0;
  3339. CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
  3340. for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
  3341. I != E; ++I, ++info_it, ++ArgNo) {
  3342. const ABIArgInfo &ArgInfo = info_it->info;
  3343. // Insert a padding argument to ensure proper alignment.
  3344. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  3345. IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  3346. llvm::UndefValue::get(ArgInfo.getPaddingType());
  3347. unsigned FirstIRArg, NumIRArgs;
  3348. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  3349. switch (ArgInfo.getKind()) {
  3350. case ABIArgInfo::InAlloca: {
  3351. assert(NumIRArgs == 0);
  3352. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  3353. if (I->isAggregate()) {
  3354. // Replace the placeholder with the appropriate argument slot GEP.
  3355. Address Addr = I->hasLValue()
  3356. ? I->getKnownLValue().getAddress()
  3357. : I->getKnownRValue().getAggregateAddress();
  3358. llvm::Instruction *Placeholder =
  3359. cast<llvm::Instruction>(Addr.getPointer());
  3360. CGBuilderTy::InsertPoint IP = Builder.saveIP();
  3361. Builder.SetInsertPoint(Placeholder);
  3362. Addr =
  3363. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  3364. Builder.restoreIP(IP);
  3365. deferPlaceholderReplacement(Placeholder, Addr.getPointer());
  3366. } else {
  3367. // Store the RValue into the argument struct.
  3368. Address Addr =
  3369. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  3370. unsigned AS = Addr.getType()->getPointerAddressSpace();
  3371. llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
  3372. // There are some cases where a trivial bitcast is not avoidable. The
  3373. // definition of a type later in a translation unit may change it's type
  3374. // from {}* to (%struct.foo*)*.
  3375. if (Addr.getType() != MemType)
  3376. Addr = Builder.CreateBitCast(Addr, MemType);
  3377. I->copyInto(*this, Addr);
  3378. }
  3379. break;
  3380. }
  3381. case ABIArgInfo::Indirect: {
  3382. assert(NumIRArgs == 1);
  3383. if (!I->isAggregate()) {
  3384. // Make a temporary alloca to pass the argument.
  3385. Address Addr = CreateMemTempWithoutCast(
  3386. I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
  3387. IRCallArgs[FirstIRArg] = Addr.getPointer();
  3388. I->copyInto(*this, Addr);
  3389. } else {
  3390. // We want to avoid creating an unnecessary temporary+copy here;
  3391. // however, we need one in three cases:
  3392. // 1. If the argument is not byval, and we are required to copy the
  3393. // source. (This case doesn't occur on any common architecture.)
  3394. // 2. If the argument is byval, RV is not sufficiently aligned, and
  3395. // we cannot force it to be sufficiently aligned.
  3396. // 3. If the argument is byval, but RV is not located in default
  3397. // or alloca address space.
  3398. Address Addr = I->hasLValue()
  3399. ? I->getKnownLValue().getAddress()
  3400. : I->getKnownRValue().getAggregateAddress();
  3401. llvm::Value *V = Addr.getPointer();
  3402. CharUnits Align = ArgInfo.getIndirectAlign();
  3403. const llvm::DataLayout *TD = &CGM.getDataLayout();
  3404. assert((FirstIRArg >= IRFuncTy->getNumParams() ||
  3405. IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
  3406. TD->getAllocaAddrSpace()) &&
  3407. "indirect argument must be in alloca address space");
  3408. bool NeedCopy = false;
  3409. if (Addr.getAlignment() < Align &&
  3410. llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) <
  3411. Align.getQuantity()) {
  3412. NeedCopy = true;
  3413. } else if (I->hasLValue()) {
  3414. auto LV = I->getKnownLValue();
  3415. auto AS = LV.getAddressSpace();
  3416. if ((!ArgInfo.getIndirectByVal() &&
  3417. (LV.getAlignment() >=
  3418. getContext().getTypeAlignInChars(I->Ty)))) {
  3419. NeedCopy = true;
  3420. }
  3421. if (!getLangOpts().OpenCL) {
  3422. if ((ArgInfo.getIndirectByVal() &&
  3423. (AS != LangAS::Default &&
  3424. AS != CGM.getASTAllocaAddressSpace()))) {
  3425. NeedCopy = true;
  3426. }
  3427. }
  3428. // For OpenCL even if RV is located in default or alloca address space
  3429. // we don't want to perform address space cast for it.
  3430. else if ((ArgInfo.getIndirectByVal() &&
  3431. Addr.getType()->getAddressSpace() != IRFuncTy->
  3432. getParamType(FirstIRArg)->getPointerAddressSpace())) {
  3433. NeedCopy = true;
  3434. }
  3435. }
  3436. if (NeedCopy) {
  3437. // Create an aligned temporary, and copy to it.
  3438. Address AI = CreateMemTempWithoutCast(
  3439. I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
  3440. IRCallArgs[FirstIRArg] = AI.getPointer();
  3441. I->copyInto(*this, AI);
  3442. } else {
  3443. // Skip the extra memcpy call.
  3444. auto *T = V->getType()->getPointerElementType()->getPointerTo(
  3445. CGM.getDataLayout().getAllocaAddrSpace());
  3446. IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
  3447. *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
  3448. true);
  3449. }
  3450. }
  3451. break;
  3452. }
  3453. case ABIArgInfo::Ignore:
  3454. assert(NumIRArgs == 0);
  3455. break;
  3456. case ABIArgInfo::Extend:
  3457. case ABIArgInfo::Direct: {
  3458. if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
  3459. ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
  3460. ArgInfo.getDirectOffset() == 0) {
  3461. assert(NumIRArgs == 1);
  3462. llvm::Value *V;
  3463. if (!I->isAggregate())
  3464. V = I->getKnownRValue().getScalarVal();
  3465. else
  3466. V = Builder.CreateLoad(
  3467. I->hasLValue() ? I->getKnownLValue().getAddress()
  3468. : I->getKnownRValue().getAggregateAddress());
  3469. // Implement swifterror by copying into a new swifterror argument.
  3470. // We'll write back in the normal path out of the call.
  3471. if (CallInfo.getExtParameterInfo(ArgNo).getABI()
  3472. == ParameterABI::SwiftErrorResult) {
  3473. assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
  3474. QualType pointeeTy = I->Ty->getPointeeType();
  3475. swiftErrorArg =
  3476. Address(V, getContext().getTypeAlignInChars(pointeeTy));
  3477. swiftErrorTemp =
  3478. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  3479. V = swiftErrorTemp.getPointer();
  3480. cast<llvm::AllocaInst>(V)->setSwiftError(true);
  3481. llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
  3482. Builder.CreateStore(errorValue, swiftErrorTemp);
  3483. }
  3484. // We might have to widen integers, but we should never truncate.
  3485. if (ArgInfo.getCoerceToType() != V->getType() &&
  3486. V->getType()->isIntegerTy())
  3487. V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
  3488. // If the argument doesn't match, perform a bitcast to coerce it. This
  3489. // can happen due to trivial type mismatches.
  3490. if (FirstIRArg < IRFuncTy->getNumParams() &&
  3491. V->getType() != IRFuncTy->getParamType(FirstIRArg))
  3492. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
  3493. IRCallArgs[FirstIRArg] = V;
  3494. break;
  3495. }
  3496. // FIXME: Avoid the conversion through memory if possible.
  3497. Address Src = Address::invalid();
  3498. if (!I->isAggregate()) {
  3499. Src = CreateMemTemp(I->Ty, "coerce");
  3500. I->copyInto(*this, Src);
  3501. } else {
  3502. Src = I->hasLValue() ? I->getKnownLValue().getAddress()
  3503. : I->getKnownRValue().getAggregateAddress();
  3504. }
  3505. // If the value is offset in memory, apply the offset now.
  3506. Src = emitAddressAtOffset(*this, Src, ArgInfo);
  3507. // Fast-isel and the optimizer generally like scalar values better than
  3508. // FCAs, so we flatten them if this is safe to do for this argument.
  3509. llvm::StructType *STy =
  3510. dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
  3511. if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  3512. llvm::Type *SrcTy = Src.getType()->getElementType();
  3513. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3514. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
  3515. // If the source type is smaller than the destination type of the
  3516. // coerce-to logic, copy the source value into a temp alloca the size
  3517. // of the destination type to allow loading all of it. The bits past
  3518. // the source value are left undef.
  3519. if (SrcSize < DstSize) {
  3520. Address TempAlloca
  3521. = CreateTempAlloca(STy, Src.getAlignment(),
  3522. Src.getName() + ".coerce");
  3523. Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
  3524. Src = TempAlloca;
  3525. } else {
  3526. Src = Builder.CreateBitCast(Src,
  3527. STy->getPointerTo(Src.getAddressSpace()));
  3528. }
  3529. assert(NumIRArgs == STy->getNumElements());
  3530. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  3531. Address EltPtr = Builder.CreateStructGEP(Src, i);
  3532. llvm::Value *LI = Builder.CreateLoad(EltPtr);
  3533. IRCallArgs[FirstIRArg + i] = LI;
  3534. }
  3535. } else {
  3536. // In the simple case, just pass the coerced loaded value.
  3537. assert(NumIRArgs == 1);
  3538. IRCallArgs[FirstIRArg] =
  3539. CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
  3540. }
  3541. break;
  3542. }
  3543. case ABIArgInfo::CoerceAndExpand: {
  3544. auto coercionType = ArgInfo.getCoerceAndExpandType();
  3545. auto layout = CGM.getDataLayout().getStructLayout(coercionType);
  3546. llvm::Value *tempSize = nullptr;
  3547. Address addr = Address::invalid();
  3548. Address AllocaAddr = Address::invalid();
  3549. if (I->isAggregate()) {
  3550. addr = I->hasLValue() ? I->getKnownLValue().getAddress()
  3551. : I->getKnownRValue().getAggregateAddress();
  3552. } else {
  3553. RValue RV = I->getKnownRValue();
  3554. assert(RV.isScalar()); // complex should always just be direct
  3555. llvm::Type *scalarType = RV.getScalarVal()->getType();
  3556. auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
  3557. auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
  3558. // Materialize to a temporary.
  3559. addr = CreateTempAlloca(RV.getScalarVal()->getType(),
  3560. CharUnits::fromQuantity(std::max(
  3561. layout->getAlignment(), scalarAlign)),
  3562. "tmp",
  3563. /*ArraySize=*/nullptr, &AllocaAddr);
  3564. tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
  3565. Builder.CreateStore(RV.getScalarVal(), addr);
  3566. }
  3567. addr = Builder.CreateElementBitCast(addr, coercionType);
  3568. unsigned IRArgPos = FirstIRArg;
  3569. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  3570. llvm::Type *eltType = coercionType->getElementType(i);
  3571. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  3572. Address eltAddr = Builder.CreateStructGEP(addr, i);
  3573. llvm::Value *elt = Builder.CreateLoad(eltAddr);
  3574. IRCallArgs[IRArgPos++] = elt;
  3575. }
  3576. assert(IRArgPos == FirstIRArg + NumIRArgs);
  3577. if (tempSize) {
  3578. EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
  3579. }
  3580. break;
  3581. }
  3582. case ABIArgInfo::Expand:
  3583. unsigned IRArgPos = FirstIRArg;
  3584. ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
  3585. assert(IRArgPos == FirstIRArg + NumIRArgs);
  3586. break;
  3587. }
  3588. }
  3589. const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
  3590. llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
  3591. // If we're using inalloca, set up that argument.
  3592. if (ArgMemory.isValid()) {
  3593. llvm::Value *Arg = ArgMemory.getPointer();
  3594. if (CallInfo.isVariadic()) {
  3595. // When passing non-POD arguments by value to variadic functions, we will
  3596. // end up with a variadic prototype and an inalloca call site. In such
  3597. // cases, we can't do any parameter mismatch checks. Give up and bitcast
  3598. // the callee.
  3599. unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
  3600. CalleePtr =
  3601. Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
  3602. } else {
  3603. llvm::Type *LastParamTy =
  3604. IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
  3605. if (Arg->getType() != LastParamTy) {
  3606. #ifndef NDEBUG
  3607. // Assert that these structs have equivalent element types.
  3608. llvm::StructType *FullTy = CallInfo.getArgStruct();
  3609. llvm::StructType *DeclaredTy = cast<llvm::StructType>(
  3610. cast<llvm::PointerType>(LastParamTy)->getElementType());
  3611. assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
  3612. for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
  3613. DE = DeclaredTy->element_end(),
  3614. FI = FullTy->element_begin();
  3615. DI != DE; ++DI, ++FI)
  3616. assert(*DI == *FI);
  3617. #endif
  3618. Arg = Builder.CreateBitCast(Arg, LastParamTy);
  3619. }
  3620. }
  3621. assert(IRFunctionArgs.hasInallocaArg());
  3622. IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
  3623. }
  3624. // 2. Prepare the function pointer.
  3625. // If the callee is a bitcast of a non-variadic function to have a
  3626. // variadic function pointer type, check to see if we can remove the
  3627. // bitcast. This comes up with unprototyped functions.
  3628. //
  3629. // This makes the IR nicer, but more importantly it ensures that we
  3630. // can inline the function at -O0 if it is marked always_inline.
  3631. auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
  3632. llvm::Value *Ptr) -> llvm::Function * {
  3633. if (!CalleeFT->isVarArg())
  3634. return nullptr;
  3635. // Get underlying value if it's a bitcast
  3636. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
  3637. if (CE->getOpcode() == llvm::Instruction::BitCast)
  3638. Ptr = CE->getOperand(0);
  3639. }
  3640. llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
  3641. if (!OrigFn)
  3642. return nullptr;
  3643. llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
  3644. // If the original type is variadic, or if any of the component types
  3645. // disagree, we cannot remove the cast.
  3646. if (OrigFT->isVarArg() ||
  3647. OrigFT->getNumParams() != CalleeFT->getNumParams() ||
  3648. OrigFT->getReturnType() != CalleeFT->getReturnType())
  3649. return nullptr;
  3650. for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
  3651. if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
  3652. return nullptr;
  3653. return OrigFn;
  3654. };
  3655. if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
  3656. CalleePtr = OrigFn;
  3657. IRFuncTy = OrigFn->getFunctionType();
  3658. }
  3659. // 3. Perform the actual call.
  3660. // Deactivate any cleanups that we're supposed to do immediately before
  3661. // the call.
  3662. if (!CallArgs.getCleanupsToDeactivate().empty())
  3663. deactivateArgCleanupsBeforeCall(*this, CallArgs);
  3664. // Assert that the arguments we computed match up. The IR verifier
  3665. // will catch this, but this is a common enough source of problems
  3666. // during IRGen changes that it's way better for debugging to catch
  3667. // it ourselves here.
  3668. #ifndef NDEBUG
  3669. assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
  3670. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  3671. // Inalloca argument can have different type.
  3672. if (IRFunctionArgs.hasInallocaArg() &&
  3673. i == IRFunctionArgs.getInallocaArgNo())
  3674. continue;
  3675. if (i < IRFuncTy->getNumParams())
  3676. assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
  3677. }
  3678. #endif
  3679. // Update the largest vector width if any arguments have vector types.
  3680. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  3681. if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
  3682. LargestVectorWidth = std::max(LargestVectorWidth,
  3683. VT->getPrimitiveSizeInBits());
  3684. }
  3685. // Compute the calling convention and attributes.
  3686. unsigned CallingConv;
  3687. llvm::AttributeList Attrs;
  3688. CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
  3689. Callee.getAbstractInfo(), Attrs, CallingConv,
  3690. /*AttrOnCallSite=*/true);
  3691. // Apply some call-site-specific attributes.
  3692. // TODO: work this into building the attribute set.
  3693. // Apply always_inline to all calls within flatten functions.
  3694. // FIXME: should this really take priority over __try, below?
  3695. if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
  3696. !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
  3697. Callee.getAbstractInfo()
  3698. .getCalleeDecl()
  3699. .getDecl()
  3700. ->hasAttr<NoInlineAttr>())) {
  3701. Attrs =
  3702. Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
  3703. llvm::Attribute::AlwaysInline);
  3704. }
  3705. // Disable inlining inside SEH __try blocks.
  3706. if (isSEHTryScope()) {
  3707. Attrs =
  3708. Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
  3709. llvm::Attribute::NoInline);
  3710. }
  3711. // Decide whether to use a call or an invoke.
  3712. bool CannotThrow;
  3713. if (currentFunctionUsesSEHTry()) {
  3714. // SEH cares about asynchronous exceptions, so everything can "throw."
  3715. CannotThrow = false;
  3716. } else if (isCleanupPadScope() &&
  3717. EHPersonality::get(*this).isMSVCXXPersonality()) {
  3718. // The MSVC++ personality will implicitly terminate the program if an
  3719. // exception is thrown during a cleanup outside of a try/catch.
  3720. // We don't need to model anything in IR to get this behavior.
  3721. CannotThrow = true;
  3722. } else {
  3723. // Otherwise, nounwind call sites will never throw.
  3724. CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
  3725. llvm::Attribute::NoUnwind);
  3726. }
  3727. // If we made a temporary, be sure to clean up after ourselves. Note that we
  3728. // can't depend on being inside of an ExprWithCleanups, so we need to manually
  3729. // pop this cleanup later on. Being eager about this is OK, since this
  3730. // temporary is 'invisible' outside of the callee.
  3731. if (UnusedReturnSizePtr)
  3732. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
  3733. UnusedReturnSizePtr);
  3734. llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
  3735. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3736. getBundlesForFunclet(CalleePtr);
  3737. // Emit the actual call/invoke instruction.
  3738. llvm::CallBase *CI;
  3739. if (!InvokeDest) {
  3740. CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
  3741. } else {
  3742. llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
  3743. CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
  3744. BundleList);
  3745. EmitBlock(Cont);
  3746. }
  3747. if (callOrInvoke)
  3748. *callOrInvoke = CI;
  3749. // Apply the attributes and calling convention.
  3750. CI->setAttributes(Attrs);
  3751. CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  3752. // Apply various metadata.
  3753. if (!CI->getType()->isVoidTy())
  3754. CI->setName("call");
  3755. // Update largest vector width from the return type.
  3756. if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
  3757. LargestVectorWidth = std::max(LargestVectorWidth,
  3758. VT->getPrimitiveSizeInBits());
  3759. // Insert instrumentation or attach profile metadata at indirect call sites.
  3760. // For more details, see the comment before the definition of
  3761. // IPVK_IndirectCallTarget in InstrProfData.inc.
  3762. if (!CI->getCalledFunction())
  3763. PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
  3764. CI, CalleePtr);
  3765. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3766. // optimizer it can aggressively ignore unwind edges.
  3767. if (CGM.getLangOpts().ObjCAutoRefCount)
  3768. AddObjCARCExceptionMetadata(CI);
  3769. // Suppress tail calls if requested.
  3770. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
  3771. const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
  3772. if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
  3773. Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
  3774. }
  3775. // 4. Finish the call.
  3776. // If the call doesn't return, finish the basic block and clear the
  3777. // insertion point; this allows the rest of IRGen to discard
  3778. // unreachable code.
  3779. if (CI->doesNotReturn()) {
  3780. if (UnusedReturnSizePtr)
  3781. PopCleanupBlock();
  3782. // Strip away the noreturn attribute to better diagnose unreachable UB.
  3783. if (SanOpts.has(SanitizerKind::Unreachable)) {
  3784. // Also remove from function since CallBase::hasFnAttr additionally checks
  3785. // attributes of the called function.
  3786. if (auto *F = CI->getCalledFunction())
  3787. F->removeFnAttr(llvm::Attribute::NoReturn);
  3788. CI->removeAttribute(llvm::AttributeList::FunctionIndex,
  3789. llvm::Attribute::NoReturn);
  3790. // Avoid incompatibility with ASan which relies on the `noreturn`
  3791. // attribute to insert handler calls.
  3792. if (SanOpts.hasOneOf(SanitizerKind::Address |
  3793. SanitizerKind::KernelAddress)) {
  3794. SanitizerScope SanScope(this);
  3795. llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
  3796. Builder.SetInsertPoint(CI);
  3797. auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  3798. llvm::FunctionCallee Fn =
  3799. CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
  3800. EmitNounwindRuntimeCall(Fn);
  3801. }
  3802. }
  3803. EmitUnreachable(Loc);
  3804. Builder.ClearInsertionPoint();
  3805. // FIXME: For now, emit a dummy basic block because expr emitters in
  3806. // generally are not ready to handle emitting expressions at unreachable
  3807. // points.
  3808. EnsureInsertPoint();
  3809. // Return a reasonable RValue.
  3810. return GetUndefRValue(RetTy);
  3811. }
  3812. // Perform the swifterror writeback.
  3813. if (swiftErrorTemp.isValid()) {
  3814. llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
  3815. Builder.CreateStore(errorResult, swiftErrorArg);
  3816. }
  3817. // Emit any call-associated writebacks immediately. Arguably this
  3818. // should happen after any return-value munging.
  3819. if (CallArgs.hasWritebacks())
  3820. emitWritebacks(*this, CallArgs);
  3821. // The stack cleanup for inalloca arguments has to run out of the normal
  3822. // lexical order, so deactivate it and run it manually here.
  3823. CallArgs.freeArgumentMemory(*this);
  3824. // Extract the return value.
  3825. RValue Ret = [&] {
  3826. switch (RetAI.getKind()) {
  3827. case ABIArgInfo::CoerceAndExpand: {
  3828. auto coercionType = RetAI.getCoerceAndExpandType();
  3829. Address addr = SRetPtr;
  3830. addr = Builder.CreateElementBitCast(addr, coercionType);
  3831. assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
  3832. bool requiresExtract = isa<llvm::StructType>(CI->getType());
  3833. unsigned unpaddedIndex = 0;
  3834. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  3835. llvm::Type *eltType = coercionType->getElementType(i);
  3836. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  3837. Address eltAddr = Builder.CreateStructGEP(addr, i);
  3838. llvm::Value *elt = CI;
  3839. if (requiresExtract)
  3840. elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
  3841. else
  3842. assert(unpaddedIndex == 0);
  3843. Builder.CreateStore(elt, eltAddr);
  3844. }
  3845. // FALLTHROUGH
  3846. LLVM_FALLTHROUGH;
  3847. }
  3848. case ABIArgInfo::InAlloca:
  3849. case ABIArgInfo::Indirect: {
  3850. RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
  3851. if (UnusedReturnSizePtr)
  3852. PopCleanupBlock();
  3853. return ret;
  3854. }
  3855. case ABIArgInfo::Ignore:
  3856. // If we are ignoring an argument that had a result, make sure to
  3857. // construct the appropriate return value for our caller.
  3858. return GetUndefRValue(RetTy);
  3859. case ABIArgInfo::Extend:
  3860. case ABIArgInfo::Direct: {
  3861. llvm::Type *RetIRTy = ConvertType(RetTy);
  3862. if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
  3863. switch (getEvaluationKind(RetTy)) {
  3864. case TEK_Complex: {
  3865. llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
  3866. llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
  3867. return RValue::getComplex(std::make_pair(Real, Imag));
  3868. }
  3869. case TEK_Aggregate: {
  3870. Address DestPtr = ReturnValue.getValue();
  3871. bool DestIsVolatile = ReturnValue.isVolatile();
  3872. if (!DestPtr.isValid()) {
  3873. DestPtr = CreateMemTemp(RetTy, "agg.tmp");
  3874. DestIsVolatile = false;
  3875. }
  3876. BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
  3877. return RValue::getAggregate(DestPtr);
  3878. }
  3879. case TEK_Scalar: {
  3880. // If the argument doesn't match, perform a bitcast to coerce it. This
  3881. // can happen due to trivial type mismatches.
  3882. llvm::Value *V = CI;
  3883. if (V->getType() != RetIRTy)
  3884. V = Builder.CreateBitCast(V, RetIRTy);
  3885. return RValue::get(V);
  3886. }
  3887. }
  3888. llvm_unreachable("bad evaluation kind");
  3889. }
  3890. Address DestPtr = ReturnValue.getValue();
  3891. bool DestIsVolatile = ReturnValue.isVolatile();
  3892. if (!DestPtr.isValid()) {
  3893. DestPtr = CreateMemTemp(RetTy, "coerce");
  3894. DestIsVolatile = false;
  3895. }
  3896. // If the value is offset in memory, apply the offset now.
  3897. Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
  3898. CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
  3899. return convertTempToRValue(DestPtr, RetTy, SourceLocation());
  3900. }
  3901. case ABIArgInfo::Expand:
  3902. llvm_unreachable("Invalid ABI kind for return argument");
  3903. }
  3904. llvm_unreachable("Unhandled ABIArgInfo::Kind");
  3905. } ();
  3906. // Emit the assume_aligned check on the return value.
  3907. const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
  3908. if (Ret.isScalar() && TargetDecl) {
  3909. if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
  3910. llvm::Value *OffsetValue = nullptr;
  3911. if (const auto *Offset = AA->getOffset())
  3912. OffsetValue = EmitScalarExpr(Offset);
  3913. llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
  3914. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
  3915. EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
  3916. AlignmentCI->getZExtValue(), OffsetValue);
  3917. } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
  3918. llvm::Value *AlignmentVal = CallArgs[AA->getParamIndex().getLLVMIndex()]
  3919. .getRValue(*this)
  3920. .getScalarVal();
  3921. EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
  3922. AlignmentVal);
  3923. }
  3924. }
  3925. return Ret;
  3926. }
  3927. CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
  3928. if (isVirtual()) {
  3929. const CallExpr *CE = getVirtualCallExpr();
  3930. return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
  3931. CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
  3932. CE ? CE->getBeginLoc() : SourceLocation());
  3933. }
  3934. return *this;
  3935. }
  3936. /* VarArg handling */
  3937. Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
  3938. VAListAddr = VE->isMicrosoftABI()
  3939. ? EmitMSVAListRef(VE->getSubExpr())
  3940. : EmitVAListRef(VE->getSubExpr());
  3941. QualType Ty = VE->getType();
  3942. if (VE->isMicrosoftABI())
  3943. return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
  3944. return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
  3945. }