CGCall.cpp 168 KB

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