CGCall.cpp 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753
  1. //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // These classes wrap the information about a call or function
  11. // definition used to handle ABI compliancy.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CGCall.h"
  15. #include "ABIInfo.h"
  16. #include "CGCXXABI.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "CGHLSLRuntime.h" // HLSL Change
  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/TargetInfo.h"
  25. #include "clang/CodeGen/CGFunctionInfo.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/ADT/StringExtras.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/InlineAsm.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. using namespace clang;
  36. using namespace CodeGen;
  37. /***/
  38. static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
  39. switch (CC) {
  40. default: return llvm::CallingConv::C;
  41. case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
  42. case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
  43. case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
  44. case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
  45. case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
  46. case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
  47. case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  48. case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
  49. // TODO: Add support for __pascal to LLVM.
  50. case CC_X86Pascal: return llvm::CallingConv::C;
  51. // TODO: Add support for __vectorcall to LLVM.
  52. case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
  53. case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
  54. case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
  55. }
  56. }
  57. /// Derives the 'this' type for codegen purposes, i.e. ignoring method
  58. /// qualification.
  59. /// FIXME: address space qualification?
  60. static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
  61. QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
  62. return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
  63. }
  64. /// Returns the canonical formal type of the given C++ method.
  65. static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
  66. return MD->getType()->getCanonicalTypeUnqualified()
  67. .getAs<FunctionProtoType>();
  68. }
  69. /// Returns the "extra-canonicalized" return type, which discards
  70. /// qualifiers on the return type. Codegen doesn't care about them,
  71. /// and it makes ABI code a little easier to be able to assume that
  72. /// all parameter and return types are top-level unqualified.
  73. static CanQualType GetReturnType(QualType RetTy) {
  74. return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
  75. }
  76. /// Arrange the argument and result information for a value of the given
  77. /// unprototyped freestanding function type.
  78. const CGFunctionInfo &
  79. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
  80. // When translating an unprototyped function type, always use a
  81. // variadic type.
  82. return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
  83. /*instanceMethod=*/false,
  84. /*chainCall=*/false, None,
  85. FTNP->getExtInfo(), RequiredArgs(0));
  86. }
  87. /// Arrange the LLVM function layout for a value of the given function
  88. /// type, on top of any implicit parameters already stored.
  89. static const CGFunctionInfo &
  90. arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
  91. SmallVectorImpl<CanQualType> &prefix,
  92. CanQual<FunctionProtoType> FTP) {
  93. RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
  94. // FIXME: Kill copy.
  95. prefix.append(FTP->param_type_begin(), FTP->param_type_end());
  96. CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
  97. return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
  98. /*chainCall=*/false, prefix,
  99. FTP->getExtInfo(), required);
  100. }
  101. /// Arrange the argument and result information for a value of the
  102. /// given freestanding function type.
  103. const CGFunctionInfo &
  104. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
  105. SmallVector<CanQualType, 16> argTypes;
  106. return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
  107. FTP);
  108. }
  109. static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
  110. // Set the appropriate calling convention for the Function.
  111. if (D->hasAttr<StdCallAttr>())
  112. return CC_X86StdCall;
  113. if (D->hasAttr<FastCallAttr>())
  114. return CC_X86FastCall;
  115. if (D->hasAttr<ThisCallAttr>())
  116. return CC_X86ThisCall;
  117. if (D->hasAttr<VectorCallAttr>())
  118. return CC_X86VectorCall;
  119. if (D->hasAttr<PascalAttr>())
  120. return CC_X86Pascal;
  121. if (PcsAttr *PCS = D->getAttr<PcsAttr>())
  122. return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
  123. if (D->hasAttr<IntelOclBiccAttr>())
  124. return CC_IntelOclBicc;
  125. if (D->hasAttr<MSABIAttr>())
  126. return IsWindows ? CC_C : CC_X86_64Win64;
  127. if (D->hasAttr<SysVABIAttr>())
  128. return IsWindows ? CC_X86_64SysV : CC_C;
  129. return CC_C;
  130. }
  131. /// Arrange the argument and result information for a call to an
  132. /// unknown C++ non-static member function of the given abstract type.
  133. /// (Zero value of RD means we don't have any meaningful "this" argument type,
  134. /// so fall back to a generic pointer type).
  135. /// The member function must be an ordinary function, i.e. not a
  136. /// constructor or destructor.
  137. const CGFunctionInfo &
  138. CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
  139. const FunctionProtoType *FTP) {
  140. SmallVector<CanQualType, 16> argTypes;
  141. // Add the 'this' pointer.
  142. if (RD)
  143. argTypes.push_back(GetThisType(Context, RD));
  144. else
  145. argTypes.push_back(Context.VoidPtrTy);
  146. return ::arrangeLLVMFunctionInfo(
  147. *this, true, argTypes,
  148. FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
  149. }
  150. /// Arrange the argument and result information for a declaration or
  151. /// definition of the given C++ non-static member function. The
  152. /// member function must be an ordinary function, i.e. not a
  153. /// constructor or destructor.
  154. const CGFunctionInfo &
  155. CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
  156. assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
  157. assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
  158. CanQual<FunctionProtoType> prototype = GetFormalType(MD);
  159. if (MD->isInstance()) {
  160. // The abstract case is perfectly fine.
  161. const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
  162. return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
  163. }
  164. return arrangeFreeFunctionType(prototype);
  165. }
  166. const CGFunctionInfo &
  167. CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
  168. StructorType Type) {
  169. SmallVector<CanQualType, 16> argTypes;
  170. argTypes.push_back(GetThisType(Context, MD->getParent()));
  171. GlobalDecl GD;
  172. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  173. GD = GlobalDecl(CD, toCXXCtorType(Type));
  174. } else {
  175. auto *DD = dyn_cast<CXXDestructorDecl>(MD);
  176. GD = GlobalDecl(DD, toCXXDtorType(Type));
  177. }
  178. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  179. // Add the formal parameters.
  180. argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
  181. TheCXXABI.buildStructorSignature(MD, Type, argTypes);
  182. RequiredArgs required =
  183. (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
  184. FunctionType::ExtInfo extInfo = FTP->getExtInfo();
  185. CanQualType resultType = TheCXXABI.HasThisReturn(GD)
  186. ? argTypes.front()
  187. : TheCXXABI.hasMostDerivedReturn(GD)
  188. ? CGM.getContext().VoidPtrTy
  189. : Context.VoidTy;
  190. return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
  191. /*chainCall=*/false, argTypes, extInfo,
  192. required);
  193. }
  194. /// Arrange a call to a C++ method, passing the given arguments.
  195. const CGFunctionInfo &
  196. CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
  197. const CXXConstructorDecl *D,
  198. CXXCtorType CtorKind,
  199. unsigned ExtraArgs) {
  200. // FIXME: Kill copy.
  201. SmallVector<CanQualType, 16> ArgTypes;
  202. for (const auto &Arg : args)
  203. ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  204. CanQual<FunctionProtoType> FPT = GetFormalType(D);
  205. RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
  206. GlobalDecl GD(D, CtorKind);
  207. CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
  208. ? ArgTypes.front()
  209. : TheCXXABI.hasMostDerivedReturn(GD)
  210. ? CGM.getContext().VoidPtrTy
  211. : Context.VoidTy;
  212. FunctionType::ExtInfo Info = FPT->getExtInfo();
  213. return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  214. /*chainCall=*/false, ArgTypes, Info,
  215. Required);
  216. }
  217. /// Arrange the argument and result information for the declaration or
  218. /// definition of the given function.
  219. const CGFunctionInfo &
  220. CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
  221. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  222. if (MD->isInstance())
  223. return arrangeCXXMethodDeclaration(MD);
  224. CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
  225. assert(isa<FunctionType>(FTy));
  226. // When declaring a function without a prototype, always use a
  227. // non-variadic type.
  228. if (isa<FunctionNoProtoType>(FTy)) {
  229. CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
  230. return arrangeLLVMFunctionInfo(
  231. noProto->getReturnType(), /*instanceMethod=*/false,
  232. /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
  233. }
  234. assert(isa<FunctionProtoType>(FTy));
  235. return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
  236. }
  237. /// Arrange the argument and result information for the declaration or
  238. /// definition of an Objective-C method.
  239. const CGFunctionInfo &
  240. CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
  241. // It happens that this is the same as a call with no optional
  242. // arguments, except also using the formal 'self' type.
  243. return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
  244. }
  245. /// Arrange the argument and result information for the function type
  246. /// through which to perform a send to the given Objective-C method,
  247. /// using the given receiver type. The receiver type is not always
  248. /// the 'self' type of the method or even an Objective-C pointer type.
  249. /// This is *not* the right method for actually performing such a
  250. /// message send, due to the possibility of optional arguments.
  251. const CGFunctionInfo &
  252. CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
  253. QualType receiverType) {
  254. SmallVector<CanQualType, 16> argTys;
  255. argTys.push_back(Context.getCanonicalParamType(receiverType));
  256. argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
  257. // FIXME: Kill copy?
  258. for (const auto *I : MD->params()) {
  259. argTys.push_back(Context.getCanonicalParamType(I->getType()));
  260. }
  261. FunctionType::ExtInfo einfo;
  262. bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
  263. einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
  264. if (getContext().getLangOpts().ObjCAutoRefCount &&
  265. MD->hasAttr<NSReturnsRetainedAttr>())
  266. einfo = einfo.withProducesResult(true);
  267. RequiredArgs required =
  268. (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
  269. return arrangeLLVMFunctionInfo(
  270. GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
  271. /*chainCall=*/false, argTys, einfo, required);
  272. }
  273. const CGFunctionInfo &
  274. CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
  275. // FIXME: Do we need to handle ObjCMethodDecl?
  276. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  277. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  278. return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
  279. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
  280. return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
  281. return arrangeFunctionDeclaration(FD);
  282. }
  283. /// Arrange a thunk that takes 'this' as the first parameter followed by
  284. /// varargs. Return a void pointer, regardless of the actual return type.
  285. /// The body of the thunk will end in a musttail call to a function of the
  286. /// correct type, and the caller will bitcast the function to the correct
  287. /// prototype.
  288. const CGFunctionInfo &
  289. CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
  290. assert(MD->isVirtual() && "only virtual memptrs have thunks");
  291. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  292. CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
  293. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
  294. /*chainCall=*/false, ArgTys,
  295. FTP->getExtInfo(), RequiredArgs(1));
  296. }
  297. const CGFunctionInfo &
  298. CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
  299. CXXCtorType CT) {
  300. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  301. CanQual<FunctionProtoType> FTP = GetFormalType(CD);
  302. SmallVector<CanQualType, 2> ArgTys;
  303. const CXXRecordDecl *RD = CD->getParent();
  304. ArgTys.push_back(GetThisType(Context, RD));
  305. if (CT == Ctor_CopyingClosure)
  306. ArgTys.push_back(*FTP->param_type_begin());
  307. if (RD->getNumVBases() > 0)
  308. ArgTys.push_back(Context.IntTy);
  309. CallingConv CC = Context.getDefaultCallingConvention(
  310. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  311. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
  312. /*chainCall=*/false, ArgTys,
  313. FunctionType::ExtInfo(CC), RequiredArgs::All);
  314. }
  315. /// Arrange a call as unto a free function, except possibly with an
  316. /// additional number of formal parameters considered required.
  317. static const CGFunctionInfo &
  318. arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
  319. CodeGenModule &CGM,
  320. const CallArgList &args,
  321. const FunctionType *fnType,
  322. unsigned numExtraRequiredArgs,
  323. bool chainCall) {
  324. assert(args.size() >= numExtraRequiredArgs);
  325. // In most cases, there are no optional arguments.
  326. RequiredArgs required = RequiredArgs::All;
  327. // If we have a variadic prototype, the required arguments are the
  328. // extra prefix plus the arguments in the prototype.
  329. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
  330. if (proto->isVariadic())
  331. required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
  332. // If we don't have a prototype at all, but we're supposed to
  333. // explicitly use the variadic convention for unprototyped calls,
  334. // treat all of the arguments as required but preserve the nominal
  335. // possibility of variadics.
  336. } else if (CGM.getTargetCodeGenInfo()
  337. .isNoProtoCallVariadic(args,
  338. cast<FunctionNoProtoType>(fnType))) {
  339. required = RequiredArgs(args.size());
  340. }
  341. // FIXME: Kill copy.
  342. SmallVector<CanQualType, 16> argTypes;
  343. for (const auto &arg : args)
  344. argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
  345. return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
  346. /*instanceMethod=*/false, chainCall,
  347. argTypes, fnType->getExtInfo(), required);
  348. }
  349. /// Figure out the rules for calling a function with the given formal
  350. /// type using the given arguments. The arguments are necessary
  351. /// because the function might be unprototyped, in which case it's
  352. /// target-dependent in crazy ways.
  353. const CGFunctionInfo &
  354. CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
  355. const FunctionType *fnType,
  356. bool chainCall) {
  357. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
  358. chainCall ? 1 : 0, chainCall);
  359. }
  360. /// A block function call is essentially a free-function call with an
  361. /// extra implicit argument.
  362. const CGFunctionInfo &
  363. CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
  364. const FunctionType *fnType) {
  365. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
  366. /*chainCall=*/false);
  367. }
  368. const CGFunctionInfo &
  369. CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
  370. const CallArgList &args,
  371. FunctionType::ExtInfo info,
  372. RequiredArgs required) {
  373. // FIXME: Kill copy.
  374. SmallVector<CanQualType, 16> argTypes;
  375. for (const auto &Arg : args)
  376. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  377. return arrangeLLVMFunctionInfo(
  378. GetReturnType(resultType), /*instanceMethod=*/false,
  379. /*chainCall=*/false, argTypes, info, required);
  380. }
  381. /// Arrange a call to a C++ method, passing the given arguments.
  382. const CGFunctionInfo &
  383. CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
  384. const FunctionProtoType *FPT,
  385. RequiredArgs required) {
  386. // FIXME: Kill copy.
  387. SmallVector<CanQualType, 16> argTypes;
  388. for (const auto &Arg : args)
  389. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  390. FunctionType::ExtInfo info = FPT->getExtInfo();
  391. return arrangeLLVMFunctionInfo(
  392. GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
  393. /*chainCall=*/false, argTypes, info, required);
  394. }
  395. const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
  396. QualType resultType, const FunctionArgList &args,
  397. const FunctionType::ExtInfo &info, bool isVariadic) {
  398. // FIXME: Kill copy.
  399. SmallVector<CanQualType, 16> argTypes;
  400. for (auto Arg : args)
  401. argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
  402. RequiredArgs required =
  403. (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
  404. return arrangeLLVMFunctionInfo(
  405. GetReturnType(resultType), /*instanceMethod=*/false,
  406. /*chainCall=*/false, argTypes, info, required);
  407. }
  408. const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
  409. return arrangeLLVMFunctionInfo(
  410. getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
  411. None, FunctionType::ExtInfo(), RequiredArgs::All);
  412. }
  413. /// Arrange the argument and result information for an abstract value
  414. /// of a given function type. This is the method which all of the
  415. /// above functions ultimately defer to.
  416. const CGFunctionInfo &
  417. CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
  418. bool instanceMethod,
  419. bool chainCall,
  420. ArrayRef<CanQualType> argTypes,
  421. FunctionType::ExtInfo info,
  422. RequiredArgs required) {
  423. // HLSL Change Starts
  424. ASTContext &context = getContext();
  425. auto isCanonicalAsParam = [&context](const CanQualType &Ty) {
  426. return Ty.isCanonicalAsParam() ||
  427. (context.getLangOpts().HLSL && Ty->isArrayType());
  428. };
  429. // HLSL Change Ends
  430. assert(std::all_of(argTypes.begin(), argTypes.end(),
  431. isCanonicalAsParam)); // HLSL Change - skip array when
  432. // check isCanonicalAsParam
  433. (void)isCanonicalAsParam;
  434. unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
  435. // Lookup or create unique function info.
  436. llvm::FoldingSetNodeID ID;
  437. CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
  438. resultType, argTypes);
  439. void *insertPos = nullptr;
  440. CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
  441. if (FI)
  442. return *FI;
  443. // Construct the function info. We co-allocate the ArgInfos.
  444. FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
  445. resultType, argTypes, required);
  446. FunctionInfos.InsertNode(FI, insertPos);
  447. bool inserted = FunctionsBeingProcessed.insert(FI).second;
  448. (void)inserted;
  449. assert(inserted && "Recursively being processed?");
  450. // Compute ABI information.
  451. getABIInfo().computeInfo(*FI);
  452. // Loop over all of the computed argument and return value info. If any of
  453. // them are direct or extend without a specified coerce type, specify the
  454. // default now.
  455. ABIArgInfo &retInfo = FI->getReturnInfo();
  456. if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
  457. retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
  458. for (auto &I : FI->arguments())
  459. if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
  460. I.info.setCoerceToType(ConvertType(I.type));
  461. bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
  462. assert(erased && "Not in set?");
  463. return *FI;
  464. }
  465. CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
  466. bool instanceMethod,
  467. bool chainCall,
  468. const FunctionType::ExtInfo &info,
  469. CanQualType resultType,
  470. ArrayRef<CanQualType> argTypes,
  471. RequiredArgs required) {
  472. void *buffer = operator new(sizeof(CGFunctionInfo) +
  473. sizeof(ArgInfo) * (argTypes.size() + 1));
  474. CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
  475. FI->CallingConvention = llvmCC;
  476. FI->EffectiveCallingConvention = llvmCC;
  477. FI->ASTCallingConvention = info.getCC();
  478. FI->InstanceMethod = instanceMethod;
  479. FI->ChainCall = chainCall;
  480. FI->NoReturn = info.getNoReturn();
  481. FI->ReturnsRetained = info.getProducesResult();
  482. FI->Required = required;
  483. FI->HasRegParm = info.getHasRegParm();
  484. FI->RegParm = info.getRegParm();
  485. FI->ArgStruct = nullptr;
  486. FI->NumArgs = argTypes.size();
  487. FI->getArgsBuffer()[0].type = resultType;
  488. for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
  489. FI->getArgsBuffer()[i + 1].type = argTypes[i];
  490. return FI;
  491. }
  492. /***/
  493. namespace {
  494. // ABIArgInfo::Expand implementation.
  495. // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
  496. struct TypeExpansion {
  497. enum TypeExpansionKind {
  498. // Elements of constant arrays are expanded recursively.
  499. TEK_ConstantArray,
  500. // Record fields are expanded recursively (but if record is a union, only
  501. // the field with the largest size is expanded).
  502. TEK_Record,
  503. // For complex types, real and imaginary parts are expanded recursively.
  504. TEK_Complex,
  505. // All other types are not expandable.
  506. TEK_None
  507. };
  508. const TypeExpansionKind Kind;
  509. TypeExpansion(TypeExpansionKind K) : Kind(K) {}
  510. virtual ~TypeExpansion() {}
  511. };
  512. struct ConstantArrayExpansion : TypeExpansion {
  513. QualType EltTy;
  514. uint64_t NumElts;
  515. ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
  516. : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
  517. static bool classof(const TypeExpansion *TE) {
  518. return TE->Kind == TEK_ConstantArray;
  519. }
  520. };
  521. struct RecordExpansion : TypeExpansion {
  522. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  523. SmallVector<const FieldDecl *, 1> Fields;
  524. RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
  525. SmallVector<const FieldDecl *, 1> &&Fields)
  526. : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
  527. static bool classof(const TypeExpansion *TE) {
  528. return TE->Kind == TEK_Record;
  529. }
  530. };
  531. struct ComplexExpansion : TypeExpansion {
  532. QualType EltTy;
  533. ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
  534. static bool classof(const TypeExpansion *TE) {
  535. return TE->Kind == TEK_Complex;
  536. }
  537. };
  538. struct NoExpansion : TypeExpansion {
  539. NoExpansion() : TypeExpansion(TEK_None) {}
  540. static bool classof(const TypeExpansion *TE) {
  541. return TE->Kind == TEK_None;
  542. }
  543. };
  544. } // namespace
  545. static std::unique_ptr<TypeExpansion>
  546. getTypeExpansion(QualType Ty, const ASTContext &Context) {
  547. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  548. return llvm::make_unique<ConstantArrayExpansion>(
  549. AT->getElementType(), AT->getSize().getZExtValue());
  550. }
  551. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  552. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  553. SmallVector<const FieldDecl *, 1> Fields;
  554. const RecordDecl *RD = RT->getDecl();
  555. assert(!RD->hasFlexibleArrayMember() &&
  556. "Cannot expand structure with flexible array.");
  557. if (RD->isUnion()) {
  558. // Unions can be here only in degenerative cases - all the fields are same
  559. // after flattening. Thus we have to use the "largest" field.
  560. const FieldDecl *LargestFD = nullptr;
  561. CharUnits UnionSize = CharUnits::Zero();
  562. for (const auto *FD : RD->fields()) {
  563. // Skip zero length bitfields.
  564. if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
  565. continue;
  566. assert(!FD->isBitField() &&
  567. "Cannot expand structure with bit-field members.");
  568. CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  569. if (UnionSize < FieldSize) {
  570. UnionSize = FieldSize;
  571. LargestFD = FD;
  572. }
  573. }
  574. if (LargestFD)
  575. Fields.push_back(LargestFD);
  576. } else {
  577. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  578. assert(!CXXRD->isDynamicClass() &&
  579. "cannot expand vtable pointers in dynamic classes");
  580. for (const CXXBaseSpecifier &BS : CXXRD->bases())
  581. Bases.push_back(&BS);
  582. }
  583. for (const auto *FD : RD->fields()) {
  584. // Skip zero length bitfields.
  585. if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
  586. continue;
  587. assert(!FD->isBitField() &&
  588. "Cannot expand structure with bit-field members.");
  589. Fields.push_back(FD);
  590. }
  591. }
  592. return llvm::make_unique<RecordExpansion>(std::move(Bases),
  593. std::move(Fields));
  594. }
  595. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  596. return llvm::make_unique<ComplexExpansion>(CT->getElementType());
  597. }
  598. return llvm::make_unique<NoExpansion>();
  599. }
  600. static int getExpansionSize(QualType Ty, const ASTContext &Context) {
  601. auto Exp = getTypeExpansion(Ty, Context);
  602. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  603. return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
  604. }
  605. if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  606. int Res = 0;
  607. for (auto BS : RExp->Bases)
  608. Res += getExpansionSize(BS->getType(), Context);
  609. for (auto FD : RExp->Fields)
  610. Res += getExpansionSize(FD->getType(), Context);
  611. return Res;
  612. }
  613. if (isa<ComplexExpansion>(Exp.get()))
  614. return 2;
  615. assert(isa<NoExpansion>(Exp.get()));
  616. return 1;
  617. }
  618. void
  619. CodeGenTypes::getExpandedTypes(QualType Ty,
  620. SmallVectorImpl<llvm::Type *>::iterator &TI) {
  621. auto Exp = getTypeExpansion(Ty, Context);
  622. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  623. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  624. getExpandedTypes(CAExp->EltTy, TI);
  625. }
  626. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  627. for (auto BS : RExp->Bases)
  628. getExpandedTypes(BS->getType(), TI);
  629. for (auto FD : RExp->Fields)
  630. getExpandedTypes(FD->getType(), TI);
  631. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  632. llvm::Type *EltTy = ConvertType(CExp->EltTy);
  633. *TI++ = EltTy;
  634. *TI++ = EltTy;
  635. } else {
  636. assert(isa<NoExpansion>(Exp.get()));
  637. *TI++ = ConvertType(Ty);
  638. }
  639. }
  640. void CodeGenFunction::ExpandTypeFromArgs(
  641. QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
  642. assert(LV.isSimple() &&
  643. "Unexpected non-simple lvalue during struct expansion.");
  644. auto Exp = getTypeExpansion(Ty, getContext());
  645. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  646. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  647. llvm::Value *EltAddr =
  648. Builder.CreateConstGEP2_32(nullptr, LV.getAddress(), 0, i);
  649. LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
  650. ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
  651. }
  652. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  653. llvm::Value *This = LV.getAddress();
  654. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  655. // Perform a single step derived-to-base conversion.
  656. llvm::Value *Base =
  657. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  658. /*NullCheckValue=*/false, SourceLocation());
  659. LValue SubLV = MakeAddrLValue(Base, BS->getType());
  660. // Recurse onto bases.
  661. ExpandTypeFromArgs(BS->getType(), SubLV, AI);
  662. }
  663. for (auto FD : RExp->Fields) {
  664. // FIXME: What are the right qualifiers here?
  665. LValue SubLV = EmitLValueForField(LV, FD);
  666. ExpandTypeFromArgs(FD->getType(), SubLV, AI);
  667. }
  668. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  669. llvm::Value *RealAddr =
  670. Builder.CreateStructGEP(nullptr, LV.getAddress(), 0, "real");
  671. EmitStoreThroughLValue(RValue::get(*AI++),
  672. MakeAddrLValue(RealAddr, CExp->EltTy));
  673. llvm::Value *ImagAddr =
  674. Builder.CreateStructGEP(nullptr, LV.getAddress(), 1, "imag");
  675. EmitStoreThroughLValue(RValue::get(*AI++),
  676. MakeAddrLValue(ImagAddr, CExp->EltTy));
  677. } else {
  678. assert(isa<NoExpansion>(Exp.get()));
  679. EmitStoreThroughLValue(RValue::get(*AI++), LV);
  680. }
  681. }
  682. void CodeGenFunction::ExpandTypeToArgs(
  683. QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  684. SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
  685. auto Exp = getTypeExpansion(Ty, getContext());
  686. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  687. llvm::Value *Addr = RV.getAggregateAddr();
  688. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  689. llvm::Value *EltAddr = Builder.CreateConstGEP2_32(nullptr, Addr, 0, i);
  690. RValue EltRV =
  691. convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
  692. ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
  693. }
  694. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  695. llvm::Value *This = RV.getAggregateAddr();
  696. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  697. // Perform a single step derived-to-base conversion.
  698. llvm::Value *Base =
  699. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  700. /*NullCheckValue=*/false, SourceLocation());
  701. RValue BaseRV = RValue::getAggregate(Base);
  702. // Recurse onto bases.
  703. ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
  704. IRCallArgPos);
  705. }
  706. LValue LV = MakeAddrLValue(This, Ty);
  707. for (auto FD : RExp->Fields) {
  708. RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
  709. ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
  710. IRCallArgPos);
  711. }
  712. } else if (isa<ComplexExpansion>(Exp.get())) {
  713. ComplexPairTy CV = RV.getComplexVal();
  714. IRCallArgs[IRCallArgPos++] = CV.first;
  715. IRCallArgs[IRCallArgPos++] = CV.second;
  716. } else {
  717. assert(isa<NoExpansion>(Exp.get()));
  718. assert(RV.isScalar() &&
  719. "Unexpected non-scalar rvalue during struct expansion.");
  720. // Insert a bitcast as needed.
  721. llvm::Value *V = RV.getScalarVal();
  722. if (IRCallArgPos < IRFuncTy->getNumParams() &&
  723. V->getType() != IRFuncTy->getParamType(IRCallArgPos))
  724. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
  725. IRCallArgs[IRCallArgPos++] = V;
  726. }
  727. }
  728. /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
  729. /// accessing some number of bytes out of it, try to gep into the struct to get
  730. /// at its inner goodness. Dive as deep as possible without entering an element
  731. /// with an in-memory size smaller than DstSize.
  732. static llvm::Value *
  733. EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
  734. llvm::StructType *SrcSTy,
  735. uint64_t DstSize, CodeGenFunction &CGF) {
  736. // We can't dive into a zero-element struct.
  737. if (SrcSTy->getNumElements() == 0) return SrcPtr;
  738. llvm::Type *FirstElt = SrcSTy->getElementType(0);
  739. // If the first elt is at least as large as what we're looking for, or if the
  740. // first element is the same size as the whole struct, we can enter it. The
  741. // comparison must be made on the store size and not the alloca size. Using
  742. // the alloca size may overstate the size of the load.
  743. uint64_t FirstEltSize =
  744. CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
  745. if (FirstEltSize < DstSize &&
  746. FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
  747. return SrcPtr;
  748. // GEP into the first element.
  749. SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcSTy, SrcPtr, 0, 0, "coerce.dive");
  750. // If the first element is a struct, recurse.
  751. llvm::Type *SrcTy =
  752. cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
  753. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
  754. return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  755. return SrcPtr;
  756. }
  757. /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
  758. /// are either integers or pointers. This does a truncation of the value if it
  759. /// is too large or a zero extension if it is too small.
  760. ///
  761. /// This behaves as if the value were coerced through memory, so on big-endian
  762. /// targets the high bits are preserved in a truncation, while little-endian
  763. /// targets preserve the low bits.
  764. static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
  765. llvm::Type *Ty,
  766. CodeGenFunction &CGF) {
  767. if (Val->getType() == Ty)
  768. return Val;
  769. if (isa<llvm::PointerType>(Val->getType())) {
  770. // If this is Pointer->Pointer avoid conversion to and from int.
  771. if (isa<llvm::PointerType>(Ty))
  772. return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
  773. // Convert the pointer to an integer so we can play with its width.
  774. Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
  775. }
  776. llvm::Type *DestIntTy = Ty;
  777. if (isa<llvm::PointerType>(DestIntTy))
  778. DestIntTy = CGF.IntPtrTy;
  779. if (Val->getType() != DestIntTy) {
  780. const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
  781. if (DL.isBigEndian()) {
  782. // Preserve the high bits on big-endian targets.
  783. // That is what memory coercion does.
  784. uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
  785. uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
  786. if (SrcSize > DstSize) {
  787. Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
  788. Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
  789. } else {
  790. Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
  791. Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
  792. }
  793. } else {
  794. // Little-endian targets preserve the low bits. No shifts required.
  795. Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
  796. }
  797. }
  798. if (isa<llvm::PointerType>(Ty))
  799. Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
  800. return Val;
  801. }
  802. /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
  803. /// a pointer to an object of type \arg Ty, known to be aligned to
  804. /// \arg SrcAlign bytes.
  805. ///
  806. /// This safely handles the case when the src type is smaller than the
  807. /// destination type; in this situation the values of bits which not
  808. /// present in the src are undefined.
  809. static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
  810. llvm::Type *Ty, CharUnits SrcAlign,
  811. CodeGenFunction &CGF) {
  812. llvm::Type *SrcTy =
  813. cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
  814. // If SrcTy and Ty are the same, just do a load.
  815. if (SrcTy == Ty)
  816. return CGF.Builder.CreateAlignedLoad(SrcPtr, SrcAlign.getQuantity());
  817. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
  818. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
  819. SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  820. SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
  821. }
  822. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  823. // If the source and destination are integer or pointer types, just do an
  824. // extension or truncation to the desired type.
  825. if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
  826. (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
  827. llvm::LoadInst *Load =
  828. CGF.Builder.CreateAlignedLoad(SrcPtr, SrcAlign.getQuantity());
  829. return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
  830. }
  831. // If load is legal, just bitcast the src pointer.
  832. if (SrcSize >= DstSize) {
  833. // Generally SrcSize is never greater than DstSize, since this means we are
  834. // losing bits. However, this can happen in cases where the structure has
  835. // additional padding, for example due to a user specified alignment.
  836. //
  837. // FIXME: Assert that we aren't truncating non-padding bits when have access
  838. // to that information.
  839. llvm::Value *Casted =
  840. CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
  841. return CGF.Builder.CreateAlignedLoad(Casted, SrcAlign.getQuantity());
  842. }
  843. // Otherwise do coercion through memory. This is stupid, but
  844. // simple.
  845. llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(Ty);
  846. Tmp->setAlignment(SrcAlign.getQuantity());
  847. llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
  848. llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
  849. llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
  850. CGF.Builder.CreateMemCpy(Casted, SrcCasted,
  851. llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
  852. SrcAlign.getQuantity(), false);
  853. return CGF.Builder.CreateAlignedLoad(Tmp, SrcAlign.getQuantity());
  854. }
  855. // Function to store a first-class aggregate into memory. We prefer to
  856. // store the elements rather than the aggregate to be more friendly to
  857. // fast-isel.
  858. // FIXME: Do we need to recurse here?
  859. static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
  860. llvm::Value *DestPtr, bool DestIsVolatile,
  861. CharUnits DestAlign,
  862. QualType QTy // HLSL Change
  863. ) {
  864. // Prefer scalar stores to first-class aggregate stores.
  865. if (llvm::StructType *STy =
  866. dyn_cast<llvm::StructType>(Val->getType())) {
  867. // HLSL Change Begins
  868. if (CGF.getLangOpts().HLSL) {
  869. CGF.CGM.getHLSLRuntime().EmitHLSLAggregateStore(CGF, Val, DestPtr, QTy);
  870. return;
  871. }
  872. // HLSL Change Ends
  873. const llvm::StructLayout *Layout =
  874. CGF.CGM.getDataLayout().getStructLayout(STy);
  875. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  876. llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(STy, DestPtr, 0, i);
  877. llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
  878. uint64_t EltOffset = Layout->getElementOffset(i);
  879. CharUnits EltAlign =
  880. DestAlign.alignmentAtOffset(CharUnits::fromQuantity(EltOffset));
  881. CGF.Builder.CreateAlignedStore(Elt, EltPtr, EltAlign.getQuantity(),
  882. DestIsVolatile);
  883. }
  884. } else {
  885. CGF.Builder.CreateAlignedStore(Val, DestPtr, DestAlign.getQuantity(),
  886. DestIsVolatile);
  887. }
  888. }
  889. /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
  890. /// where the source and destination may have different types. The
  891. /// destination is known to be aligned to \arg DstAlign bytes.
  892. ///
  893. /// This safely handles the case when the src type is larger than the
  894. /// destination type; the upper bits of the src will be lost.
  895. static void CreateCoercedStore(llvm::Value *Src,
  896. llvm::Value *DstPtr,
  897. bool DstIsVolatile,
  898. CharUnits DstAlign,
  899. CodeGenFunction &CGF,
  900. QualType QTy // HLSL Change
  901. ) {
  902. llvm::Type *SrcTy = Src->getType();
  903. llvm::Type *DstTy =
  904. cast<llvm::PointerType>(DstPtr->getType())->getElementType();
  905. if (SrcTy == DstTy) {
  906. CGF.Builder.CreateAlignedStore(Src, DstPtr, DstAlign.getQuantity(),
  907. DstIsVolatile);
  908. return;
  909. }
  910. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  911. if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
  912. DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
  913. DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
  914. }
  915. // If the source and destination are integer or pointer types, just do an
  916. // extension or truncation to the desired type.
  917. if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
  918. (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
  919. Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
  920. CGF.Builder.CreateAlignedStore(Src, DstPtr, DstAlign.getQuantity(),
  921. DstIsVolatile);
  922. return;
  923. }
  924. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
  925. // If store is legal, just bitcast the src pointer.
  926. if (SrcSize <= DstSize) {
  927. llvm::Value *Casted =
  928. CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
  929. BuildAggStore(CGF, Src, Casted, DstIsVolatile, DstAlign, QTy); // HLSL Change - Add QTy
  930. } else {
  931. // Otherwise do coercion through memory. This is stupid, but
  932. // simple.
  933. // Generally SrcSize is never greater than DstSize, since this means we are
  934. // losing bits. However, this can happen in cases where the structure has
  935. // additional padding, for example due to a user specified alignment.
  936. //
  937. // FIXME: Assert that we aren't truncating non-padding bits when have access
  938. // to that information.
  939. llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(SrcTy);
  940. Tmp->setAlignment(DstAlign.getQuantity());
  941. CGF.Builder.CreateAlignedStore(Src, Tmp, DstAlign.getQuantity());
  942. llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
  943. llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
  944. llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
  945. CGF.Builder.CreateMemCpy(DstCasted, Casted,
  946. llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
  947. DstAlign.getQuantity(), false);
  948. }
  949. }
  950. namespace {
  951. /// Encapsulates information about the way function arguments from
  952. /// CGFunctionInfo should be passed to actual LLVM IR function.
  953. class ClangToLLVMArgMapping {
  954. static const unsigned InvalidIndex = ~0U;
  955. unsigned InallocaArgNo;
  956. unsigned SRetArgNo;
  957. unsigned TotalIRArgs;
  958. /// Arguments of LLVM IR function corresponding to single Clang argument.
  959. struct IRArgs {
  960. unsigned PaddingArgIndex;
  961. // Argument is expanded to IR arguments at positions
  962. // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
  963. unsigned FirstArgIndex;
  964. unsigned NumberOfArgs;
  965. IRArgs()
  966. : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
  967. NumberOfArgs(0) {}
  968. };
  969. SmallVector<IRArgs, 8> ArgInfo;
  970. public:
  971. ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
  972. bool OnlyRequiredArgs = false)
  973. : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
  974. ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
  975. construct(Context, FI, OnlyRequiredArgs);
  976. }
  977. bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
  978. unsigned getInallocaArgNo() const {
  979. assert(hasInallocaArg());
  980. return InallocaArgNo;
  981. }
  982. bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
  983. unsigned getSRetArgNo() const {
  984. assert(hasSRetArg());
  985. return SRetArgNo;
  986. }
  987. unsigned totalIRArgs() const { return TotalIRArgs; }
  988. bool hasPaddingArg(unsigned ArgNo) const {
  989. assert(ArgNo < ArgInfo.size());
  990. return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
  991. }
  992. unsigned getPaddingArgNo(unsigned ArgNo) const {
  993. assert(hasPaddingArg(ArgNo));
  994. return ArgInfo[ArgNo].PaddingArgIndex;
  995. }
  996. /// Returns index of first IR argument corresponding to ArgNo, and their
  997. /// quantity.
  998. std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
  999. assert(ArgNo < ArgInfo.size());
  1000. return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
  1001. ArgInfo[ArgNo].NumberOfArgs);
  1002. }
  1003. private:
  1004. void construct(const ASTContext &Context, const CGFunctionInfo &FI,
  1005. bool OnlyRequiredArgs);
  1006. };
  1007. void ClangToLLVMArgMapping::construct(const ASTContext &Context,
  1008. const CGFunctionInfo &FI,
  1009. bool OnlyRequiredArgs) {
  1010. unsigned IRArgNo = 0;
  1011. bool SwapThisWithSRet = false;
  1012. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1013. if (RetAI.getKind() == ABIArgInfo::Indirect) {
  1014. SwapThisWithSRet = RetAI.isSRetAfterThis();
  1015. SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
  1016. }
  1017. unsigned ArgNo = 0;
  1018. unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
  1019. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
  1020. ++I, ++ArgNo) {
  1021. assert(I != FI.arg_end());
  1022. QualType ArgType = I->type;
  1023. const ABIArgInfo &AI = I->info;
  1024. // Collect data about IR arguments corresponding to Clang argument ArgNo.
  1025. auto &IRArgs = ArgInfo[ArgNo];
  1026. if (AI.getPaddingType())
  1027. IRArgs.PaddingArgIndex = IRArgNo++;
  1028. switch (AI.getKind()) {
  1029. case ABIArgInfo::Extend:
  1030. case ABIArgInfo::Direct: {
  1031. // FIXME: handle sseregparm someday...
  1032. llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
  1033. if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
  1034. IRArgs.NumberOfArgs = STy->getNumElements();
  1035. } else {
  1036. IRArgs.NumberOfArgs = 1;
  1037. }
  1038. break;
  1039. }
  1040. case ABIArgInfo::Indirect:
  1041. IRArgs.NumberOfArgs = 1;
  1042. break;
  1043. case ABIArgInfo::Ignore:
  1044. case ABIArgInfo::InAlloca:
  1045. // ignore and inalloca doesn't have matching LLVM parameters.
  1046. IRArgs.NumberOfArgs = 0;
  1047. break;
  1048. case ABIArgInfo::Expand: {
  1049. IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
  1050. break;
  1051. }
  1052. }
  1053. if (IRArgs.NumberOfArgs > 0) {
  1054. IRArgs.FirstArgIndex = IRArgNo;
  1055. IRArgNo += IRArgs.NumberOfArgs;
  1056. }
  1057. // Skip over the sret parameter when it comes second. We already handled it
  1058. // above.
  1059. if (IRArgNo == 1 && SwapThisWithSRet)
  1060. IRArgNo++;
  1061. }
  1062. assert(ArgNo == ArgInfo.size());
  1063. if (FI.usesInAlloca())
  1064. InallocaArgNo = IRArgNo++;
  1065. TotalIRArgs = IRArgNo;
  1066. }
  1067. } // namespace
  1068. /***/
  1069. bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
  1070. return FI.getReturnInfo().isIndirect();
  1071. }
  1072. bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
  1073. return ReturnTypeUsesSRet(FI) &&
  1074. getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
  1075. }
  1076. bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
  1077. if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
  1078. switch (BT->getKind()) {
  1079. default:
  1080. return false;
  1081. case BuiltinType::Float:
  1082. return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
  1083. case BuiltinType::Double:
  1084. return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
  1085. case BuiltinType::LongDouble:
  1086. return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
  1087. }
  1088. }
  1089. return false;
  1090. }
  1091. bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
  1092. if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
  1093. if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
  1094. if (BT->getKind() == BuiltinType::LongDouble)
  1095. return getTarget().useObjCFP2RetForComplexLongDouble();
  1096. }
  1097. }
  1098. return false;
  1099. }
  1100. llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
  1101. const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
  1102. return GetFunctionType(FI);
  1103. }
  1104. llvm::FunctionType *
  1105. CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  1106. bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
  1107. (void)Inserted;
  1108. assert(Inserted && "Recursively being processed?");
  1109. llvm::Type *resultType = nullptr;
  1110. const ABIArgInfo &retAI = FI.getReturnInfo();
  1111. switch (retAI.getKind()) {
  1112. case ABIArgInfo::Expand:
  1113. llvm_unreachable("Invalid ABI kind for return argument");
  1114. case ABIArgInfo::Extend:
  1115. case ABIArgInfo::Direct:
  1116. resultType = retAI.getCoerceToType();
  1117. break;
  1118. case ABIArgInfo::InAlloca:
  1119. if (retAI.getInAllocaSRet()) {
  1120. // sret things on win32 aren't void, they return the sret pointer.
  1121. QualType ret = FI.getReturnType();
  1122. llvm::Type *ty = ConvertType(ret);
  1123. unsigned addressSpace = Context.getTargetAddressSpace(ret);
  1124. resultType = llvm::PointerType::get(ty, addressSpace);
  1125. } else {
  1126. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1127. }
  1128. break;
  1129. case ABIArgInfo::Indirect: {
  1130. assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
  1131. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1132. break;
  1133. }
  1134. case ABIArgInfo::Ignore:
  1135. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1136. break;
  1137. }
  1138. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
  1139. SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
  1140. // Add type for sret argument.
  1141. if (IRFunctionArgs.hasSRetArg()) {
  1142. QualType Ret = FI.getReturnType();
  1143. llvm::Type *Ty = ConvertType(Ret);
  1144. unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
  1145. ArgTypes[IRFunctionArgs.getSRetArgNo()] =
  1146. llvm::PointerType::get(Ty, AddressSpace);
  1147. }
  1148. // Add type for inalloca argument.
  1149. if (IRFunctionArgs.hasInallocaArg()) {
  1150. auto ArgStruct = FI.getArgStruct();
  1151. assert(ArgStruct);
  1152. ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
  1153. }
  1154. // Add in all of the required arguments.
  1155. unsigned ArgNo = 0;
  1156. CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
  1157. ie = it + FI.getNumRequiredArgs();
  1158. for (; it != ie; ++it, ++ArgNo) {
  1159. const ABIArgInfo &ArgInfo = it->info;
  1160. // Insert a padding type to ensure proper alignment.
  1161. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  1162. ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1163. ArgInfo.getPaddingType();
  1164. unsigned FirstIRArg, NumIRArgs;
  1165. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1166. switch (ArgInfo.getKind()) {
  1167. case ABIArgInfo::Ignore:
  1168. case ABIArgInfo::InAlloca:
  1169. assert(NumIRArgs == 0);
  1170. break;
  1171. case ABIArgInfo::Indirect: {
  1172. assert(NumIRArgs == 1);
  1173. // indirect arguments are always on the stack, which is addr space #0.
  1174. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1175. ArgTypes[FirstIRArg] = LTy->getPointerTo();
  1176. break;
  1177. }
  1178. case ABIArgInfo::Extend:
  1179. case ABIArgInfo::Direct: {
  1180. // Fast-isel and the optimizer generally like scalar values better than
  1181. // FCAs, so we flatten them if this is safe to do for this argument.
  1182. llvm::Type *argType = ArgInfo.getCoerceToType();
  1183. llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
  1184. if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  1185. assert(NumIRArgs == st->getNumElements());
  1186. for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
  1187. ArgTypes[FirstIRArg + i] = st->getElementType(i);
  1188. } else {
  1189. assert(NumIRArgs == 1);
  1190. ArgTypes[FirstIRArg] = argType;
  1191. }
  1192. break;
  1193. }
  1194. case ABIArgInfo::Expand:
  1195. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1196. getExpandedTypes(it->type, ArgTypesIter);
  1197. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1198. break;
  1199. }
  1200. }
  1201. bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
  1202. assert(Erased && "Not in set?");
  1203. return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
  1204. }
  1205. llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
  1206. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1207. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1208. if (!isFuncTypeConvertible(FPT))
  1209. return llvm::StructType::get(getLLVMContext());
  1210. const CGFunctionInfo *Info;
  1211. if (isa<CXXDestructorDecl>(MD))
  1212. Info =
  1213. &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
  1214. else
  1215. Info = &arrangeCXXMethodDeclaration(MD);
  1216. return GetFunctionType(*Info);
  1217. }
  1218. void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
  1219. const Decl *TargetDecl,
  1220. AttributeListType &PAL,
  1221. unsigned &CallingConv,
  1222. bool AttrOnCallSite) {
  1223. llvm::AttrBuilder FuncAttrs;
  1224. llvm::AttrBuilder RetAttrs;
  1225. bool HasOptnone = false;
  1226. CallingConv = FI.getEffectiveCallingConvention();
  1227. if (FI.isNoReturn())
  1228. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1229. // FIXME: handle sseregparm someday...
  1230. if (TargetDecl) {
  1231. if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
  1232. FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
  1233. if (TargetDecl->hasAttr<NoThrowAttr>())
  1234. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1235. if (TargetDecl->hasAttr<NoReturnAttr>())
  1236. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1237. if (TargetDecl->hasAttr<NoDuplicateAttr>())
  1238. FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
  1239. if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1240. const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
  1241. if (FPT && FPT->isNothrow(getContext()))
  1242. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1243. // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
  1244. // These attributes are not inherited by overloads.
  1245. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
  1246. if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
  1247. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1248. }
  1249. // 'const' and 'pure' attribute functions are also nounwind.
  1250. if (TargetDecl->hasAttr<ConstAttr>()) {
  1251. FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
  1252. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1253. } else if (TargetDecl->hasAttr<PureAttr>()) {
  1254. FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
  1255. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1256. }
  1257. if (TargetDecl->hasAttr<RestrictAttr>())
  1258. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1259. if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
  1260. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1261. HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
  1262. }
  1263. // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
  1264. if (!HasOptnone) {
  1265. if (CodeGenOpts.OptimizeSize)
  1266. FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
  1267. if (CodeGenOpts.OptimizeSize == 2)
  1268. FuncAttrs.addAttribute(llvm::Attribute::MinSize);
  1269. }
  1270. if (CodeGenOpts.DisableRedZone)
  1271. FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
  1272. if (CodeGenOpts.NoImplicitFloat)
  1273. FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
  1274. if (CodeGenOpts.EnableSegmentedStacks &&
  1275. !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
  1276. FuncAttrs.addAttribute("split-stack");
  1277. if (AttrOnCallSite) {
  1278. // Attributes that should go on the call site only.
  1279. if (!CodeGenOpts.SimplifyLibCalls)
  1280. FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
  1281. if (!CodeGenOpts.TrapFuncName.empty())
  1282. FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
  1283. } else {
  1284. // Attributes that should go on the function, but not the call site.
  1285. if (!CodeGenOpts.DisableFPElim) {
  1286. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1287. } else if (CodeGenOpts.OmitLeafFramePointer) {
  1288. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1289. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1290. } else {
  1291. FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
  1292. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1293. }
  1294. FuncAttrs.addAttribute("disable-tail-calls",
  1295. llvm::toStringRef(CodeGenOpts.DisableTailCalls));
  1296. FuncAttrs.addAttribute("less-precise-fpmad",
  1297. llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
  1298. FuncAttrs.addAttribute("no-infs-fp-math",
  1299. llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
  1300. FuncAttrs.addAttribute("no-nans-fp-math",
  1301. llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
  1302. FuncAttrs.addAttribute("unsafe-fp-math",
  1303. llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
  1304. FuncAttrs.addAttribute("use-soft-float",
  1305. llvm::toStringRef(CodeGenOpts.SoftFloat));
  1306. FuncAttrs.addAttribute("stack-protector-buffer-size",
  1307. llvm::utostr(CodeGenOpts.SSPBufferSize));
  1308. if (!CodeGenOpts.StackRealignment)
  1309. FuncAttrs.addAttribute("no-realign-stack");
  1310. // Add target-cpu and target-features attributes to functions. If
  1311. // we have a decl for the function and it has a target attribute then
  1312. // parse that and add it to the feature set.
  1313. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1314. // TODO: Features gets us the features on the command line including
  1315. // feature dependencies. For canonicalization purposes we might want to
  1316. // avoid putting features in the target-features set if we know it'll be
  1317. // one of the default features in the backend, e.g. corei7-avx and +avx or
  1318. // figure out non-explicit dependencies.
  1319. // Canonicalize the existing features in a new feature map.
  1320. // TODO: Migrate the existing backends to keep the map around rather than
  1321. // the vector.
  1322. llvm::StringMap<bool> FeatureMap;
  1323. for (auto F : getTarget().getTargetOpts().Features) {
  1324. const char *Name = F.c_str();
  1325. bool Enabled = Name[0] == '+';
  1326. getTarget().setFeatureEnabled(FeatureMap, Name + 1, Enabled);
  1327. }
  1328. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
  1329. if (FD) {
  1330. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  1331. StringRef FeaturesStr = TD->getFeatures();
  1332. SmallVector<StringRef, 1> AttrFeatures;
  1333. FeaturesStr.split(AttrFeatures, ",");
  1334. // Grab the various features and prepend a "+" to turn on the feature to
  1335. // the backend and add them to our existing set of features.
  1336. for (auto &Feature : AttrFeatures) {
  1337. // Go ahead and trim whitespace rather than either erroring or
  1338. // accepting it weirdly.
  1339. Feature = Feature.trim();
  1340. // While we're here iterating check for a different target cpu.
  1341. if (Feature.startswith("arch="))
  1342. TargetCPU = Feature.split("=").second.trim();
  1343. else if (Feature.startswith("tune="))
  1344. // We don't support cpu tuning this way currently.
  1345. ;
  1346. else if (Feature.startswith("fpmath="))
  1347. // TODO: Support the fpmath option this way. It will require checking
  1348. // overall feature validity for the function with the rest of the
  1349. // attributes on the function.
  1350. ;
  1351. else if (Feature.startswith("mno-"))
  1352. getTarget().setFeatureEnabled(FeatureMap, Feature.split("-").second,
  1353. false);
  1354. else
  1355. getTarget().setFeatureEnabled(FeatureMap, Feature, true);
  1356. }
  1357. }
  1358. }
  1359. // Produce the canonical string for this set of features.
  1360. std::vector<std::string> Features;
  1361. for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
  1362. ie = FeatureMap.end();
  1363. it != ie; ++it)
  1364. Features.push_back((it->second ? "+" : "-") + it->first().str());
  1365. // Now add the target-cpu and target-features to the function.
  1366. if (TargetCPU != "")
  1367. FuncAttrs.addAttribute("target-cpu", TargetCPU);
  1368. if (!Features.empty()) {
  1369. std::sort(Features.begin(), Features.end());
  1370. FuncAttrs.addAttribute("target-features",
  1371. llvm::join(Features.begin(), Features.end(), ","));
  1372. }
  1373. }
  1374. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
  1375. QualType RetTy = FI.getReturnType();
  1376. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1377. switch (RetAI.getKind()) {
  1378. case ABIArgInfo::Extend:
  1379. if (RetTy->hasSignedIntegerRepresentation())
  1380. RetAttrs.addAttribute(llvm::Attribute::SExt);
  1381. else if (RetTy->hasUnsignedIntegerRepresentation())
  1382. RetAttrs.addAttribute(llvm::Attribute::ZExt);
  1383. // FALL THROUGH
  1384. case ABIArgInfo::Direct:
  1385. if (RetAI.getInReg())
  1386. RetAttrs.addAttribute(llvm::Attribute::InReg);
  1387. break;
  1388. case ABIArgInfo::Ignore:
  1389. break;
  1390. case ABIArgInfo::InAlloca:
  1391. case ABIArgInfo::Indirect: {
  1392. // inalloca and sret disable readnone and readonly
  1393. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1394. .removeAttribute(llvm::Attribute::ReadNone);
  1395. break;
  1396. }
  1397. case ABIArgInfo::Expand:
  1398. llvm_unreachable("Invalid ABI kind for return argument");
  1399. }
  1400. if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
  1401. QualType PTy = RefTy->getPointeeType();
  1402. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1403. RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1404. .getQuantity());
  1405. else if (getContext().getTargetAddressSpace(PTy) == 0)
  1406. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1407. }
  1408. // Attach return attributes.
  1409. if (RetAttrs.hasAttributes()) {
  1410. PAL.push_back(llvm::AttributeSet::get(
  1411. getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
  1412. }
  1413. // Attach attributes to sret.
  1414. if (IRFunctionArgs.hasSRetArg()) {
  1415. llvm::AttrBuilder SRETAttrs;
  1416. SRETAttrs.addAttribute(llvm::Attribute::StructRet);
  1417. if (RetAI.getInReg())
  1418. SRETAttrs.addAttribute(llvm::Attribute::InReg);
  1419. PAL.push_back(llvm::AttributeSet::get(
  1420. getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
  1421. }
  1422. // Attach attributes to inalloca argument.
  1423. if (IRFunctionArgs.hasInallocaArg()) {
  1424. llvm::AttrBuilder Attrs;
  1425. Attrs.addAttribute(llvm::Attribute::InAlloca);
  1426. PAL.push_back(llvm::AttributeSet::get(
  1427. getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
  1428. }
  1429. unsigned ArgNo = 0;
  1430. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
  1431. E = FI.arg_end();
  1432. I != E; ++I, ++ArgNo) {
  1433. QualType ParamType = I->type;
  1434. const ABIArgInfo &AI = I->info;
  1435. llvm::AttrBuilder Attrs;
  1436. // Add attribute for padding argument, if necessary.
  1437. if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
  1438. if (AI.getPaddingInReg())
  1439. PAL.push_back(llvm::AttributeSet::get(
  1440. getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
  1441. llvm::Attribute::InReg));
  1442. }
  1443. // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
  1444. // have the corresponding parameter variable. It doesn't make
  1445. // sense to do it here because parameters are so messed up.
  1446. switch (AI.getKind()) {
  1447. case ABIArgInfo::Extend:
  1448. if (ParamType->isSignedIntegerOrEnumerationType())
  1449. Attrs.addAttribute(llvm::Attribute::SExt);
  1450. else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
  1451. if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
  1452. Attrs.addAttribute(llvm::Attribute::SExt);
  1453. else
  1454. Attrs.addAttribute(llvm::Attribute::ZExt);
  1455. }
  1456. // FALL THROUGH
  1457. case ABIArgInfo::Direct:
  1458. if (ArgNo == 0 && FI.isChainCall())
  1459. Attrs.addAttribute(llvm::Attribute::Nest);
  1460. else if (AI.getInReg())
  1461. Attrs.addAttribute(llvm::Attribute::InReg);
  1462. break;
  1463. case ABIArgInfo::Indirect:
  1464. if (AI.getInReg())
  1465. Attrs.addAttribute(llvm::Attribute::InReg);
  1466. if (AI.getIndirectByVal())
  1467. Attrs.addAttribute(llvm::Attribute::ByVal);
  1468. Attrs.addAlignmentAttr(AI.getIndirectAlign());
  1469. // byval disables readnone and readonly.
  1470. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1471. .removeAttribute(llvm::Attribute::ReadNone);
  1472. break;
  1473. case ABIArgInfo::Ignore:
  1474. case ABIArgInfo::Expand:
  1475. continue;
  1476. case ABIArgInfo::InAlloca:
  1477. // inalloca disables readnone and readonly.
  1478. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1479. .removeAttribute(llvm::Attribute::ReadNone);
  1480. continue;
  1481. }
  1482. if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
  1483. QualType PTy = RefTy->getPointeeType();
  1484. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1485. Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1486. .getQuantity());
  1487. else if (getContext().getTargetAddressSpace(PTy) == 0)
  1488. Attrs.addAttribute(llvm::Attribute::NonNull);
  1489. }
  1490. if (Attrs.hasAttributes()) {
  1491. unsigned FirstIRArg, NumIRArgs;
  1492. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1493. for (unsigned i = 0; i < NumIRArgs; i++)
  1494. PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
  1495. FirstIRArg + i + 1, Attrs));
  1496. }
  1497. }
  1498. assert(ArgNo == FI.arg_size());
  1499. if (FuncAttrs.hasAttributes())
  1500. PAL.push_back(llvm::
  1501. AttributeSet::get(getLLVMContext(),
  1502. llvm::AttributeSet::FunctionIndex,
  1503. FuncAttrs));
  1504. }
  1505. /// An argument came in as a promoted argument; demote it back to its
  1506. /// declared type.
  1507. static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
  1508. const VarDecl *var,
  1509. llvm::Value *value) {
  1510. llvm::Type *varType = CGF.ConvertType(var->getType());
  1511. // This can happen with promotions that actually don't change the
  1512. // underlying type, like the enum promotions.
  1513. if (value->getType() == varType) return value;
  1514. assert((varType->isIntegerTy() || varType->isFloatingPointTy())
  1515. && "unexpected promotion type");
  1516. if (isa<llvm::IntegerType>(varType))
  1517. return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
  1518. return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
  1519. }
  1520. /// Returns the attribute (either parameter attribute, or function
  1521. /// attribute), which declares argument ArgNo to be non-null.
  1522. static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
  1523. QualType ArgType, unsigned ArgNo) {
  1524. // FIXME: __attribute__((nonnull)) can also be applied to:
  1525. // - references to pointers, where the pointee is known to be
  1526. // nonnull (apparently a Clang extension)
  1527. // - transparent unions containing pointers
  1528. // In the former case, LLVM IR cannot represent the constraint. In
  1529. // the latter case, we have no guarantee that the transparent union
  1530. // is in fact passed as a pointer.
  1531. if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
  1532. return nullptr;
  1533. // First, check attribute on parameter itself.
  1534. if (PVD) {
  1535. if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
  1536. return ParmNNAttr;
  1537. }
  1538. // Check function attributes.
  1539. if (!FD)
  1540. return nullptr;
  1541. for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
  1542. if (NNAttr->isNonNull(ArgNo))
  1543. return NNAttr;
  1544. }
  1545. return nullptr;
  1546. }
  1547. void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
  1548. llvm::Function *Fn,
  1549. const FunctionArgList &Args) {
  1550. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
  1551. // Naked functions don't have prologues.
  1552. return;
  1553. // If this is an implicit-return-zero function, go ahead and
  1554. // initialize the return value. TODO: it might be nice to have
  1555. // a more general mechanism for this that didn't require synthesized
  1556. // return statements.
  1557. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  1558. if (FD->hasImplicitReturnZero()) {
  1559. QualType RetTy = FD->getReturnType().getUnqualifiedType();
  1560. llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
  1561. llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
  1562. Builder.CreateStore(Zero, ReturnValue);
  1563. }
  1564. }
  1565. // FIXME: We no longer need the types from FunctionArgList; lift up and
  1566. // simplify.
  1567. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
  1568. // Flattened function arguments.
  1569. SmallVector<llvm::Argument *, 16> FnArgs;
  1570. FnArgs.reserve(IRFunctionArgs.totalIRArgs());
  1571. for (auto &Arg : Fn->args()) {
  1572. FnArgs.push_back(&Arg);
  1573. }
  1574. assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
  1575. // If we're using inalloca, all the memory arguments are GEPs off of the last
  1576. // parameter, which is a pointer to the complete memory area.
  1577. llvm::Value *ArgStruct = nullptr;
  1578. if (IRFunctionArgs.hasInallocaArg()) {
  1579. ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
  1580. assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
  1581. }
  1582. // Name the struct return parameter.
  1583. if (IRFunctionArgs.hasSRetArg()) {
  1584. auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
  1585. AI->setName("agg.result");
  1586. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
  1587. llvm::Attribute::NoAlias));
  1588. }
  1589. // Track if we received the parameter as a pointer (indirect, byval, or
  1590. // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
  1591. // into a local alloca for us.
  1592. enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
  1593. typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
  1594. SmallVector<ValueAndIsPtr, 16> ArgVals;
  1595. ArgVals.reserve(Args.size());
  1596. // Create a pointer value for every parameter declaration. This usually
  1597. // entails copying one or more LLVM IR arguments into an alloca. Don't push
  1598. // any cleanups or do anything that might unwind. We do that separately, so
  1599. // we can push the cleanups in the correct order for the ABI.
  1600. assert(FI.arg_size() == Args.size() &&
  1601. "Mismatch between function signature & arguments.");
  1602. unsigned ArgNo = 0;
  1603. CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
  1604. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1605. i != e; ++i, ++info_it, ++ArgNo) {
  1606. const VarDecl *Arg = *i;
  1607. QualType Ty = info_it->type;
  1608. const ABIArgInfo &ArgI = info_it->info;
  1609. bool isPromoted = !getLangOpts().HLSL && // HLSL Change - no knr promotion in HLSL
  1610. isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
  1611. unsigned FirstIRArg, NumIRArgs;
  1612. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1613. switch (ArgI.getKind()) {
  1614. case ABIArgInfo::InAlloca: {
  1615. assert(NumIRArgs == 0);
  1616. llvm::Value *V =
  1617. Builder.CreateStructGEP(FI.getArgStruct(), ArgStruct,
  1618. ArgI.getInAllocaFieldIndex(), Arg->getName());
  1619. ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
  1620. break;
  1621. }
  1622. case ABIArgInfo::Indirect: {
  1623. assert(NumIRArgs == 1);
  1624. llvm::Value *V = FnArgs[FirstIRArg];
  1625. if (!hasScalarEvaluationKind(Ty)) {
  1626. // Aggregates and complex variables are accessed by reference. All we
  1627. // need to do is realign the value, if requested
  1628. if (ArgI.getIndirectRealign()) {
  1629. llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
  1630. // Copy from the incoming argument pointer to the temporary with the
  1631. // appropriate alignment.
  1632. //
  1633. // FIXME: We should have a common utility for generating an aggregate
  1634. // copy.
  1635. llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
  1636. CharUnits Size = getContext().getTypeSizeInChars(Ty);
  1637. llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
  1638. llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
  1639. Builder.CreateMemCpy(Dst,
  1640. Src,
  1641. llvm::ConstantInt::get(IntPtrTy,
  1642. Size.getQuantity()),
  1643. ArgI.getIndirectAlign(),
  1644. false);
  1645. V = AlignedTemp;
  1646. }
  1647. ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
  1648. } else {
  1649. // Load scalar value from indirect argument.
  1650. V = EmitLoadOfScalar(V, false, ArgI.getIndirectAlign(), Ty,
  1651. Arg->getLocStart());
  1652. if (isPromoted)
  1653. V = emitArgumentDemotion(*this, Arg, V);
  1654. ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
  1655. }
  1656. break;
  1657. }
  1658. case ABIArgInfo::Extend:
  1659. case ABIArgInfo::Direct: {
  1660. // HLSL Change Begins
  1661. if (hlsl::IsHLSLMatType(Ty)) {
  1662. assert(NumIRArgs == 1);
  1663. auto AI = FnArgs[FirstIRArg];
  1664. llvm::Value *V = AI;
  1665. ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
  1666. break;
  1667. }
  1668. // HLSL Change Ends
  1669. // If we have the trivial case, handle it with no muss and fuss.
  1670. if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
  1671. ArgI.getCoerceToType() == ConvertType(Ty) &&
  1672. ArgI.getDirectOffset() == 0) {
  1673. assert(NumIRArgs == 1);
  1674. auto AI = FnArgs[FirstIRArg];
  1675. llvm::Value *V = AI;
  1676. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
  1677. if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
  1678. PVD->getFunctionScopeIndex()))
  1679. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1680. AI->getArgNo() + 1,
  1681. llvm::Attribute::NonNull));
  1682. QualType OTy = PVD->getOriginalType();
  1683. if (const auto *ArrTy =
  1684. getContext().getAsConstantArrayType(OTy)) {
  1685. // A C99 array parameter declaration with the static keyword also
  1686. // indicates dereferenceability, and if the size is constant we can
  1687. // use the dereferenceable attribute (which requires the size in
  1688. // bytes).
  1689. if (ArrTy->getSizeModifier() == ArrayType::Static) {
  1690. QualType ETy = ArrTy->getElementType();
  1691. uint64_t ArrSize = ArrTy->getSize().getZExtValue();
  1692. if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
  1693. ArrSize) {
  1694. llvm::AttrBuilder Attrs;
  1695. Attrs.addDereferenceableAttr(
  1696. getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
  1697. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1698. AI->getArgNo() + 1, Attrs));
  1699. } else if (getContext().getTargetAddressSpace(ETy) == 0) {
  1700. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1701. AI->getArgNo() + 1,
  1702. llvm::Attribute::NonNull));
  1703. }
  1704. }
  1705. } else if (const auto *ArrTy =
  1706. getContext().getAsVariableArrayType(OTy)) {
  1707. // For C99 VLAs with the static keyword, we don't know the size so
  1708. // we can't use the dereferenceable attribute, but in addrspace(0)
  1709. // we know that it must be nonnull.
  1710. if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
  1711. !getContext().getTargetAddressSpace(ArrTy->getElementType()))
  1712. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1713. AI->getArgNo() + 1,
  1714. llvm::Attribute::NonNull));
  1715. }
  1716. const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
  1717. if (!AVAttr)
  1718. if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
  1719. AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
  1720. if (AVAttr) {
  1721. llvm::Value *AlignmentValue =
  1722. EmitScalarExpr(AVAttr->getAlignment());
  1723. llvm::ConstantInt *AlignmentCI =
  1724. cast<llvm::ConstantInt>(AlignmentValue);
  1725. unsigned Alignment =
  1726. std::min((unsigned) AlignmentCI->getZExtValue(),
  1727. +llvm::Value::MaximumAlignment);
  1728. llvm::AttrBuilder Attrs;
  1729. Attrs.addAlignmentAttr(Alignment);
  1730. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1731. AI->getArgNo() + 1, Attrs));
  1732. }
  1733. }
  1734. if (Arg->getType().isRestrictQualified())
  1735. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1736. AI->getArgNo() + 1,
  1737. llvm::Attribute::NoAlias));
  1738. // Ensure the argument is the correct type.
  1739. if (V->getType() != ArgI.getCoerceToType())
  1740. V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
  1741. if (isPromoted)
  1742. V = emitArgumentDemotion(*this, Arg, V);
  1743. if (const CXXMethodDecl *MD =
  1744. dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
  1745. if (MD->isVirtual() && Arg == CXXABIThisDecl)
  1746. V = CGM.getCXXABI().
  1747. adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
  1748. }
  1749. // Because of merging of function types from multiple decls it is
  1750. // possible for the type of an argument to not match the corresponding
  1751. // type in the function type. Since we are codegening the callee
  1752. // in here, add a cast to the argument type.
  1753. llvm::Type *LTy = ConvertType(Arg->getType());
  1754. if (V->getType() != LTy)
  1755. V = Builder.CreateBitCast(V, LTy);
  1756. ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
  1757. break;
  1758. }
  1759. llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
  1760. // The alignment we need to use is the max of the requested alignment for
  1761. // the argument plus the alignment required by our access code below.
  1762. unsigned AlignmentToUse =
  1763. CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
  1764. AlignmentToUse = std::max(AlignmentToUse,
  1765. (unsigned)getContext().getDeclAlign(Arg).getQuantity());
  1766. Alloca->setAlignment(AlignmentToUse);
  1767. llvm::Value *V = Alloca;
  1768. llvm::Value *Ptr = V; // Pointer to store into.
  1769. CharUnits PtrAlign = CharUnits::fromQuantity(AlignmentToUse);
  1770. // If the value is offset in memory, apply the offset now.
  1771. if (unsigned Offs = ArgI.getDirectOffset()) {
  1772. Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
  1773. Ptr = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), Ptr, Offs);
  1774. Ptr = Builder.CreateBitCast(Ptr,
  1775. llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
  1776. PtrAlign = PtrAlign.alignmentAtOffset(CharUnits::fromQuantity(Offs));
  1777. }
  1778. // Fast-isel and the optimizer generally like scalar values better than
  1779. // FCAs, so we flatten them if this is safe to do for this argument.
  1780. llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
  1781. if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
  1782. STy->getNumElements() > 1) {
  1783. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
  1784. llvm::Type *DstTy =
  1785. cast<llvm::PointerType>(Ptr->getType())->getElementType();
  1786. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
  1787. if (SrcSize <= DstSize) {
  1788. Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
  1789. assert(STy->getNumElements() == NumIRArgs);
  1790. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1791. auto AI = FnArgs[FirstIRArg + i];
  1792. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  1793. llvm::Value *EltPtr = Builder.CreateConstGEP2_32(STy, Ptr, 0, i);
  1794. Builder.CreateStore(AI, EltPtr);
  1795. }
  1796. } else {
  1797. llvm::AllocaInst *TempAlloca =
  1798. CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
  1799. TempAlloca->setAlignment(AlignmentToUse);
  1800. llvm::Value *TempV = TempAlloca;
  1801. assert(STy->getNumElements() == NumIRArgs);
  1802. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1803. auto AI = FnArgs[FirstIRArg + i];
  1804. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  1805. llvm::Value *EltPtr =
  1806. Builder.CreateConstGEP2_32(ArgI.getCoerceToType(), TempV, 0, i);
  1807. Builder.CreateStore(AI, EltPtr);
  1808. }
  1809. Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
  1810. }
  1811. } else {
  1812. // Simple case, just do a coerced store of the argument into the alloca.
  1813. assert(NumIRArgs == 1);
  1814. auto AI = FnArgs[FirstIRArg];
  1815. AI->setName(Arg->getName() + ".coerce");
  1816. CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, PtrAlign, *this, Ty); // HLSL Change - Add Ty.
  1817. }
  1818. // Match to what EmitParmDecl is expecting for this type.
  1819. if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
  1820. V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
  1821. if (isPromoted)
  1822. V = emitArgumentDemotion(*this, Arg, V);
  1823. ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
  1824. } else {
  1825. ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
  1826. }
  1827. break;
  1828. }
  1829. case ABIArgInfo::Expand: {
  1830. // If this structure was expanded into multiple arguments then
  1831. // we need to create a temporary and reconstruct it from the
  1832. // arguments.
  1833. llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
  1834. CharUnits Align = getContext().getDeclAlign(Arg);
  1835. Alloca->setAlignment(Align.getQuantity());
  1836. LValue LV = MakeAddrLValue(Alloca, Ty, Align);
  1837. ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
  1838. auto FnArgIter = FnArgs.begin() + FirstIRArg;
  1839. ExpandTypeFromArgs(Ty, LV, FnArgIter);
  1840. assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
  1841. for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
  1842. auto AI = FnArgs[FirstIRArg + i];
  1843. AI->setName(Arg->getName() + "." + Twine(i));
  1844. }
  1845. break;
  1846. }
  1847. case ABIArgInfo::Ignore:
  1848. assert(NumIRArgs == 0);
  1849. // Initialize the local variable appropriately.
  1850. if (!hasScalarEvaluationKind(Ty)) {
  1851. ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
  1852. } else {
  1853. llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
  1854. ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
  1855. }
  1856. break;
  1857. }
  1858. }
  1859. if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1860. for (int I = Args.size() - 1; I >= 0; --I)
  1861. EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
  1862. I + 1);
  1863. } else {
  1864. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  1865. EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
  1866. I + 1);
  1867. }
  1868. // HLSL Change Begins.
  1869. if (getLangOpts().HLSL) {
  1870. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  1871. CGM.getHLSLRuntime().EmitHLSLFunctionProlog(Fn, FD);
  1872. }
  1873. }
  1874. // HLSL Change Ends.
  1875. }
  1876. #if 0 // HLSL Change Start - no ObjC support
  1877. static void eraseUnusedBitCasts(llvm::Instruction *insn) {
  1878. while (insn->use_empty()) {
  1879. llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
  1880. if (!bitcast) return;
  1881. // This is "safe" because we would have used a ConstantExpr otherwise.
  1882. insn = cast<llvm::Instruction>(bitcast->getOperand(0));
  1883. bitcast->eraseFromParent();
  1884. }
  1885. }
  1886. /// Try to emit a fused autorelease of a return result.
  1887. static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
  1888. llvm::Value *result) {
  1889. // We must be immediately followed the cast.
  1890. llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
  1891. if (BB->empty()) return nullptr;
  1892. if (&BB->back() != result) return nullptr;
  1893. llvm::Type *resultType = result->getType();
  1894. // result is in a BasicBlock and is therefore an Instruction.
  1895. llvm::Instruction *generator = cast<llvm::Instruction>(result);
  1896. SmallVector<llvm::Instruction*,4> insnsToKill;
  1897. // Look for:
  1898. // %generator = bitcast %type1* %generator2 to %type2*
  1899. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
  1900. // We would have emitted this as a constant if the operand weren't
  1901. // an Instruction.
  1902. generator = cast<llvm::Instruction>(bitcast->getOperand(0));
  1903. // Require the generator to be immediately followed by the cast.
  1904. if (generator->getNextNode() != bitcast)
  1905. return nullptr;
  1906. insnsToKill.push_back(bitcast);
  1907. }
  1908. // Look for:
  1909. // %generator = call i8* @objc_retain(i8* %originalResult)
  1910. // or
  1911. // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
  1912. llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
  1913. if (!call) return nullptr;
  1914. bool doRetainAutorelease;
  1915. if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
  1916. doRetainAutorelease = true;
  1917. } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
  1918. .objc_retainAutoreleasedReturnValue) {
  1919. doRetainAutorelease = false;
  1920. // If we emitted an assembly marker for this call (and the
  1921. // ARCEntrypoints field should have been set if so), go looking
  1922. // for that call. If we can't find it, we can't do this
  1923. // optimization. But it should always be the immediately previous
  1924. // instruction, unless we needed bitcasts around the call.
  1925. if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
  1926. llvm::Instruction *prev = call->getPrevNode();
  1927. assert(prev);
  1928. if (isa<llvm::BitCastInst>(prev)) {
  1929. prev = prev->getPrevNode();
  1930. assert(prev);
  1931. }
  1932. assert(isa<llvm::CallInst>(prev));
  1933. assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
  1934. CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
  1935. insnsToKill.push_back(prev);
  1936. }
  1937. } else {
  1938. return nullptr;
  1939. }
  1940. result = call->getArgOperand(0);
  1941. insnsToKill.push_back(call);
  1942. // Keep killing bitcasts, for sanity. Note that we no longer care
  1943. // about precise ordering as long as there's exactly one use.
  1944. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
  1945. if (!bitcast->hasOneUse()) break;
  1946. insnsToKill.push_back(bitcast);
  1947. result = bitcast->getOperand(0);
  1948. }
  1949. // Delete all the unnecessary instructions, from latest to earliest.
  1950. for (SmallVectorImpl<llvm::Instruction*>::iterator
  1951. i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
  1952. (*i)->eraseFromParent();
  1953. // Do the fused retain/autorelease if we were asked to.
  1954. if (doRetainAutorelease)
  1955. result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
  1956. // Cast back to the result type.
  1957. return CGF.Builder.CreateBitCast(result, resultType);
  1958. }
  1959. /// If this is a +1 of the value of an immutable 'self', remove it.
  1960. static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
  1961. llvm::Value *result) {
  1962. // This is only applicable to a method with an immutable 'self'.
  1963. const ObjCMethodDecl *method =
  1964. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
  1965. if (!method) return nullptr;
  1966. const VarDecl *self = method->getSelfDecl();
  1967. if (!self->getType().isConstQualified()) return nullptr;
  1968. // Look for a retain call.
  1969. llvm::CallInst *retainCall =
  1970. dyn_cast<llvm::CallInst>(result->stripPointerCasts());
  1971. if (!retainCall ||
  1972. retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
  1973. return nullptr;
  1974. // Look for an ordinary load of 'self'.
  1975. llvm::Value *retainedValue = retainCall->getArgOperand(0);
  1976. llvm::LoadInst *load =
  1977. dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
  1978. if (!load || load->isAtomic() || load->isVolatile() ||
  1979. load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
  1980. return nullptr;
  1981. // Okay! Burn it all down. This relies for correctness on the
  1982. // assumption that the retain is emitted as part of the return and
  1983. // that thereafter everything is used "linearly".
  1984. llvm::Type *resultType = result->getType();
  1985. eraseUnusedBitCasts(cast<llvm::Instruction>(result));
  1986. assert(retainCall->use_empty());
  1987. retainCall->eraseFromParent();
  1988. eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
  1989. return CGF.Builder.CreateBitCast(load, resultType);
  1990. }
  1991. /// Emit an ARC autorelease of the result of a function.
  1992. ///
  1993. /// \return the value to actually return from the function
  1994. static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
  1995. llvm::Value *result) {
  1996. // If we're returning 'self', kill the initial retain. This is a
  1997. // heuristic attempt to "encourage correctness" in the really unfortunate
  1998. // case where we have a return of self during a dealloc and we desperately
  1999. // need to avoid the possible autorelease.
  2000. if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
  2001. return self;
  2002. // At -O0, try to emit a fused retain/autorelease.
  2003. if (CGF.shouldUseFusedARCCalls())
  2004. if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
  2005. return fused;
  2006. return CGF.EmitARCAutoreleaseReturnValue(result);
  2007. }
  2008. #endif // HLSL Change Ends - no ObjC support
  2009. /// Heuristically search for a dominating store to the return-value slot.
  2010. static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
  2011. // If there are multiple uses of the return-value slot, just check
  2012. // for something immediately preceding the IP. Sometimes this can
  2013. // happen with how we generate implicit-returns; it can also happen
  2014. // with noreturn cleanups.
  2015. if (!CGF.ReturnValue->hasOneUse()) {
  2016. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2017. if (IP->empty()) return nullptr;
  2018. llvm::Instruction *I = &IP->back();
  2019. // Skip lifetime markers
  2020. for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
  2021. IE = IP->rend();
  2022. II != IE; ++II) {
  2023. if (llvm::IntrinsicInst *Intrinsic =
  2024. dyn_cast<llvm::IntrinsicInst>(&*II)) {
  2025. if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
  2026. const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
  2027. ++II;
  2028. if (II == IE)
  2029. break;
  2030. if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
  2031. continue;
  2032. }
  2033. }
  2034. I = &*II;
  2035. break;
  2036. }
  2037. llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(I);
  2038. if (!store) return nullptr;
  2039. if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
  2040. assert(!store->isAtomic() && !store->isVolatile()); // see below
  2041. return store;
  2042. }
  2043. llvm::StoreInst *store =
  2044. dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
  2045. if (!store) return nullptr;
  2046. // These aren't actually possible for non-coerced returns, and we
  2047. // only care about non-coerced returns on this code path.
  2048. assert(!store->isAtomic() && !store->isVolatile());
  2049. // Now do a first-and-dirty dominance check: just walk up the
  2050. // single-predecessors chain from the current insertion point.
  2051. llvm::BasicBlock *StoreBB = store->getParent();
  2052. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2053. while (IP != StoreBB) {
  2054. if (!(IP = IP->getSinglePredecessor()))
  2055. return nullptr;
  2056. }
  2057. // Okay, the store's basic block dominates the insertion point; we
  2058. // can do our thing.
  2059. return store;
  2060. }
  2061. void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
  2062. bool EmitRetDbgLoc,
  2063. SourceLocation EndLoc) {
  2064. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
  2065. // Naked functions don't have epilogues.
  2066. Builder.CreateUnreachable();
  2067. return;
  2068. }
  2069. // Functions with no result always return void.
  2070. if (!ReturnValue) {
  2071. Builder.CreateRetVoid();
  2072. return;
  2073. }
  2074. llvm::DebugLoc RetDbgLoc;
  2075. llvm::Value *RV = nullptr;
  2076. QualType RetTy = FI.getReturnType();
  2077. const ABIArgInfo &RetAI = FI.getReturnInfo();
  2078. switch (RetAI.getKind()) {
  2079. case ABIArgInfo::InAlloca:
  2080. // Aggregrates get evaluated directly into the destination. Sometimes we
  2081. // need to return the sret value in a register, though.
  2082. assert(hasAggregateEvaluationKind(RetTy));
  2083. if (RetAI.getInAllocaSRet()) {
  2084. llvm::Function::arg_iterator EI = CurFn->arg_end();
  2085. --EI;
  2086. llvm::Value *ArgStruct = EI;
  2087. llvm::Value *SRet = Builder.CreateStructGEP(
  2088. nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
  2089. RV = Builder.CreateLoad(SRet, "sret");
  2090. }
  2091. break;
  2092. case ABIArgInfo::Indirect: {
  2093. auto AI = CurFn->arg_begin();
  2094. if (RetAI.isSRetAfterThis())
  2095. ++AI;
  2096. switch (getEvaluationKind(RetTy)) {
  2097. case TEK_Complex: {
  2098. ComplexPairTy RT =
  2099. EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
  2100. EndLoc);
  2101. EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
  2102. /*isInit*/ true);
  2103. break;
  2104. }
  2105. case TEK_Aggregate:
  2106. // Do nothing; aggregrates get evaluated directly into the destination.
  2107. break;
  2108. case TEK_Scalar:
  2109. EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
  2110. MakeNaturalAlignAddrLValue(AI, RetTy),
  2111. /*isInit*/ true);
  2112. break;
  2113. }
  2114. break;
  2115. }
  2116. case ABIArgInfo::Extend:
  2117. case ABIArgInfo::Direct:
  2118. if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
  2119. RetAI.getDirectOffset() == 0) {
  2120. // HLSL Change Begin.
  2121. // If optimization is disabled, just load return value.
  2122. if (CGM.getCodeGenOpts().DisableLLVMOpts) {
  2123. // HLSL Change Begins
  2124. if (hlsl::IsHLSLMatType(RetTy))
  2125. RV = CGM.getHLSLRuntime().EmitHLSLMatrixLoad(*this, ReturnValue,
  2126. FnRetTy); // FnRetTy retains attributed type
  2127. else
  2128. // HLSL Change Ends
  2129. RV = Builder.CreateLoad(ReturnValue);
  2130. } else {
  2131. // HLSL Change End.
  2132. // The internal return value temp always will have pointer-to-return-type
  2133. // type, just do a load.
  2134. // If there is a dominating store to ReturnValue, we can elide
  2135. // the load, zap the store, and usually zap the alloca.
  2136. if (llvm::StoreInst *SI =
  2137. findDominatingStoreToReturnValue(*this)) {
  2138. // Reuse the debug location from the store unless there is
  2139. // cleanup code to be emitted between the store and return
  2140. // instruction.
  2141. if (EmitRetDbgLoc && !AutoreleaseResult)
  2142. RetDbgLoc = SI->getDebugLoc();
  2143. // Get the stored value and nuke the now-dead store.
  2144. RV = SI->getValueOperand();
  2145. SI->eraseFromParent();
  2146. // If that was the only use of the return value, nuke it as well now.
  2147. if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
  2148. cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
  2149. ReturnValue = nullptr;
  2150. }
  2151. // Otherwise, we have to do a simple load.
  2152. } else {
  2153. // HLSL Change Begins
  2154. if (hlsl::IsHLSLMatType(RetTy))
  2155. RV = CGM.getHLSLRuntime().EmitHLSLMatrixLoad(*this, ReturnValue,
  2156. FnRetTy); // FnRetTy retains attributed type
  2157. else
  2158. // HLSL Change Ends
  2159. RV = Builder.CreateLoad(ReturnValue);
  2160. }
  2161. } // HLSL Change
  2162. } else {
  2163. llvm::Value *V = ReturnValue;
  2164. CharUnits Align = getContext().getTypeAlignInChars(RetTy);
  2165. // If the value is offset in memory, apply the offset now.
  2166. if (unsigned Offs = RetAI.getDirectOffset()) {
  2167. V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
  2168. V = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), V, Offs);
  2169. V = Builder.CreateBitCast(V,
  2170. llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
  2171. Align = Align.alignmentAtOffset(CharUnits::fromQuantity(Offs));
  2172. }
  2173. RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), Align, *this);
  2174. }
  2175. // In ARC, end functions that return a retainable type with a call
  2176. // to objc_autoreleaseReturnValue.
  2177. #if 0 // HLSL Change - no ObjC support
  2178. if (AutoreleaseResult) {
  2179. assert(getLangOpts().ObjCAutoRefCount &&
  2180. !FI.isReturnsRetained() &&
  2181. RetTy->isObjCRetainableType());
  2182. RV = emitAutoreleaseOfResult(*this, RV);
  2183. }
  2184. #else
  2185. assert(!AutoreleaseResult && "autorelease not supported in HLSL");
  2186. #endif // HLSL Change - no ObjC support
  2187. break;
  2188. case ABIArgInfo::Ignore:
  2189. break;
  2190. case ABIArgInfo::Expand:
  2191. llvm_unreachable("Invalid ABI kind for return argument");
  2192. }
  2193. llvm::Instruction *Ret;
  2194. if (RV) {
  2195. if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
  2196. if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
  2197. SanitizerScope SanScope(this);
  2198. llvm::Value *Cond = Builder.CreateICmpNE(
  2199. RV, llvm::Constant::getNullValue(RV->getType()));
  2200. llvm::Constant *StaticData[] = {
  2201. EmitCheckSourceLocation(EndLoc),
  2202. EmitCheckSourceLocation(RetNNAttr->getLocation()),
  2203. };
  2204. EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
  2205. "nonnull_return", StaticData, None);
  2206. }
  2207. }
  2208. Ret = Builder.CreateRet(RV);
  2209. } else {
  2210. Ret = Builder.CreateRetVoid();
  2211. }
  2212. if (RetDbgLoc)
  2213. Ret->setDebugLoc(std::move(RetDbgLoc));
  2214. }
  2215. static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
  2216. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2217. return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
  2218. }
  2219. static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
  2220. // FIXME: Generate IR in one pass, rather than going back and fixing up these
  2221. // placeholders.
  2222. llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
  2223. llvm::Value *Placeholder =
  2224. llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
  2225. Placeholder = CGF.Builder.CreateLoad(Placeholder);
  2226. return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
  2227. Ty.getQualifiers(),
  2228. AggValueSlot::IsNotDestructed,
  2229. AggValueSlot::DoesNotNeedGCBarriers,
  2230. AggValueSlot::IsNotAliased);
  2231. }
  2232. void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
  2233. const VarDecl *param,
  2234. SourceLocation loc) {
  2235. // StartFunction converted the ABI-lowered parameter(s) into a
  2236. // local alloca. We need to turn that into an r-value suitable
  2237. // for EmitCall.
  2238. llvm::Value *local = GetAddrOfLocalVar(param);
  2239. QualType type = param->getType();
  2240. // For the most part, we just need to load the alloca, except:
  2241. // 1) aggregate r-values are actually pointers to temporaries, and
  2242. // 2) references to non-scalars are pointers directly to the aggregate.
  2243. // I don't know why references to scalars are different here.
  2244. if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
  2245. if (!hasScalarEvaluationKind(ref->getPointeeType()))
  2246. return args.add(RValue::getAggregate(local), type);
  2247. // Locals which are references to scalars are represented
  2248. // with allocas holding the pointer.
  2249. return args.add(RValue::get(Builder.CreateLoad(local)), type);
  2250. }
  2251. assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
  2252. "cannot emit delegate call arguments for inalloca arguments!");
  2253. args.add(convertTempToRValue(local, type, loc), type);
  2254. }
  2255. #if 0 // HLSL Change - no ObjC support
  2256. static bool isProvablyNull(llvm::Value *addr) {
  2257. return isa<llvm::ConstantPointerNull>(addr);
  2258. }
  2259. static bool isProvablyNonNull(llvm::Value *addr) {
  2260. return isa<llvm::AllocaInst>(addr);
  2261. }
  2262. /// Emit the actual writing-back of a writeback.
  2263. static void emitWriteback(CodeGenFunction &CGF,
  2264. const CallArgList::Writeback &writeback) {
  2265. const LValue &srcLV = writeback.Source;
  2266. llvm::Value *srcAddr = srcLV.getAddress();
  2267. assert(!isProvablyNull(srcAddr) &&
  2268. "shouldn't have writeback for provably null argument");
  2269. llvm::BasicBlock *contBB = nullptr;
  2270. // If the argument wasn't provably non-null, we need to null check
  2271. // before doing the store.
  2272. bool provablyNonNull = isProvablyNonNull(srcAddr);
  2273. if (!provablyNonNull) {
  2274. llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
  2275. contBB = CGF.createBasicBlock("icr.done");
  2276. llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
  2277. CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
  2278. CGF.EmitBlock(writebackBB);
  2279. }
  2280. // Load the value to writeback.
  2281. llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
  2282. // Cast it back, in case we're writing an id to a Foo* or something.
  2283. value = CGF.Builder.CreateBitCast(value,
  2284. cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
  2285. "icr.writeback-cast");
  2286. // Perform the writeback.
  2287. // If we have a "to use" value, it's something we need to emit a use
  2288. // of. This has to be carefully threaded in: if it's done after the
  2289. // release it's potentially undefined behavior (and the optimizer
  2290. // will ignore it), and if it happens before the retain then the
  2291. // optimizer could move the release there.
  2292. if (writeback.ToUse) {
  2293. assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
  2294. // Retain the new value. No need to block-copy here: the block's
  2295. // being passed up the stack.
  2296. value = CGF.EmitARCRetainNonBlock(value);
  2297. // Emit the intrinsic use here.
  2298. CGF.EmitARCIntrinsicUse(writeback.ToUse);
  2299. // Load the old value (primitively).
  2300. llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
  2301. // Put the new value in place (primitively).
  2302. CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
  2303. // Release the old value.
  2304. CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
  2305. // Otherwise, we can just do a normal lvalue store.
  2306. } else {
  2307. CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
  2308. }
  2309. // Jump to the continuation block.
  2310. if (!provablyNonNull)
  2311. CGF.EmitBlock(contBB);
  2312. }
  2313. static void emitWritebacks(CodeGenFunction &CGF,
  2314. const CallArgList &args) {
  2315. for (const auto &I : args.writebacks())
  2316. emitWriteback(CGF, I);
  2317. }
  2318. #endif // HLSL Change - no ObjC support
  2319. static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
  2320. const CallArgList &CallArgs) {
  2321. assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
  2322. ArrayRef<CallArgList::CallArgCleanup> Cleanups =
  2323. CallArgs.getCleanupsToDeactivate();
  2324. // Iterate in reverse to increase the likelihood of popping the cleanup.
  2325. for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
  2326. I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
  2327. CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
  2328. I->IsActiveIP->eraseFromParent();
  2329. }
  2330. }
  2331. #if 0 // HLSL Change - no ObjC support
  2332. static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
  2333. if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
  2334. if (uop->getOpcode() == UO_AddrOf)
  2335. return uop->getSubExpr();
  2336. return nullptr;
  2337. }
  2338. /// Emit an argument that's being passed call-by-writeback. That is,
  2339. /// we are passing the address of
  2340. static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
  2341. const ObjCIndirectCopyRestoreExpr *CRE) {
  2342. LValue srcLV;
  2343. // Make an optimistic effort to emit the address as an l-value.
  2344. // This can fail if the argument expression is more complicated.
  2345. if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
  2346. srcLV = CGF.EmitLValue(lvExpr);
  2347. // Otherwise, just emit it as a scalar.
  2348. } else {
  2349. llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
  2350. QualType srcAddrType =
  2351. CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2352. srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
  2353. }
  2354. llvm::Value *srcAddr = srcLV.getAddress();
  2355. // The dest and src types don't necessarily match in LLVM terms
  2356. // because of the crazy ObjC compatibility rules.
  2357. llvm::PointerType *destType =
  2358. cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
  2359. // If the address is a constant null, just pass the appropriate null.
  2360. if (isProvablyNull(srcAddr)) {
  2361. args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
  2362. CRE->getType());
  2363. return;
  2364. }
  2365. // Create the temporary.
  2366. llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
  2367. "icr.temp");
  2368. // Loading an l-value can introduce a cleanup if the l-value is __weak,
  2369. // and that cleanup will be conditional if we can't prove that the l-value
  2370. // isn't null, so we need to register a dominating point so that the cleanups
  2371. // system will make valid IR.
  2372. CodeGenFunction::ConditionalEvaluation condEval(CGF);
  2373. // Zero-initialize it if we're not doing a copy-initialization.
  2374. bool shouldCopy = CRE->shouldCopy();
  2375. if (!shouldCopy) {
  2376. llvm::Value *null =
  2377. llvm::ConstantPointerNull::get(
  2378. cast<llvm::PointerType>(destType->getElementType()));
  2379. CGF.Builder.CreateStore(null, temp);
  2380. }
  2381. llvm::BasicBlock *contBB = nullptr;
  2382. llvm::BasicBlock *originBB = nullptr;
  2383. // If the address is *not* known to be non-null, we need to switch.
  2384. llvm::Value *finalArgument;
  2385. bool provablyNonNull = isProvablyNonNull(srcAddr);
  2386. if (provablyNonNull) {
  2387. finalArgument = temp;
  2388. } else {
  2389. llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
  2390. finalArgument = CGF.Builder.CreateSelect(isNull,
  2391. llvm::ConstantPointerNull::get(destType),
  2392. temp, "icr.argument");
  2393. // If we need to copy, then the load has to be conditional, which
  2394. // means we need control flow.
  2395. if (shouldCopy) {
  2396. originBB = CGF.Builder.GetInsertBlock();
  2397. contBB = CGF.createBasicBlock("icr.cont");
  2398. llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
  2399. CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
  2400. CGF.EmitBlock(copyBB);
  2401. condEval.begin(CGF);
  2402. }
  2403. }
  2404. llvm::Value *valueToUse = nullptr;
  2405. // Perform a copy if necessary.
  2406. if (shouldCopy) {
  2407. RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
  2408. assert(srcRV.isScalar());
  2409. llvm::Value *src = srcRV.getScalarVal();
  2410. src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
  2411. "icr.cast");
  2412. // Use an ordinary store, not a store-to-lvalue.
  2413. CGF.Builder.CreateStore(src, temp);
  2414. // If optimization is enabled, and the value was held in a
  2415. // __strong variable, we need to tell the optimizer that this
  2416. // value has to stay alive until we're doing the store back.
  2417. // This is because the temporary is effectively unretained,
  2418. // and so otherwise we can violate the high-level semantics.
  2419. if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2420. srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
  2421. valueToUse = src;
  2422. }
  2423. }
  2424. // Finish the control flow if we needed it.
  2425. if (shouldCopy && !provablyNonNull) {
  2426. llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
  2427. CGF.EmitBlock(contBB);
  2428. // Make a phi for the value to intrinsically use.
  2429. if (valueToUse) {
  2430. llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
  2431. "icr.to-use");
  2432. phiToUse->addIncoming(valueToUse, copyBB);
  2433. phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
  2434. originBB);
  2435. valueToUse = phiToUse;
  2436. }
  2437. condEval.end(CGF);
  2438. }
  2439. args.addWriteback(srcLV, temp, valueToUse);
  2440. args.add(RValue::get(finalArgument), CRE->getType());
  2441. }
  2442. #endif // HLSL Change - no ObjC support
  2443. void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
  2444. assert(!StackBase && !StackCleanup.isValid());
  2445. // Save the stack.
  2446. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  2447. StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
  2448. // Control gets really tied up in landing pads, so we have to spill the
  2449. // stacksave to an alloca to avoid violating SSA form.
  2450. // TODO: This is dead if we never emit the cleanup. We should create the
  2451. // alloca and store lazily on the first cleanup emission.
  2452. StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
  2453. CGF.Builder.CreateStore(StackBase, StackBaseMem);
  2454. CGF.pushStackRestore(EHCleanup, StackBaseMem);
  2455. StackCleanup = CGF.EHStack.getInnermostEHScope();
  2456. assert(StackCleanup.isValid());
  2457. }
  2458. void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
  2459. if (StackBase) {
  2460. CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
  2461. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  2462. // We could load StackBase from StackBaseMem, but in the non-exceptional
  2463. // case we can skip it.
  2464. CGF.Builder.CreateCall(F, StackBase);
  2465. }
  2466. }
  2467. void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
  2468. SourceLocation ArgLoc,
  2469. const FunctionDecl *FD,
  2470. unsigned ParmNum) {
  2471. if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
  2472. return;
  2473. auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
  2474. unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
  2475. auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
  2476. if (!NNAttr)
  2477. return;
  2478. SanitizerScope SanScope(this);
  2479. assert(RV.isScalar());
  2480. llvm::Value *V = RV.getScalarVal();
  2481. llvm::Value *Cond =
  2482. Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
  2483. llvm::Constant *StaticData[] = {
  2484. EmitCheckSourceLocation(ArgLoc),
  2485. EmitCheckSourceLocation(NNAttr->getLocation()),
  2486. llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
  2487. };
  2488. EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
  2489. "nonnull_arg", StaticData, None);
  2490. }
  2491. void CodeGenFunction::EmitCallArgs(CallArgList &Args,
  2492. ArrayRef<QualType> ArgTypes,
  2493. CallExpr::const_arg_iterator ArgBeg,
  2494. CallExpr::const_arg_iterator ArgEnd,
  2495. const FunctionDecl *CalleeDecl,
  2496. unsigned ParamsToSkip) {
  2497. // We *have* to evaluate arguments from right to left in the MS C++ ABI,
  2498. // because arguments are destroyed left to right in the callee.
  2499. if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2500. // Insert a stack save if we're going to need any inalloca args.
  2501. bool HasInAllocaArgs = false;
  2502. for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
  2503. I != E && !HasInAllocaArgs; ++I)
  2504. HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
  2505. if (HasInAllocaArgs) {
  2506. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2507. Args.allocateArgumentMemory(*this);
  2508. }
  2509. // Evaluate each argument.
  2510. size_t CallArgsStart = Args.size();
  2511. for (int I = ArgTypes.size() - 1; I >= 0; --I) {
  2512. CallExpr::const_arg_iterator Arg = ArgBeg + I;
  2513. EmitCallArg(Args, *Arg, ArgTypes[I]);
  2514. EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
  2515. CalleeDecl, ParamsToSkip + I);
  2516. }
  2517. // Un-reverse the arguments we just evaluated so they match up with the LLVM
  2518. // IR function.
  2519. std::reverse(Args.begin() + CallArgsStart, Args.end());
  2520. return;
  2521. }
  2522. for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
  2523. CallExpr::const_arg_iterator Arg = ArgBeg + I;
  2524. assert(Arg != ArgEnd);
  2525. EmitCallArg(Args, *Arg, ArgTypes[I]);
  2526. EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
  2527. CalleeDecl, ParamsToSkip + I);
  2528. }
  2529. }
  2530. namespace {
  2531. struct DestroyUnpassedArg : EHScopeStack::Cleanup {
  2532. DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
  2533. : Addr(Addr), Ty(Ty) {}
  2534. llvm::Value *Addr;
  2535. QualType Ty;
  2536. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2537. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  2538. assert(!Dtor->isTrivial());
  2539. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
  2540. /*Delegating=*/false, Addr);
  2541. }
  2542. };
  2543. }
  2544. struct DisableDebugLocationUpdates {
  2545. CodeGenFunction &CGF;
  2546. bool disabledDebugInfo;
  2547. DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
  2548. if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
  2549. CGF.disableDebugInfo();
  2550. }
  2551. ~DisableDebugLocationUpdates() {
  2552. if (disabledDebugInfo)
  2553. CGF.enableDebugInfo();
  2554. }
  2555. };
  2556. void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
  2557. QualType type) {
  2558. DisableDebugLocationUpdates Dis(*this, E);
  2559. #if 0 // HLSL Change - no ObjC support
  2560. if (const ObjCIndirectCopyRestoreExpr *CRE
  2561. = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
  2562. assert(getLangOpts().ObjCAutoRefCount);
  2563. assert(getContext().hasSameType(E->getType(), type));
  2564. return emitWritebackArg(*this, args, CRE);
  2565. }
  2566. #endif // HLSL Change - no ObjC support
  2567. assert(type->isReferenceType() == E->isGLValue() &&
  2568. "reference binding to unmaterialized r-value!");
  2569. if (E->isGLValue()) {
  2570. // HLSL Change Begins.
  2571. if (E->getObjectKind() == OK_VectorComponent) {
  2572. if (const HLSLVectorElementExpr *VecElt = dyn_cast<HLSLVectorElementExpr>(E)) {
  2573. LValue LV = EmitHLSLVectorElementExpr(VecElt);
  2574. llvm::Value *V = LV.getExtVectorAddr();
  2575. llvm::Constant *Elts = LV.getExtVectorElts();
  2576. // Only support scalar for atomic operations.
  2577. assert(Elts->getType()->getVectorNumElements() == 1);
  2578. llvm::Value *ch = Builder.CreateExtractElement(Elts, (uint64_t)0);
  2579. llvm::Value *Ptr = Builder.CreateGEP(V, {Builder.getInt32(0), ch});
  2580. RValue RV = RValue::get(Ptr);
  2581. return args.add(RV, type);
  2582. } else {
  2583. LValue LV = EmitExtMatrixElementExpr(cast<ExtMatrixElementExpr>(E));
  2584. llvm::Value *Ptr = LV.getAddress();
  2585. // Only support scalar for atomic operations.
  2586. assert(Ptr->getType()->getPointerElementType() == Ptr->getType()->getPointerElementType()->getScalarType());
  2587. RValue RV = RValue::get(Ptr);
  2588. return args.add(RV, type);
  2589. }
  2590. }
  2591. // HLSL Change Ends.
  2592. assert(E->getObjectKind() == OK_Ordinary);
  2593. return args.add(EmitReferenceBindingToExpr(E), type);
  2594. }
  2595. bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
  2596. // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
  2597. // However, we still have to push an EH-only cleanup in case we unwind before
  2598. // we make it to the call.
  2599. if (HasAggregateEvalKind &&
  2600. !LangOptions().HLSL && // HLSL Change : Do not generate agg.tmp for HLSL
  2601. CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2602. // If we're using inalloca, use the argument memory. Otherwise, use a
  2603. // temporary.
  2604. AggValueSlot Slot;
  2605. if (args.isUsingInAlloca())
  2606. Slot = createPlaceholderSlot(*this, type);
  2607. else
  2608. Slot = CreateAggTemp(type, "agg.tmp");
  2609. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2610. bool DestroyedInCallee =
  2611. RD && RD->hasNonTrivialDestructor() &&
  2612. CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
  2613. if (DestroyedInCallee)
  2614. Slot.setExternallyDestructed();
  2615. EmitAggExpr(E, Slot);
  2616. RValue RV = Slot.asRValue();
  2617. args.add(RV, type);
  2618. if (DestroyedInCallee) {
  2619. // Create a no-op GEP between the placeholder and the cleanup so we can
  2620. // RAUW it successfully. It also serves as a marker of the first
  2621. // instruction where the cleanup is active.
  2622. pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
  2623. // This unreachable is a temporary marker which will be removed later.
  2624. llvm::Instruction *IsActive = Builder.CreateUnreachable();
  2625. args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
  2626. }
  2627. return;
  2628. }
  2629. if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
  2630. cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
  2631. LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
  2632. assert(L.isSimple());
  2633. if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
  2634. // HLSL Change Begin - don't copy input arg.
  2635. // Copy for out param is done at CGMSHLSLRuntime::EmitHLSLOutParamConversion*.
  2636. args.add(L.asAggregateRValue(), type); // /*NeedsCopy*/true);
  2637. // HLSL Change End
  2638. } else {
  2639. // We can't represent a misaligned lvalue in the CallArgList, so copy
  2640. // to an aligned temporary now.
  2641. llvm::Value *tmp = CreateMemTemp(type);
  2642. EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
  2643. L.getAlignment());
  2644. args.add(RValue::getAggregate(tmp), type);
  2645. }
  2646. return;
  2647. }
  2648. // HLSL Change Begins.
  2649. // For DeclRefExpr of aggregate type, don't create temp.
  2650. if (HasAggregateEvalKind && LangOptions().HLSL &&
  2651. isa<DeclRefExpr>(E)) {
  2652. LValue LV = EmitDeclRefLValue(cast<DeclRefExpr>(E));
  2653. RValue RV = RValue::getAggregate(LV.getAddress());
  2654. args.add(RV, type);
  2655. return;
  2656. }
  2657. // HLSL Change Ends.
  2658. args.add(EmitAnyExprToTemp(E), type);
  2659. }
  2660. QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
  2661. // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
  2662. // implicitly widens null pointer constants that are arguments to varargs
  2663. // functions to pointer-sized ints.
  2664. if (!getTarget().getTriple().isOSWindows())
  2665. return Arg->getType();
  2666. if (Arg->getType()->isIntegerType() &&
  2667. getContext().getTypeSize(Arg->getType()) <
  2668. getContext().getTargetInfo().getPointerWidth(0) &&
  2669. Arg->isNullPointerConstant(getContext(),
  2670. Expr::NPC_ValueDependentIsNotNull)) {
  2671. return getContext().getIntPtrType();
  2672. }
  2673. return Arg->getType();
  2674. }
  2675. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  2676. // optimizer it can aggressively ignore unwind edges.
  2677. void
  2678. CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
  2679. if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2680. !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  2681. Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
  2682. CGM.getNoObjCARCExceptionsMetadata());
  2683. }
  2684. /// Emits a call to the given no-arguments nounwind runtime function.
  2685. llvm::CallInst *
  2686. CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
  2687. const llvm::Twine &name) {
  2688. return EmitNounwindRuntimeCall(callee, None, name);
  2689. }
  2690. /// Emits a call to the given nounwind runtime function.
  2691. llvm::CallInst *
  2692. CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
  2693. ArrayRef<llvm::Value*> args,
  2694. const llvm::Twine &name) {
  2695. llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
  2696. call->setDoesNotThrow();
  2697. return call;
  2698. }
  2699. /// Emits a simple call (never an invoke) to the given no-arguments
  2700. /// runtime function.
  2701. llvm::CallInst *
  2702. CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
  2703. const llvm::Twine &name) {
  2704. return EmitRuntimeCall(callee, None, name);
  2705. }
  2706. /// Emits a simple call (never an invoke) to the given runtime
  2707. /// function.
  2708. llvm::CallInst *
  2709. CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
  2710. ArrayRef<llvm::Value*> args,
  2711. const llvm::Twine &name) {
  2712. llvm::CallInst *call = Builder.CreateCall(callee, args, name);
  2713. call->setCallingConv(getRuntimeCC());
  2714. return call;
  2715. }
  2716. /// Emits a call or invoke to the given noreturn runtime function.
  2717. void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2718. ArrayRef<llvm::Value*> args) {
  2719. if (getInvokeDest()) {
  2720. llvm::InvokeInst *invoke =
  2721. Builder.CreateInvoke(callee,
  2722. getUnreachableBlock(),
  2723. getInvokeDest(),
  2724. args);
  2725. invoke->setDoesNotReturn();
  2726. invoke->setCallingConv(getRuntimeCC());
  2727. } else {
  2728. llvm::CallInst *call = Builder.CreateCall(callee, args);
  2729. call->setDoesNotReturn();
  2730. call->setCallingConv(getRuntimeCC());
  2731. Builder.CreateUnreachable();
  2732. }
  2733. }
  2734. /// Emits a call or invoke instruction to the given nullary runtime
  2735. /// function.
  2736. llvm::CallSite
  2737. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2738. const Twine &name) {
  2739. return EmitRuntimeCallOrInvoke(callee, None, name);
  2740. }
  2741. /// Emits a call or invoke instruction to the given runtime function.
  2742. llvm::CallSite
  2743. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2744. ArrayRef<llvm::Value*> args,
  2745. const Twine &name) {
  2746. llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
  2747. callSite.setCallingConv(getRuntimeCC());
  2748. return callSite;
  2749. }
  2750. llvm::CallSite
  2751. CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
  2752. const Twine &Name) {
  2753. return EmitCallOrInvoke(Callee, None, Name);
  2754. }
  2755. /// Emits a call or invoke instruction to the given function, depending
  2756. /// on the current state of the EH stack.
  2757. llvm::CallSite
  2758. CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
  2759. ArrayRef<llvm::Value *> Args,
  2760. const Twine &Name) {
  2761. llvm::BasicBlock *InvokeDest = getInvokeDest();
  2762. llvm::Instruction *Inst;
  2763. if (!InvokeDest)
  2764. Inst = Builder.CreateCall(Callee, Args, Name);
  2765. else {
  2766. llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
  2767. Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
  2768. EmitBlock(ContBB);
  2769. }
  2770. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  2771. // optimizer it can aggressively ignore unwind edges.
  2772. if (CGM.getLangOpts().ObjCAutoRefCount)
  2773. AddObjCARCExceptionMetadata(Inst);
  2774. return llvm::CallSite(Inst);
  2775. }
  2776. /// \brief Store a non-aggregate value to an address to initialize it. For
  2777. /// initialization, a non-atomic store will be used.
  2778. static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
  2779. LValue Dst) {
  2780. if (Src.isScalar())
  2781. CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
  2782. else
  2783. CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
  2784. }
  2785. void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
  2786. llvm::Value *New) {
  2787. DeferredReplacements.push_back(std::make_pair(Old, New));
  2788. }
  2789. RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
  2790. llvm::Value *Callee,
  2791. ReturnValueSlot ReturnValue,
  2792. const CallArgList &CallArgs,
  2793. const Decl *TargetDecl,
  2794. llvm::Instruction **callOrInvoke) {
  2795. // FIXME: We no longer need the types from CallArgs; lift up and simplify.
  2796. // Handle struct-return functions by passing a pointer to the
  2797. // location that we would like to return into.
  2798. QualType RetTy = CallInfo.getReturnType();
  2799. const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
  2800. llvm::FunctionType *IRFuncTy =
  2801. cast<llvm::FunctionType>(
  2802. cast<llvm::PointerType>(Callee->getType())->getElementType());
  2803. // If we're using inalloca, insert the allocation after the stack save.
  2804. // FIXME: Do this earlier rather than hacking it in here!
  2805. llvm::AllocaInst *ArgMemory = nullptr;
  2806. if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
  2807. llvm::Instruction *IP = CallArgs.getStackBase();
  2808. llvm::AllocaInst *AI;
  2809. if (IP) {
  2810. IP = IP->getNextNode();
  2811. AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
  2812. } else {
  2813. AI = CreateTempAlloca(ArgStruct, "argmem");
  2814. }
  2815. AI->setUsedWithInAlloca(true);
  2816. assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
  2817. ArgMemory = AI;
  2818. }
  2819. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
  2820. SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
  2821. // If the call returns a temporary with struct return, create a temporary
  2822. // alloca to hold the result, unless one is given to us.
  2823. llvm::Value *SRetPtr = nullptr;
  2824. size_t UnusedReturnSize = 0;
  2825. if (RetAI.isIndirect() || RetAI.isInAlloca()) {
  2826. SRetPtr = ReturnValue.getValue();
  2827. if (!SRetPtr) {
  2828. SRetPtr = CreateMemTemp(RetTy);
  2829. if (HaveInsertPoint() && ReturnValue.isUnused()) {
  2830. uint64_t size =
  2831. CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
  2832. if (EmitLifetimeStart(size, SRetPtr))
  2833. UnusedReturnSize = size;
  2834. }
  2835. }
  2836. if (IRFunctionArgs.hasSRetArg()) {
  2837. IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
  2838. } else {
  2839. llvm::Value *Addr =
  2840. Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
  2841. RetAI.getInAllocaFieldIndex());
  2842. Builder.CreateStore(SRetPtr, Addr);
  2843. }
  2844. }
  2845. assert(CallInfo.arg_size() == CallArgs.size() &&
  2846. "Mismatch between function signature & arguments.");
  2847. unsigned ArgNo = 0;
  2848. CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
  2849. for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
  2850. I != E; ++I, ++info_it, ++ArgNo) {
  2851. const ABIArgInfo &ArgInfo = info_it->info;
  2852. RValue RV = I->RV;
  2853. CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
  2854. // Insert a padding argument to ensure proper alignment.
  2855. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  2856. IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  2857. llvm::UndefValue::get(ArgInfo.getPaddingType());
  2858. unsigned FirstIRArg, NumIRArgs;
  2859. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  2860. switch (ArgInfo.getKind()) {
  2861. case ABIArgInfo::InAlloca: {
  2862. assert(NumIRArgs == 0);
  2863. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2864. if (RV.isAggregate()) {
  2865. // Replace the placeholder with the appropriate argument slot GEP.
  2866. llvm::Instruction *Placeholder =
  2867. cast<llvm::Instruction>(RV.getAggregateAddr());
  2868. CGBuilderTy::InsertPoint IP = Builder.saveIP();
  2869. Builder.SetInsertPoint(Placeholder);
  2870. llvm::Value *Addr =
  2871. Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
  2872. ArgInfo.getInAllocaFieldIndex());
  2873. Builder.restoreIP(IP);
  2874. deferPlaceholderReplacement(Placeholder, Addr);
  2875. } else {
  2876. // Store the RValue into the argument struct.
  2877. llvm::Value *Addr =
  2878. Builder.CreateStructGEP(ArgMemory->getAllocatedType(), ArgMemory,
  2879. ArgInfo.getInAllocaFieldIndex());
  2880. unsigned AS = Addr->getType()->getPointerAddressSpace();
  2881. llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
  2882. // There are some cases where a trivial bitcast is not avoidable. The
  2883. // definition of a type later in a translation unit may change it's type
  2884. // from {}* to (%struct.foo*)*.
  2885. if (Addr->getType() != MemType)
  2886. Addr = Builder.CreateBitCast(Addr, MemType);
  2887. LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
  2888. EmitInitStoreOfNonAggregate(*this, RV, argLV);
  2889. }
  2890. break;
  2891. }
  2892. case ABIArgInfo::Indirect: {
  2893. assert(NumIRArgs == 1);
  2894. if (RV.isScalar() || RV.isComplex()) {
  2895. // Make a temporary alloca to pass the argument.
  2896. llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
  2897. if (ArgInfo.getIndirectAlign() > AI->getAlignment())
  2898. AI->setAlignment(ArgInfo.getIndirectAlign());
  2899. IRCallArgs[FirstIRArg] = AI;
  2900. LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
  2901. EmitInitStoreOfNonAggregate(*this, RV, argLV);
  2902. } else {
  2903. // We want to avoid creating an unnecessary temporary+copy here;
  2904. // however, we need one in three cases:
  2905. // 1. If the argument is not byval, and we are required to copy the
  2906. // source. (This case doesn't occur on any common architecture.)
  2907. // 2. If the argument is byval, RV is not sufficiently aligned, and
  2908. // we cannot force it to be sufficiently aligned.
  2909. // 3. If the argument is byval, but RV is located in an address space
  2910. // different than that of the argument (0).
  2911. llvm::Value *Addr = RV.getAggregateAddr();
  2912. unsigned Align = ArgInfo.getIndirectAlign();
  2913. const llvm::DataLayout *TD = &CGM.getDataLayout();
  2914. const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
  2915. const unsigned ArgAddrSpace =
  2916. (FirstIRArg < IRFuncTy->getNumParams()
  2917. ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
  2918. : 0);
  2919. if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
  2920. (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
  2921. llvm::getOrEnforceKnownAlignment(Addr, Align, *TD) < Align) ||
  2922. (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
  2923. // Create an aligned temporary, and copy to it.
  2924. llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
  2925. if (Align > AI->getAlignment())
  2926. AI->setAlignment(Align);
  2927. IRCallArgs[FirstIRArg] = AI;
  2928. EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
  2929. } else {
  2930. // Skip the extra memcpy call.
  2931. IRCallArgs[FirstIRArg] = Addr;
  2932. }
  2933. }
  2934. break;
  2935. }
  2936. case ABIArgInfo::Ignore:
  2937. assert(NumIRArgs == 0);
  2938. break;
  2939. case ABIArgInfo::Extend:
  2940. case ABIArgInfo::Direct: {
  2941. if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
  2942. ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
  2943. ArgInfo.getDirectOffset() == 0) {
  2944. assert(NumIRArgs == 1);
  2945. llvm::Value *V;
  2946. if (RV.isScalar())
  2947. V = RV.getScalarVal();
  2948. else
  2949. V = Builder.CreateLoad(RV.getAggregateAddr());
  2950. // We might have to widen integers, but we should never truncate.
  2951. if (ArgInfo.getCoerceToType() != V->getType() &&
  2952. V->getType()->isIntegerTy())
  2953. V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
  2954. // If the argument doesn't match, perform a bitcast to coerce it. This
  2955. // can happen due to trivial type mismatches.
  2956. if (FirstIRArg < IRFuncTy->getNumParams() &&
  2957. V->getType() != IRFuncTy->getParamType(FirstIRArg)) {
  2958. // HLSL Change Starts
  2959. // Generate AddrSpaceCast for shared memory.
  2960. if (V->getType()->isPointerTy())
  2961. V = Builder.CreatePointerBitCastOrAddrSpaceCast(
  2962. V, IRFuncTy->getParamType(FirstIRArg));
  2963. else
  2964. // HLSL Change Ends
  2965. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
  2966. }
  2967. IRCallArgs[FirstIRArg] = V;
  2968. break;
  2969. }
  2970. // HLSL Change Begins
  2971. if (hlsl::IsHLSLMatType(I->Ty)) {
  2972. // For matrix, just use the val directly
  2973. IRCallArgs[FirstIRArg] = RV.getScalarVal();
  2974. continue;
  2975. }
  2976. // HLSL Change Ends
  2977. // FIXME: Avoid the conversion through memory if possible.
  2978. llvm::Value *SrcPtr;
  2979. CharUnits SrcAlign;
  2980. if (RV.isScalar() || RV.isComplex()) {
  2981. SrcPtr = CreateMemTemp(I->Ty, "coerce");
  2982. SrcAlign = TypeAlign;
  2983. LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
  2984. EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
  2985. } else {
  2986. SrcPtr = RV.getAggregateAddr();
  2987. // This alignment is guaranteed by EmitCallArg.
  2988. SrcAlign = TypeAlign;
  2989. }
  2990. // If the value is offset in memory, apply the offset now.
  2991. if (unsigned Offs = ArgInfo.getDirectOffset()) {
  2992. SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
  2993. SrcPtr = Builder.CreateConstGEP1_32(Builder.getInt8Ty(), SrcPtr, Offs);
  2994. SrcPtr = Builder.CreateBitCast(SrcPtr,
  2995. llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
  2996. SrcAlign = SrcAlign.alignmentAtOffset(CharUnits::fromQuantity(Offs));
  2997. }
  2998. // Fast-isel and the optimizer generally like scalar values better than
  2999. // FCAs, so we flatten them if this is safe to do for this argument.
  3000. llvm::StructType *STy =
  3001. dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
  3002. if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  3003. llvm::Type *SrcTy =
  3004. cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
  3005. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3006. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
  3007. // If the source type is smaller than the destination type of the
  3008. // coerce-to logic, copy the source value into a temp alloca the size
  3009. // of the destination type to allow loading all of it. The bits past
  3010. // the source value are left undef.
  3011. if (SrcSize < DstSize) {
  3012. llvm::AllocaInst *TempAlloca
  3013. = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
  3014. Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
  3015. SrcPtr = TempAlloca;
  3016. } else {
  3017. SrcPtr = Builder.CreateBitCast(SrcPtr,
  3018. llvm::PointerType::getUnqual(STy));
  3019. }
  3020. assert(NumIRArgs == STy->getNumElements());
  3021. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  3022. llvm::Value *EltPtr = Builder.CreateConstGEP2_32(STy, SrcPtr, 0, i);
  3023. llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
  3024. // We don't know what we're loading from.
  3025. LI->setAlignment(1);
  3026. IRCallArgs[FirstIRArg + i] = LI;
  3027. }
  3028. } else {
  3029. // In the simple case, just pass the coerced loaded value.
  3030. assert(NumIRArgs == 1);
  3031. IRCallArgs[FirstIRArg] =
  3032. CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
  3033. SrcAlign, *this);
  3034. }
  3035. break;
  3036. }
  3037. case ABIArgInfo::Expand:
  3038. unsigned IRArgPos = FirstIRArg;
  3039. ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
  3040. assert(IRArgPos == FirstIRArg + NumIRArgs);
  3041. break;
  3042. }
  3043. }
  3044. if (ArgMemory) {
  3045. llvm::Value *Arg = ArgMemory;
  3046. if (CallInfo.isVariadic()) {
  3047. // When passing non-POD arguments by value to variadic functions, we will
  3048. // end up with a variadic prototype and an inalloca call site. In such
  3049. // cases, we can't do any parameter mismatch checks. Give up and bitcast
  3050. // the callee.
  3051. unsigned CalleeAS =
  3052. cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
  3053. Callee = Builder.CreateBitCast(
  3054. Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
  3055. } else {
  3056. llvm::Type *LastParamTy =
  3057. IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
  3058. if (Arg->getType() != LastParamTy) {
  3059. #ifndef NDEBUG
  3060. // Assert that these structs have equivalent element types.
  3061. llvm::StructType *FullTy = CallInfo.getArgStruct();
  3062. llvm::StructType *DeclaredTy = cast<llvm::StructType>(
  3063. cast<llvm::PointerType>(LastParamTy)->getElementType());
  3064. assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
  3065. for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
  3066. DE = DeclaredTy->element_end(),
  3067. FI = FullTy->element_begin();
  3068. DI != DE; ++DI, ++FI)
  3069. assert(*DI == *FI);
  3070. #endif
  3071. Arg = Builder.CreateBitCast(Arg, LastParamTy);
  3072. }
  3073. }
  3074. assert(IRFunctionArgs.hasInallocaArg());
  3075. IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
  3076. }
  3077. if (!CallArgs.getCleanupsToDeactivate().empty())
  3078. deactivateArgCleanupsBeforeCall(*this, CallArgs);
  3079. // If the callee is a bitcast of a function to a varargs pointer to function
  3080. // type, check to see if we can remove the bitcast. This handles some cases
  3081. // with unprototyped functions.
  3082. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
  3083. if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
  3084. llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
  3085. llvm::FunctionType *CurFT =
  3086. cast<llvm::FunctionType>(CurPT->getElementType());
  3087. llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
  3088. if (CE->getOpcode() == llvm::Instruction::BitCast &&
  3089. ActualFT->getReturnType() == CurFT->getReturnType() &&
  3090. ActualFT->getNumParams() == CurFT->getNumParams() &&
  3091. ActualFT->getNumParams() == IRCallArgs.size() &&
  3092. (CurFT->isVarArg() || !ActualFT->isVarArg())) {
  3093. bool ArgsMatch = true;
  3094. for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
  3095. if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
  3096. ArgsMatch = false;
  3097. break;
  3098. }
  3099. // Strip the cast if we can get away with it. This is a nice cleanup,
  3100. // but also allows us to inline the function at -O0 if it is marked
  3101. // always_inline.
  3102. if (ArgsMatch)
  3103. Callee = CalleeF;
  3104. }
  3105. }
  3106. assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
  3107. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  3108. // Inalloca argument can have different type.
  3109. if (IRFunctionArgs.hasInallocaArg() &&
  3110. i == IRFunctionArgs.getInallocaArgNo())
  3111. continue;
  3112. if (i < IRFuncTy->getNumParams())
  3113. assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
  3114. }
  3115. unsigned CallingConv;
  3116. CodeGen::AttributeListType AttributeList;
  3117. CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
  3118. CallingConv, true);
  3119. llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
  3120. AttributeList);
  3121. llvm::BasicBlock *InvokeDest = nullptr;
  3122. if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
  3123. llvm::Attribute::NoUnwind) ||
  3124. currentFunctionUsesSEHTry())
  3125. InvokeDest = getInvokeDest();
  3126. llvm::CallSite CS;
  3127. if (!InvokeDest) {
  3128. CS = Builder.CreateCall(Callee, IRCallArgs);
  3129. } else {
  3130. llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
  3131. CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
  3132. EmitBlock(Cont);
  3133. }
  3134. if (callOrInvoke)
  3135. *callOrInvoke = CS.getInstruction();
  3136. if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
  3137. !CS.hasFnAttr(llvm::Attribute::NoInline))
  3138. Attrs =
  3139. Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
  3140. llvm::Attribute::AlwaysInline);
  3141. // Disable inlining inside SEH __try blocks.
  3142. if (isSEHTryScope())
  3143. Attrs =
  3144. Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
  3145. llvm::Attribute::NoInline);
  3146. CS.setAttributes(Attrs);
  3147. CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  3148. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3149. // optimizer it can aggressively ignore unwind edges.
  3150. if (CGM.getLangOpts().ObjCAutoRefCount)
  3151. AddObjCARCExceptionMetadata(CS.getInstruction());
  3152. // If the call doesn't return, finish the basic block and clear the
  3153. // insertion point; this allows the rest of IRgen to discard
  3154. // unreachable code.
  3155. if (CS.doesNotReturn()) {
  3156. if (UnusedReturnSize)
  3157. EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
  3158. SRetPtr);
  3159. Builder.CreateUnreachable();
  3160. Builder.ClearInsertionPoint();
  3161. // FIXME: For now, emit a dummy basic block because expr emitters in
  3162. // generally are not ready to handle emitting expressions at unreachable
  3163. // points.
  3164. EnsureInsertPoint();
  3165. // Return a reasonable RValue.
  3166. return GetUndefRValue(RetTy);
  3167. }
  3168. llvm::Instruction *CI = CS.getInstruction();
  3169. if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
  3170. CI->setName("call");
  3171. #if 0 // HLSL Change - no ObjC support
  3172. // Emit any writebacks immediately. Arguably this should happen
  3173. // after any return-value munging.
  3174. if (CallArgs.hasWritebacks())
  3175. emitWritebacks(*this, CallArgs);
  3176. #else
  3177. assert(!CallArgs.hasWritebacks() && "writebacks are unavailable in HLSL");
  3178. #endif // HLSL Change - no ObjC support
  3179. // The stack cleanup for inalloca arguments has to run out of the normal
  3180. // lexical order, so deactivate it and run it manually here.
  3181. CallArgs.freeArgumentMemory(*this);
  3182. RValue Ret = [&] {
  3183. switch (RetAI.getKind()) {
  3184. case ABIArgInfo::InAlloca:
  3185. case ABIArgInfo::Indirect: {
  3186. RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
  3187. if (UnusedReturnSize)
  3188. EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
  3189. SRetPtr);
  3190. return ret;
  3191. }
  3192. case ABIArgInfo::Ignore:
  3193. // If we are ignoring an argument that had a result, make sure to
  3194. // construct the appropriate return value for our caller.
  3195. return GetUndefRValue(RetTy);
  3196. case ABIArgInfo::Extend:
  3197. case ABIArgInfo::Direct: {
  3198. llvm::Type *RetIRTy = ConvertType(RetTy);
  3199. if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
  3200. switch (getEvaluationKind(RetTy)) {
  3201. case TEK_Complex: {
  3202. llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
  3203. llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
  3204. return RValue::getComplex(std::make_pair(Real, Imag));
  3205. }
  3206. case TEK_Aggregate: {
  3207. llvm::Value *DestPtr = ReturnValue.getValue();
  3208. bool DestIsVolatile = ReturnValue.isVolatile();
  3209. CharUnits DestAlign = getContext().getTypeAlignInChars(RetTy);
  3210. if (!DestPtr) {
  3211. DestPtr = CreateMemTemp(RetTy, "agg.tmp");
  3212. DestIsVolatile = false;
  3213. }
  3214. BuildAggStore(*this, CI, DestPtr, DestIsVolatile, DestAlign, RetTy); // HLSL Change - Add QualTy.
  3215. return RValue::getAggregate(DestPtr);
  3216. }
  3217. case TEK_Scalar: {
  3218. // If the argument doesn't match, perform a bitcast to coerce it. This
  3219. // can happen due to trivial type mismatches.
  3220. llvm::Value *V = CI;
  3221. if (V->getType() != RetIRTy)
  3222. V = Builder.CreateBitCast(V, RetIRTy);
  3223. return RValue::get(V);
  3224. }
  3225. }
  3226. llvm_unreachable("bad evaluation kind");
  3227. }
  3228. llvm::Value *DestPtr = ReturnValue.getValue();
  3229. bool DestIsVolatile = ReturnValue.isVolatile();
  3230. CharUnits DestAlign = getContext().getTypeAlignInChars(RetTy);
  3231. if (!DestPtr) {
  3232. DestPtr = CreateMemTemp(RetTy, "coerce");
  3233. DestIsVolatile = false;
  3234. }
  3235. // If the value is offset in memory, apply the offset now.
  3236. llvm::Value *StorePtr = DestPtr;
  3237. CharUnits StoreAlign = DestAlign;
  3238. if (unsigned Offs = RetAI.getDirectOffset()) {
  3239. StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
  3240. StorePtr =
  3241. Builder.CreateConstGEP1_32(Builder.getInt8Ty(), StorePtr, Offs);
  3242. StorePtr = Builder.CreateBitCast(StorePtr,
  3243. llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
  3244. StoreAlign =
  3245. StoreAlign.alignmentAtOffset(CharUnits::fromQuantity(Offs));
  3246. }
  3247. CreateCoercedStore(CI, StorePtr, DestIsVolatile, StoreAlign, *this, RetTy); // HLSL Change - Add QTy.
  3248. return convertTempToRValue(DestPtr, RetTy, SourceLocation());
  3249. }
  3250. case ABIArgInfo::Expand:
  3251. llvm_unreachable("Invalid ABI kind for return argument");
  3252. }
  3253. llvm_unreachable("Unhandled ABIArgInfo::Kind");
  3254. } ();
  3255. if (Ret.isScalar() && TargetDecl) {
  3256. if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
  3257. llvm::Value *OffsetValue = nullptr;
  3258. if (const auto *Offset = AA->getOffset())
  3259. OffsetValue = EmitScalarExpr(Offset);
  3260. llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
  3261. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
  3262. EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
  3263. OffsetValue);
  3264. }
  3265. }
  3266. return Ret;
  3267. }
  3268. /* VarArg handling */
  3269. llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
  3270. return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
  3271. }