CGCall.cpp 172 KB

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