CGCall.cpp 165 KB

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