CodeGenModule.cpp 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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. // This coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "CodeGenTBAA.h"
  26. #include "ConstantBuilder.h"
  27. #include "CoverageMappingGen.h"
  28. #include "TargetInfo.h"
  29. #include "clang/AST/ASTContext.h"
  30. #include "clang/AST/CharUnits.h"
  31. #include "clang/AST/DeclCXX.h"
  32. #include "clang/AST/DeclObjC.h"
  33. #include "clang/AST/DeclTemplate.h"
  34. #include "clang/AST/Mangle.h"
  35. #include "clang/AST/RecordLayout.h"
  36. #include "clang/AST/RecursiveASTVisitor.h"
  37. #include "clang/Basic/Builtins.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/Module.h"
  41. #include "clang/Basic/SourceManager.h"
  42. #include "clang/Basic/TargetInfo.h"
  43. #include "clang/Basic/Version.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/IR/CallSite.h"
  48. #include "llvm/IR/CallingConv.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/Intrinsics.h"
  51. #include "llvm/IR/LLVMContext.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/ProfileData/InstrProfReader.h"
  54. #include "llvm/Support/ConvertUTF.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/MD5.h"
  57. using namespace clang;
  58. using namespace CodeGen;
  59. static const char AnnotationSection[] = "llvm.metadata";
  60. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  61. switch (CGM.getTarget().getCXXABI().getKind()) {
  62. case TargetCXXABI::GenericAArch64:
  63. case TargetCXXABI::GenericARM:
  64. case TargetCXXABI::iOS:
  65. case TargetCXXABI::iOS64:
  66. case TargetCXXABI::WatchOS:
  67. case TargetCXXABI::GenericMIPS:
  68. case TargetCXXABI::GenericItanium:
  69. case TargetCXXABI::WebAssembly:
  70. return CreateItaniumCXXABI(CGM);
  71. case TargetCXXABI::Microsoft:
  72. return CreateMicrosoftCXXABI(CGM);
  73. }
  74. llvm_unreachable("invalid C++ ABI kind");
  75. }
  76. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  77. const PreprocessorOptions &PPO,
  78. const CodeGenOptions &CGO, llvm::Module &M,
  79. DiagnosticsEngine &diags,
  80. CoverageSourceInfo *CoverageInfo)
  81. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  82. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  83. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  84. VMContext(M.getContext()), Types(*this), VTables(*this),
  85. SanitizerMD(new SanitizerMetadata(*this)) {
  86. // Initialize the type cache.
  87. llvm::LLVMContext &LLVMContext = M.getContext();
  88. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  89. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  90. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  91. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  92. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  93. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  94. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  95. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  96. PointerAlignInBytes =
  97. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  98. SizeSizeInBytes =
  99. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  100. IntAlignInBytes =
  101. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  102. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  103. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  104. C.getTargetInfo().getMaxPointerWidth());
  105. Int8PtrTy = Int8Ty->getPointerTo(0);
  106. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  107. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  108. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  109. if (LangOpts.ObjC1)
  110. createObjCRuntime();
  111. if (LangOpts.OpenCL)
  112. createOpenCLRuntime();
  113. if (LangOpts.OpenMP)
  114. createOpenMPRuntime();
  115. if (LangOpts.CUDA)
  116. createCUDARuntime();
  117. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  118. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  119. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  120. TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  121. getCXXABI().getMangleContext()));
  122. // If debug info or coverage generation is enabled, create the CGDebugInfo
  123. // object.
  124. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  125. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  126. DebugInfo.reset(new CGDebugInfo(*this));
  127. Block.GlobalUniqueCount = 0;
  128. if (C.getLangOpts().ObjC1)
  129. ObjCData.reset(new ObjCEntrypoints());
  130. if (CodeGenOpts.hasProfileClangUse()) {
  131. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  132. CodeGenOpts.ProfileInstrumentUsePath);
  133. if (auto E = ReaderOrErr.takeError()) {
  134. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  135. "Could not read profile %0: %1");
  136. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  137. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  138. << EI.message();
  139. });
  140. } else
  141. PGOReader = std::move(ReaderOrErr.get());
  142. }
  143. // If coverage mapping generation is enabled, create the
  144. // CoverageMappingModuleGen object.
  145. if (CodeGenOpts.CoverageMapping)
  146. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  147. }
  148. CodeGenModule::~CodeGenModule() {}
  149. void CodeGenModule::createObjCRuntime() {
  150. // This is just isGNUFamily(), but we want to force implementors of
  151. // new ABIs to decide how best to do this.
  152. switch (LangOpts.ObjCRuntime.getKind()) {
  153. case ObjCRuntime::GNUstep:
  154. case ObjCRuntime::GCC:
  155. case ObjCRuntime::ObjFW:
  156. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  157. return;
  158. case ObjCRuntime::FragileMacOSX:
  159. case ObjCRuntime::MacOSX:
  160. case ObjCRuntime::iOS:
  161. case ObjCRuntime::WatchOS:
  162. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  163. return;
  164. }
  165. llvm_unreachable("bad runtime kind");
  166. }
  167. void CodeGenModule::createOpenCLRuntime() {
  168. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  169. }
  170. void CodeGenModule::createOpenMPRuntime() {
  171. // Select a specialized code generation class based on the target, if any.
  172. // If it does not exist use the default implementation.
  173. switch (getTriple().getArch()) {
  174. case llvm::Triple::nvptx:
  175. case llvm::Triple::nvptx64:
  176. assert(getLangOpts().OpenMPIsDevice &&
  177. "OpenMP NVPTX is only prepared to deal with device code.");
  178. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  179. break;
  180. default:
  181. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  182. break;
  183. }
  184. }
  185. void CodeGenModule::createCUDARuntime() {
  186. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  187. }
  188. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  189. Replacements[Name] = C;
  190. }
  191. void CodeGenModule::applyReplacements() {
  192. for (auto &I : Replacements) {
  193. StringRef MangledName = I.first();
  194. llvm::Constant *Replacement = I.second;
  195. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  196. if (!Entry)
  197. continue;
  198. auto *OldF = cast<llvm::Function>(Entry);
  199. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  200. if (!NewF) {
  201. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  202. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  203. } else {
  204. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  205. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  206. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  207. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  208. }
  209. }
  210. // Replace old with new, but keep the old order.
  211. OldF->replaceAllUsesWith(Replacement);
  212. if (NewF) {
  213. NewF->removeFromParent();
  214. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  215. NewF);
  216. }
  217. OldF->eraseFromParent();
  218. }
  219. }
  220. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  221. GlobalValReplacements.push_back(std::make_pair(GV, C));
  222. }
  223. void CodeGenModule::applyGlobalValReplacements() {
  224. for (auto &I : GlobalValReplacements) {
  225. llvm::GlobalValue *GV = I.first;
  226. llvm::Constant *C = I.second;
  227. GV->replaceAllUsesWith(C);
  228. GV->eraseFromParent();
  229. }
  230. }
  231. // This is only used in aliases that we created and we know they have a
  232. // linear structure.
  233. static const llvm::GlobalObject *getAliasedGlobal(
  234. const llvm::GlobalIndirectSymbol &GIS) {
  235. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  236. const llvm::Constant *C = &GIS;
  237. for (;;) {
  238. C = C->stripPointerCasts();
  239. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  240. return GO;
  241. // stripPointerCasts will not walk over weak aliases.
  242. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  243. if (!GIS2)
  244. return nullptr;
  245. if (!Visited.insert(GIS2).second)
  246. return nullptr;
  247. C = GIS2->getIndirectSymbol();
  248. }
  249. }
  250. void CodeGenModule::checkAliases() {
  251. // Check if the constructed aliases are well formed. It is really unfortunate
  252. // that we have to do this in CodeGen, but we only construct mangled names
  253. // and aliases during codegen.
  254. bool Error = false;
  255. DiagnosticsEngine &Diags = getDiags();
  256. for (const GlobalDecl &GD : Aliases) {
  257. const auto *D = cast<ValueDecl>(GD.getDecl());
  258. SourceLocation Location;
  259. bool IsIFunc = D->hasAttr<IFuncAttr>();
  260. if (const Attr *A = D->getDefiningAttr())
  261. Location = A->getLocation();
  262. else
  263. llvm_unreachable("Not an alias or ifunc?");
  264. StringRef MangledName = getMangledName(GD);
  265. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  266. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  267. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  268. if (!GV) {
  269. Error = true;
  270. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  271. } else if (GV->isDeclaration()) {
  272. Error = true;
  273. Diags.Report(Location, diag::err_alias_to_undefined)
  274. << IsIFunc << IsIFunc;
  275. } else if (IsIFunc) {
  276. // Check resolver function type.
  277. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  278. GV->getType()->getPointerElementType());
  279. assert(FTy);
  280. if (!FTy->getReturnType()->isPointerTy())
  281. Diags.Report(Location, diag::err_ifunc_resolver_return);
  282. if (FTy->getNumParams())
  283. Diags.Report(Location, diag::err_ifunc_resolver_params);
  284. }
  285. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  286. llvm::GlobalValue *AliaseeGV;
  287. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  288. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  289. else
  290. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  291. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  292. StringRef AliasSection = SA->getName();
  293. if (AliasSection != AliaseeGV->getSection())
  294. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  295. << AliasSection << IsIFunc << IsIFunc;
  296. }
  297. // We have to handle alias to weak aliases in here. LLVM itself disallows
  298. // this since the object semantics would not match the IL one. For
  299. // compatibility with gcc we implement it by just pointing the alias
  300. // to its aliasee's aliasee. We also warn, since the user is probably
  301. // expecting the link to be weak.
  302. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  303. if (GA->isInterposable()) {
  304. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  305. << GV->getName() << GA->getName() << IsIFunc;
  306. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  307. GA->getIndirectSymbol(), Alias->getType());
  308. Alias->setIndirectSymbol(Aliasee);
  309. }
  310. }
  311. }
  312. if (!Error)
  313. return;
  314. for (const GlobalDecl &GD : Aliases) {
  315. StringRef MangledName = getMangledName(GD);
  316. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  317. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  318. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  319. Alias->eraseFromParent();
  320. }
  321. }
  322. void CodeGenModule::clear() {
  323. DeferredDeclsToEmit.clear();
  324. if (OpenMPRuntime)
  325. OpenMPRuntime->clear();
  326. }
  327. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  328. StringRef MainFile) {
  329. if (!hasDiagnostics())
  330. return;
  331. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  332. if (MainFile.empty())
  333. MainFile = "<stdin>";
  334. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  335. } else
  336. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  337. << Mismatched;
  338. }
  339. void CodeGenModule::Release() {
  340. EmitDeferred();
  341. applyGlobalValReplacements();
  342. applyReplacements();
  343. checkAliases();
  344. EmitCXXGlobalInitFunc();
  345. EmitCXXGlobalDtorFunc();
  346. EmitCXXThreadLocalInitFunc();
  347. if (ObjCRuntime)
  348. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  349. AddGlobalCtor(ObjCInitFunction);
  350. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  351. CUDARuntime) {
  352. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  353. AddGlobalCtor(CudaCtorFunction);
  354. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  355. AddGlobalDtor(CudaDtorFunction);
  356. }
  357. if (OpenMPRuntime)
  358. if (llvm::Function *OpenMPRegistrationFunction =
  359. OpenMPRuntime->emitRegistrationFunction())
  360. AddGlobalCtor(OpenMPRegistrationFunction, 0);
  361. if (PGOReader) {
  362. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  363. if (PGOStats.hasDiagnostics())
  364. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  365. }
  366. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  367. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  368. EmitGlobalAnnotations();
  369. EmitStaticExternCAliases();
  370. EmitDeferredUnusedCoverageMappings();
  371. if (CoverageMapping)
  372. CoverageMapping->emit();
  373. if (CodeGenOpts.SanitizeCfiCrossDso)
  374. CodeGenFunction(*this).EmitCfiCheckFail();
  375. emitLLVMUsed();
  376. if (SanStats)
  377. SanStats->finish();
  378. if (CodeGenOpts.Autolink &&
  379. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  380. EmitModuleLinkOptions();
  381. }
  382. if (CodeGenOpts.DwarfVersion) {
  383. // We actually want the latest version when there are conflicts.
  384. // We can change from Warning to Latest if such mode is supported.
  385. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  386. CodeGenOpts.DwarfVersion);
  387. }
  388. if (CodeGenOpts.EmitCodeView) {
  389. // Indicate that we want CodeView in the metadata.
  390. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  391. }
  392. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  393. // We don't support LTO with 2 with different StrictVTablePointers
  394. // FIXME: we could support it by stripping all the information introduced
  395. // by StrictVTablePointers.
  396. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  397. llvm::Metadata *Ops[2] = {
  398. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  399. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  400. llvm::Type::getInt32Ty(VMContext), 1))};
  401. getModule().addModuleFlag(llvm::Module::Require,
  402. "StrictVTablePointersRequirement",
  403. llvm::MDNode::get(VMContext, Ops));
  404. }
  405. if (DebugInfo)
  406. // We support a single version in the linked module. The LLVM
  407. // parser will drop debug info with a different version number
  408. // (and warn about it, too).
  409. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  410. llvm::DEBUG_METADATA_VERSION);
  411. // We need to record the widths of enums and wchar_t, so that we can generate
  412. // the correct build attributes in the ARM backend.
  413. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  414. if ( Arch == llvm::Triple::arm
  415. || Arch == llvm::Triple::armeb
  416. || Arch == llvm::Triple::thumb
  417. || Arch == llvm::Triple::thumbeb) {
  418. // Width of wchar_t in bytes
  419. uint64_t WCharWidth =
  420. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  421. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  422. // The minimum width of an enum in bytes
  423. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  424. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  425. }
  426. if (CodeGenOpts.SanitizeCfiCrossDso) {
  427. // Indicate that we want cross-DSO control flow integrity checks.
  428. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  429. }
  430. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  431. // Indicate whether __nvvm_reflect should be configured to flush denormal
  432. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  433. // property.)
  434. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  435. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  436. }
  437. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  438. assert(PLevel < 3 && "Invalid PIC Level");
  439. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  440. if (Context.getLangOpts().PIE)
  441. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  442. }
  443. SimplifyPersonality();
  444. if (getCodeGenOpts().EmitDeclMetadata)
  445. EmitDeclMetadata();
  446. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  447. EmitCoverageFile();
  448. if (DebugInfo)
  449. DebugInfo->finalize();
  450. EmitVersionIdentMetadata();
  451. EmitTargetMetadata();
  452. }
  453. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  454. // Make sure that this type is translated.
  455. Types.UpdateCompletedType(TD);
  456. }
  457. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  458. // Make sure that this type is translated.
  459. Types.RefreshTypeCacheForClass(RD);
  460. }
  461. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  462. if (!TBAA)
  463. return nullptr;
  464. return TBAA->getTBAAInfo(QTy);
  465. }
  466. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  467. if (!TBAA)
  468. return nullptr;
  469. return TBAA->getTBAAInfoForVTablePtr();
  470. }
  471. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  472. if (!TBAA)
  473. return nullptr;
  474. return TBAA->getTBAAStructInfo(QTy);
  475. }
  476. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  477. llvm::MDNode *AccessN,
  478. uint64_t O) {
  479. if (!TBAA)
  480. return nullptr;
  481. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  482. }
  483. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  484. /// and struct-path aware TBAA, the tag has the same format:
  485. /// base type, access type and offset.
  486. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  487. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  488. llvm::MDNode *TBAAInfo,
  489. bool ConvertTypeToTag) {
  490. if (ConvertTypeToTag && TBAA)
  491. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  492. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  493. else
  494. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  495. }
  496. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  497. llvm::Instruction *I, const CXXRecordDecl *RD) {
  498. llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  499. auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
  500. // Check if we have to wrap MDString in MDNode.
  501. if (!MetaDataNode)
  502. MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
  503. I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
  504. }
  505. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  506. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  507. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  508. }
  509. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  510. /// specified stmt yet.
  511. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  512. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  513. "cannot compile this %0 yet");
  514. std::string Msg = Type;
  515. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  516. << Msg << S->getSourceRange();
  517. }
  518. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  519. /// specified decl yet.
  520. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  521. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  522. "cannot compile this %0 yet");
  523. std::string Msg = Type;
  524. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  525. }
  526. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  527. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  528. }
  529. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  530. const NamedDecl *D) const {
  531. // Internal definitions always have default visibility.
  532. if (GV->hasLocalLinkage()) {
  533. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  534. return;
  535. }
  536. // Set visibility for definitions.
  537. LinkageInfo LV = D->getLinkageAndVisibility();
  538. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  539. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  540. }
  541. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  542. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  543. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  544. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  545. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  546. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  547. }
  548. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  549. CodeGenOptions::TLSModel M) {
  550. switch (M) {
  551. case CodeGenOptions::GeneralDynamicTLSModel:
  552. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  553. case CodeGenOptions::LocalDynamicTLSModel:
  554. return llvm::GlobalVariable::LocalDynamicTLSModel;
  555. case CodeGenOptions::InitialExecTLSModel:
  556. return llvm::GlobalVariable::InitialExecTLSModel;
  557. case CodeGenOptions::LocalExecTLSModel:
  558. return llvm::GlobalVariable::LocalExecTLSModel;
  559. }
  560. llvm_unreachable("Invalid TLS model!");
  561. }
  562. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  563. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  564. llvm::GlobalValue::ThreadLocalMode TLM;
  565. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  566. // Override the TLS model if it is explicitly specified.
  567. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  568. TLM = GetLLVMTLSModel(Attr->getModel());
  569. }
  570. GV->setThreadLocalMode(TLM);
  571. }
  572. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  573. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  574. // Some ABIs don't have constructor variants. Make sure that base and
  575. // complete constructors get mangled the same.
  576. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  577. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  578. CXXCtorType OrigCtorType = GD.getCtorType();
  579. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  580. if (OrigCtorType == Ctor_Base)
  581. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  582. }
  583. }
  584. StringRef &FoundStr = MangledDeclNames[CanonicalGD];
  585. if (!FoundStr.empty())
  586. return FoundStr;
  587. const auto *ND = cast<NamedDecl>(GD.getDecl());
  588. SmallString<256> Buffer;
  589. StringRef Str;
  590. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  591. llvm::raw_svector_ostream Out(Buffer);
  592. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  593. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  594. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  595. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  596. else
  597. getCXXABI().getMangleContext().mangleName(ND, Out);
  598. Str = Out.str();
  599. } else {
  600. IdentifierInfo *II = ND->getIdentifier();
  601. assert(II && "Attempt to mangle unnamed decl.");
  602. const auto *FD = dyn_cast<FunctionDecl>(ND);
  603. if (FD &&
  604. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  605. llvm::raw_svector_ostream Out(Buffer);
  606. Out << "__regcall3__" << II->getName();
  607. Str = Out.str();
  608. } else {
  609. Str = II->getName();
  610. }
  611. }
  612. // Keep the first result in the case of a mangling collision.
  613. auto Result = Manglings.insert(std::make_pair(Str, GD));
  614. return FoundStr = Result.first->first();
  615. }
  616. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  617. const BlockDecl *BD) {
  618. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  619. const Decl *D = GD.getDecl();
  620. SmallString<256> Buffer;
  621. llvm::raw_svector_ostream Out(Buffer);
  622. if (!D)
  623. MangleCtx.mangleGlobalBlock(BD,
  624. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  625. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  626. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  627. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  628. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  629. else
  630. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  631. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  632. return Result.first->first();
  633. }
  634. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  635. return getModule().getNamedValue(Name);
  636. }
  637. /// AddGlobalCtor - Add a function to the list that will be called before
  638. /// main() runs.
  639. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  640. llvm::Constant *AssociatedData) {
  641. // FIXME: Type coercion of void()* types.
  642. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  643. }
  644. /// AddGlobalDtor - Add a function to the list that will be called
  645. /// when the module is unloaded.
  646. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  647. // FIXME: Type coercion of void()* types.
  648. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  649. }
  650. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  651. if (Fns.empty()) return;
  652. // Ctor function type is void()*.
  653. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  654. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  655. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  656. llvm::StructType *CtorStructTy = llvm::StructType::get(
  657. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  658. // Construct the constructor and destructor arrays.
  659. ConstantInitBuilder builder(*this);
  660. auto ctors = builder.beginArray(CtorStructTy);
  661. for (const auto &I : Fns) {
  662. auto ctor = ctors.beginStruct(CtorStructTy);
  663. ctor.addInt(Int32Ty, I.Priority);
  664. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  665. if (I.AssociatedData)
  666. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  667. else
  668. ctor.addNullPointer(VoidPtrTy);
  669. ctor.finishAndAddTo(ctors);
  670. }
  671. auto list =
  672. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  673. /*constant*/ false,
  674. llvm::GlobalValue::AppendingLinkage);
  675. // The LTO linker doesn't seem to like it when we set an alignment
  676. // on appending variables. Take it off as a workaround.
  677. list->setAlignment(0);
  678. Fns.clear();
  679. }
  680. llvm::GlobalValue::LinkageTypes
  681. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  682. const auto *D = cast<FunctionDecl>(GD.getDecl());
  683. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  684. if (isa<CXXDestructorDecl>(D) &&
  685. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  686. GD.getDtorType())) {
  687. // Destructor variants in the Microsoft C++ ABI are always internal or
  688. // linkonce_odr thunks emitted on an as-needed basis.
  689. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  690. : llvm::GlobalValue::LinkOnceODRLinkage;
  691. }
  692. if (isa<CXXConstructorDecl>(D) &&
  693. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  694. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  695. // Our approach to inheriting constructors is fundamentally different from
  696. // that used by the MS ABI, so keep our inheriting constructor thunks
  697. // internal rather than trying to pick an unambiguous mangling for them.
  698. return llvm::GlobalValue::InternalLinkage;
  699. }
  700. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  701. }
  702. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  703. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  704. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  705. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  706. // Don't dllexport/import destructor thunks.
  707. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  708. return;
  709. }
  710. }
  711. if (FD->hasAttr<DLLImportAttr>())
  712. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  713. else if (FD->hasAttr<DLLExportAttr>())
  714. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  715. else
  716. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  717. }
  718. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  719. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  720. if (!MDS) return nullptr;
  721. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  722. }
  723. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  724. llvm::Function *F) {
  725. setNonAliasAttributes(D, F);
  726. }
  727. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  728. const CGFunctionInfo &Info,
  729. llvm::Function *F) {
  730. unsigned CallingConv;
  731. AttributeListType AttributeList;
  732. ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
  733. false);
  734. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  735. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  736. }
  737. /// Determines whether the language options require us to model
  738. /// unwind exceptions. We treat -fexceptions as mandating this
  739. /// except under the fragile ObjC ABI with only ObjC exceptions
  740. /// enabled. This means, for example, that C with -fexceptions
  741. /// enables this.
  742. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  743. // If exceptions are completely disabled, obviously this is false.
  744. if (!LangOpts.Exceptions) return false;
  745. // If C++ exceptions are enabled, this is true.
  746. if (LangOpts.CXXExceptions) return true;
  747. // If ObjC exceptions are enabled, this depends on the ABI.
  748. if (LangOpts.ObjCExceptions) {
  749. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  750. }
  751. return true;
  752. }
  753. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  754. llvm::Function *F) {
  755. llvm::AttrBuilder B;
  756. if (CodeGenOpts.UnwindTables)
  757. B.addAttribute(llvm::Attribute::UWTable);
  758. if (!hasUnwindExceptions(LangOpts))
  759. B.addAttribute(llvm::Attribute::NoUnwind);
  760. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  761. B.addAttribute(llvm::Attribute::StackProtect);
  762. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  763. B.addAttribute(llvm::Attribute::StackProtectStrong);
  764. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  765. B.addAttribute(llvm::Attribute::StackProtectReq);
  766. if (!D) {
  767. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  768. llvm::AttributeSet::get(
  769. F->getContext(),
  770. llvm::AttributeSet::FunctionIndex, B));
  771. return;
  772. }
  773. if (D->hasAttr<NakedAttr>()) {
  774. // Naked implies noinline: we should not be inlining such functions.
  775. B.addAttribute(llvm::Attribute::Naked);
  776. B.addAttribute(llvm::Attribute::NoInline);
  777. } else if (D->hasAttr<NoDuplicateAttr>()) {
  778. B.addAttribute(llvm::Attribute::NoDuplicate);
  779. } else if (D->hasAttr<NoInlineAttr>()) {
  780. B.addAttribute(llvm::Attribute::NoInline);
  781. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  782. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  783. llvm::Attribute::NoInline)) {
  784. // (noinline wins over always_inline, and we can't specify both in IR)
  785. B.addAttribute(llvm::Attribute::AlwaysInline);
  786. }
  787. if (D->hasAttr<ColdAttr>()) {
  788. if (!D->hasAttr<OptimizeNoneAttr>())
  789. B.addAttribute(llvm::Attribute::OptimizeForSize);
  790. B.addAttribute(llvm::Attribute::Cold);
  791. }
  792. if (D->hasAttr<MinSizeAttr>())
  793. B.addAttribute(llvm::Attribute::MinSize);
  794. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  795. llvm::AttributeSet::get(
  796. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  797. if (D->hasAttr<OptimizeNoneAttr>()) {
  798. // OptimizeNone implies noinline; we should not be inlining such functions.
  799. F->addFnAttr(llvm::Attribute::OptimizeNone);
  800. F->addFnAttr(llvm::Attribute::NoInline);
  801. // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
  802. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  803. F->removeFnAttr(llvm::Attribute::MinSize);
  804. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  805. "OptimizeNone and AlwaysInline on same function!");
  806. // Attribute 'inlinehint' has no effect on 'optnone' functions.
  807. // Explicitly remove it from the set of function attributes.
  808. F->removeFnAttr(llvm::Attribute::InlineHint);
  809. }
  810. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  811. if (alignment)
  812. F->setAlignment(alignment);
  813. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  814. // reserve a bit for differentiating between virtual and non-virtual member
  815. // functions. If the current target's C++ ABI requires this and this is a
  816. // member function, set its alignment accordingly.
  817. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  818. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  819. F->setAlignment(2);
  820. }
  821. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  822. if (CodeGenOpts.SanitizeCfiCrossDso)
  823. if (auto *FD = dyn_cast<FunctionDecl>(D))
  824. CreateFunctionTypeMetadata(FD, F);
  825. }
  826. void CodeGenModule::SetCommonAttributes(const Decl *D,
  827. llvm::GlobalValue *GV) {
  828. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  829. setGlobalVisibility(GV, ND);
  830. else
  831. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  832. if (D && D->hasAttr<UsedAttr>())
  833. addUsedGlobal(GV);
  834. }
  835. void CodeGenModule::setAliasAttributes(const Decl *D,
  836. llvm::GlobalValue *GV) {
  837. SetCommonAttributes(D, GV);
  838. // Process the dllexport attribute based on whether the original definition
  839. // (not necessarily the aliasee) was exported.
  840. if (D->hasAttr<DLLExportAttr>())
  841. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  842. }
  843. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  844. llvm::GlobalObject *GO) {
  845. SetCommonAttributes(D, GO);
  846. if (D)
  847. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  848. GO->setSection(SA->getName());
  849. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  850. }
  851. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  852. llvm::Function *F,
  853. const CGFunctionInfo &FI) {
  854. SetLLVMFunctionAttributes(D, FI, F);
  855. SetLLVMFunctionAttributesForDefinition(D, F);
  856. F->setLinkage(llvm::Function::InternalLinkage);
  857. setNonAliasAttributes(D, F);
  858. }
  859. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  860. const NamedDecl *ND) {
  861. // Set linkage and visibility in case we never see a definition.
  862. LinkageInfo LV = ND->getLinkageAndVisibility();
  863. if (LV.getLinkage() != ExternalLinkage) {
  864. // Don't set internal linkage on declarations.
  865. } else {
  866. if (ND->hasAttr<DLLImportAttr>()) {
  867. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  868. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  869. } else if (ND->hasAttr<DLLExportAttr>()) {
  870. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  871. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  872. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  873. // "extern_weak" is overloaded in LLVM; we probably should have
  874. // separate linkage types for this.
  875. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  876. }
  877. // Set visibility on a declaration only if it's explicit.
  878. if (LV.isVisibilityExplicit())
  879. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  880. }
  881. }
  882. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  883. llvm::Function *F) {
  884. // Only if we are checking indirect calls.
  885. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  886. return;
  887. // Non-static class methods are handled via vtable pointer checks elsewhere.
  888. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  889. return;
  890. // Additionally, if building with cross-DSO support...
  891. if (CodeGenOpts.SanitizeCfiCrossDso) {
  892. // Skip available_externally functions. They won't be codegen'ed in the
  893. // current module anyway.
  894. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  895. return;
  896. }
  897. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  898. F->addTypeMetadata(0, MD);
  899. // Emit a hash-based bit set entry for cross-DSO calls.
  900. if (CodeGenOpts.SanitizeCfiCrossDso)
  901. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  902. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  903. }
  904. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  905. bool IsIncompleteFunction,
  906. bool IsThunk) {
  907. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  908. // If this is an intrinsic function, set the function's attributes
  909. // to the intrinsic's attributes.
  910. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  911. return;
  912. }
  913. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  914. if (!IsIncompleteFunction)
  915. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  916. // Add the Returned attribute for "this", except for iOS 5 and earlier
  917. // where substantial code, including the libstdc++ dylib, was compiled with
  918. // GCC and does not actually return "this".
  919. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  920. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  921. assert(!F->arg_empty() &&
  922. F->arg_begin()->getType()
  923. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  924. "unexpected this return");
  925. F->addAttribute(1, llvm::Attribute::Returned);
  926. }
  927. // Only a few attributes are set on declarations; these may later be
  928. // overridden by a definition.
  929. setLinkageAndVisibilityForGV(F, FD);
  930. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  931. F->setSection(SA->getName());
  932. if (FD->isReplaceableGlobalAllocationFunction()) {
  933. // A replaceable global allocation function does not act like a builtin by
  934. // default, only if it is invoked by a new-expression or delete-expression.
  935. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  936. llvm::Attribute::NoBuiltin);
  937. // A sane operator new returns a non-aliasing pointer.
  938. // FIXME: Also add NonNull attribute to the return value
  939. // for the non-nothrow forms?
  940. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  941. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  942. (Kind == OO_New || Kind == OO_Array_New))
  943. F->addAttribute(llvm::AttributeSet::ReturnIndex,
  944. llvm::Attribute::NoAlias);
  945. }
  946. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  947. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  948. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  949. if (MD->isVirtual())
  950. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  951. // Don't emit entries for function declarations in the cross-DSO mode. This
  952. // is handled with better precision by the receiving DSO.
  953. if (!CodeGenOpts.SanitizeCfiCrossDso)
  954. CreateFunctionTypeMetadata(FD, F);
  955. }
  956. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  957. assert(!GV->isDeclaration() &&
  958. "Only globals with definition can force usage.");
  959. LLVMUsed.emplace_back(GV);
  960. }
  961. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  962. assert(!GV->isDeclaration() &&
  963. "Only globals with definition can force usage.");
  964. LLVMCompilerUsed.emplace_back(GV);
  965. }
  966. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  967. std::vector<llvm::WeakVH> &List) {
  968. // Don't create llvm.used if there is no need.
  969. if (List.empty())
  970. return;
  971. // Convert List to what ConstantArray needs.
  972. SmallVector<llvm::Constant*, 8> UsedArray;
  973. UsedArray.resize(List.size());
  974. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  975. UsedArray[i] =
  976. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  977. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  978. }
  979. if (UsedArray.empty())
  980. return;
  981. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  982. auto *GV = new llvm::GlobalVariable(
  983. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  984. llvm::ConstantArray::get(ATy, UsedArray), Name);
  985. GV->setSection("llvm.metadata");
  986. }
  987. void CodeGenModule::emitLLVMUsed() {
  988. emitUsed(*this, "llvm.used", LLVMUsed);
  989. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  990. }
  991. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  992. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  993. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  994. }
  995. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  996. llvm::SmallString<32> Opt;
  997. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  998. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  999. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1000. }
  1001. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1002. llvm::SmallString<24> Opt;
  1003. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1004. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1005. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1006. }
  1007. /// \brief Add link options implied by the given module, including modules
  1008. /// it depends on, using a postorder walk.
  1009. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1010. SmallVectorImpl<llvm::Metadata *> &Metadata,
  1011. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1012. // Import this module's parent.
  1013. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1014. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1015. }
  1016. // Import this module's dependencies.
  1017. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1018. if (Visited.insert(Mod->Imports[I - 1]).second)
  1019. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1020. }
  1021. // Add linker options to link against the libraries/frameworks
  1022. // described by this module.
  1023. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1024. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1025. // Link against a framework. Frameworks are currently Darwin only, so we
  1026. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1027. if (Mod->LinkLibraries[I-1].IsFramework) {
  1028. llvm::Metadata *Args[2] = {
  1029. llvm::MDString::get(Context, "-framework"),
  1030. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1031. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1032. continue;
  1033. }
  1034. // Link against a library.
  1035. llvm::SmallString<24> Opt;
  1036. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1037. Mod->LinkLibraries[I-1].Library, Opt);
  1038. auto *OptString = llvm::MDString::get(Context, Opt);
  1039. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1040. }
  1041. }
  1042. void CodeGenModule::EmitModuleLinkOptions() {
  1043. // Collect the set of all of the modules we want to visit to emit link
  1044. // options, which is essentially the imported modules and all of their
  1045. // non-explicit child modules.
  1046. llvm::SetVector<clang::Module *> LinkModules;
  1047. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1048. SmallVector<clang::Module *, 16> Stack;
  1049. // Seed the stack with imported modules.
  1050. for (Module *M : ImportedModules)
  1051. if (Visited.insert(M).second)
  1052. Stack.push_back(M);
  1053. // Find all of the modules to import, making a little effort to prune
  1054. // non-leaf modules.
  1055. while (!Stack.empty()) {
  1056. clang::Module *Mod = Stack.pop_back_val();
  1057. bool AnyChildren = false;
  1058. // Visit the submodules of this module.
  1059. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1060. SubEnd = Mod->submodule_end();
  1061. Sub != SubEnd; ++Sub) {
  1062. // Skip explicit children; they need to be explicitly imported to be
  1063. // linked against.
  1064. if ((*Sub)->IsExplicit)
  1065. continue;
  1066. if (Visited.insert(*Sub).second) {
  1067. Stack.push_back(*Sub);
  1068. AnyChildren = true;
  1069. }
  1070. }
  1071. // We didn't find any children, so add this module to the list of
  1072. // modules to link against.
  1073. if (!AnyChildren) {
  1074. LinkModules.insert(Mod);
  1075. }
  1076. }
  1077. // Add link options for all of the imported modules in reverse topological
  1078. // order. We don't do anything to try to order import link flags with respect
  1079. // to linker options inserted by things like #pragma comment().
  1080. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  1081. Visited.clear();
  1082. for (Module *M : LinkModules)
  1083. if (Visited.insert(M).second)
  1084. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1085. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1086. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1087. // Add the linker options metadata flag.
  1088. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  1089. llvm::MDNode::get(getLLVMContext(),
  1090. LinkerOptionsMetadata));
  1091. }
  1092. void CodeGenModule::EmitDeferred() {
  1093. // Emit code for any potentially referenced deferred decls. Since a
  1094. // previously unused static decl may become used during the generation of code
  1095. // for a static function, iterate until no changes are made.
  1096. if (!DeferredVTables.empty()) {
  1097. EmitDeferredVTables();
  1098. // Emitting a vtable doesn't directly cause more vtables to
  1099. // become deferred, although it can cause functions to be
  1100. // emitted that then need those vtables.
  1101. assert(DeferredVTables.empty());
  1102. }
  1103. // Stop if we're out of both deferred vtables and deferred declarations.
  1104. if (DeferredDeclsToEmit.empty())
  1105. return;
  1106. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1107. // work, it will not interfere with this.
  1108. std::vector<DeferredGlobal> CurDeclsToEmit;
  1109. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1110. for (DeferredGlobal &G : CurDeclsToEmit) {
  1111. GlobalDecl D = G.GD;
  1112. G.GV = nullptr;
  1113. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1114. // to get GlobalValue with exactly the type we need, not something that
  1115. // might had been created for another decl with the same mangled name but
  1116. // different type.
  1117. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1118. GetAddrOfGlobal(D, ForDefinition));
  1119. // In case of different address spaces, we may still get a cast, even with
  1120. // IsForDefinition equal to true. Query mangled names table to get
  1121. // GlobalValue.
  1122. if (!GV)
  1123. GV = GetGlobalValue(getMangledName(D));
  1124. // Make sure GetGlobalValue returned non-null.
  1125. assert(GV);
  1126. // Check to see if we've already emitted this. This is necessary
  1127. // for a couple of reasons: first, decls can end up in the
  1128. // deferred-decls queue multiple times, and second, decls can end
  1129. // up with definitions in unusual ways (e.g. by an extern inline
  1130. // function acquiring a strong function redefinition). Just
  1131. // ignore these cases.
  1132. if (!GV->isDeclaration())
  1133. continue;
  1134. // Otherwise, emit the definition and move on to the next one.
  1135. EmitGlobalDefinition(D, GV);
  1136. // If we found out that we need to emit more decls, do that recursively.
  1137. // This has the advantage that the decls are emitted in a DFS and related
  1138. // ones are close together, which is convenient for testing.
  1139. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1140. EmitDeferred();
  1141. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1142. }
  1143. }
  1144. }
  1145. void CodeGenModule::EmitGlobalAnnotations() {
  1146. if (Annotations.empty())
  1147. return;
  1148. // Create a new global variable for the ConstantStruct in the Module.
  1149. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1150. Annotations[0]->getType(), Annotations.size()), Annotations);
  1151. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1152. llvm::GlobalValue::AppendingLinkage,
  1153. Array, "llvm.global.annotations");
  1154. gv->setSection(AnnotationSection);
  1155. }
  1156. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1157. llvm::Constant *&AStr = AnnotationStrings[Str];
  1158. if (AStr)
  1159. return AStr;
  1160. // Not found yet, create a new global.
  1161. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1162. auto *gv =
  1163. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1164. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1165. gv->setSection(AnnotationSection);
  1166. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1167. AStr = gv;
  1168. return gv;
  1169. }
  1170. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1171. SourceManager &SM = getContext().getSourceManager();
  1172. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1173. if (PLoc.isValid())
  1174. return EmitAnnotationString(PLoc.getFilename());
  1175. return EmitAnnotationString(SM.getBufferName(Loc));
  1176. }
  1177. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1178. SourceManager &SM = getContext().getSourceManager();
  1179. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1180. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1181. SM.getExpansionLineNumber(L);
  1182. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1183. }
  1184. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1185. const AnnotateAttr *AA,
  1186. SourceLocation L) {
  1187. // Get the globals for file name, annotation, and the line number.
  1188. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1189. *UnitGV = EmitAnnotationUnit(L),
  1190. *LineNoCst = EmitAnnotationLineNo(L);
  1191. // Create the ConstantStruct for the global annotation.
  1192. llvm::Constant *Fields[4] = {
  1193. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1194. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1195. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1196. LineNoCst
  1197. };
  1198. return llvm::ConstantStruct::getAnon(Fields);
  1199. }
  1200. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1201. llvm::GlobalValue *GV) {
  1202. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1203. // Get the struct elements for these annotations.
  1204. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1205. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1206. }
  1207. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1208. SourceLocation Loc) const {
  1209. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1210. // Blacklist by function name.
  1211. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1212. return true;
  1213. // Blacklist by location.
  1214. if (Loc.isValid())
  1215. return SanitizerBL.isBlacklistedLocation(Loc);
  1216. // If location is unknown, this may be a compiler-generated function. Assume
  1217. // it's located in the main file.
  1218. auto &SM = Context.getSourceManager();
  1219. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1220. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1221. }
  1222. return false;
  1223. }
  1224. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1225. SourceLocation Loc, QualType Ty,
  1226. StringRef Category) const {
  1227. // For now globals can be blacklisted only in ASan and KASan.
  1228. if (!LangOpts.Sanitize.hasOneOf(
  1229. SanitizerKind::Address | SanitizerKind::KernelAddress))
  1230. return false;
  1231. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1232. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1233. return true;
  1234. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1235. return true;
  1236. // Check global type.
  1237. if (!Ty.isNull()) {
  1238. // Drill down the array types: if global variable of a fixed type is
  1239. // blacklisted, we also don't instrument arrays of them.
  1240. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1241. Ty = AT->getElementType();
  1242. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1243. // We allow to blacklist only record types (classes, structs etc.)
  1244. if (Ty->isRecordType()) {
  1245. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1246. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1247. return true;
  1248. }
  1249. }
  1250. return false;
  1251. }
  1252. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1253. // Never defer when EmitAllDecls is specified.
  1254. if (LangOpts.EmitAllDecls)
  1255. return true;
  1256. return getContext().DeclMustBeEmitted(Global);
  1257. }
  1258. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1259. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1260. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1261. // Implicit template instantiations may change linkage if they are later
  1262. // explicitly instantiated, so they should not be emitted eagerly.
  1263. return false;
  1264. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1265. if (Context.getInlineVariableDefinitionKind(VD) ==
  1266. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1267. // A definition of an inline constexpr static data member may change
  1268. // linkage later if it's redeclared outside the class.
  1269. return false;
  1270. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1271. // codegen for global variables, because they may be marked as threadprivate.
  1272. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1273. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1274. return false;
  1275. return true;
  1276. }
  1277. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1278. const CXXUuidofExpr* E) {
  1279. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1280. // well-formed.
  1281. StringRef Uuid = E->getUuidStr();
  1282. std::string Name = "_GUID_" + Uuid.lower();
  1283. std::replace(Name.begin(), Name.end(), '-', '_');
  1284. // The UUID descriptor should be pointer aligned.
  1285. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1286. // Look for an existing global.
  1287. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1288. return ConstantAddress(GV, Alignment);
  1289. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1290. assert(Init && "failed to initialize as constant");
  1291. auto *GV = new llvm::GlobalVariable(
  1292. getModule(), Init->getType(),
  1293. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1294. if (supportsCOMDAT())
  1295. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1296. return ConstantAddress(GV, Alignment);
  1297. }
  1298. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1299. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1300. assert(AA && "No alias?");
  1301. CharUnits Alignment = getContext().getDeclAlign(VD);
  1302. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1303. // See if there is already something with the target's name in the module.
  1304. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1305. if (Entry) {
  1306. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1307. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1308. return ConstantAddress(Ptr, Alignment);
  1309. }
  1310. llvm::Constant *Aliasee;
  1311. if (isa<llvm::FunctionType>(DeclTy))
  1312. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1313. GlobalDecl(cast<FunctionDecl>(VD)),
  1314. /*ForVTable=*/false);
  1315. else
  1316. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1317. llvm::PointerType::getUnqual(DeclTy),
  1318. nullptr);
  1319. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1320. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1321. WeakRefReferences.insert(F);
  1322. return ConstantAddress(Aliasee, Alignment);
  1323. }
  1324. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1325. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1326. // Weak references don't produce any output by themselves.
  1327. if (Global->hasAttr<WeakRefAttr>())
  1328. return;
  1329. // If this is an alias definition (which otherwise looks like a declaration)
  1330. // emit it now.
  1331. if (Global->hasAttr<AliasAttr>())
  1332. return EmitAliasDefinition(GD);
  1333. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1334. if (Global->hasAttr<IFuncAttr>())
  1335. return emitIFuncDefinition(GD);
  1336. // If this is CUDA, be selective about which declarations we emit.
  1337. if (LangOpts.CUDA) {
  1338. if (LangOpts.CUDAIsDevice) {
  1339. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1340. !Global->hasAttr<CUDAGlobalAttr>() &&
  1341. !Global->hasAttr<CUDAConstantAttr>() &&
  1342. !Global->hasAttr<CUDASharedAttr>())
  1343. return;
  1344. } else {
  1345. // We need to emit host-side 'shadows' for all global
  1346. // device-side variables because the CUDA runtime needs their
  1347. // size and host-side address in order to provide access to
  1348. // their device-side incarnations.
  1349. // So device-only functions are the only things we skip.
  1350. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1351. Global->hasAttr<CUDADeviceAttr>())
  1352. return;
  1353. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1354. "Expected Variable or Function");
  1355. }
  1356. }
  1357. if (LangOpts.OpenMP) {
  1358. // If this is OpenMP device, check if it is legal to emit this global
  1359. // normally.
  1360. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1361. return;
  1362. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1363. if (MustBeEmitted(Global))
  1364. EmitOMPDeclareReduction(DRD);
  1365. return;
  1366. }
  1367. }
  1368. // Ignore declarations, they will be emitted on their first use.
  1369. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1370. // Forward declarations are emitted lazily on first use.
  1371. if (!FD->doesThisDeclarationHaveABody()) {
  1372. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1373. return;
  1374. StringRef MangledName = getMangledName(GD);
  1375. // Compute the function info and LLVM type.
  1376. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1377. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1378. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1379. /*DontDefer=*/false);
  1380. return;
  1381. }
  1382. } else {
  1383. const auto *VD = cast<VarDecl>(Global);
  1384. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1385. // We need to emit device-side global CUDA variables even if a
  1386. // variable does not have a definition -- we still need to define
  1387. // host-side shadow for it.
  1388. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1389. !VD->hasDefinition() &&
  1390. (VD->hasAttr<CUDAConstantAttr>() ||
  1391. VD->hasAttr<CUDADeviceAttr>());
  1392. if (!MustEmitForCuda &&
  1393. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1394. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1395. // If this declaration may have caused an inline variable definition to
  1396. // change linkage, make sure that it's emitted.
  1397. if (Context.getInlineVariableDefinitionKind(VD) ==
  1398. ASTContext::InlineVariableDefinitionKind::Strong)
  1399. GetAddrOfGlobalVar(VD);
  1400. return;
  1401. }
  1402. }
  1403. // Defer code generation to first use when possible, e.g. if this is an inline
  1404. // function. If the global must always be emitted, do it eagerly if possible
  1405. // to benefit from cache locality.
  1406. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1407. // Emit the definition if it can't be deferred.
  1408. EmitGlobalDefinition(GD);
  1409. return;
  1410. }
  1411. // If we're deferring emission of a C++ variable with an
  1412. // initializer, remember the order in which it appeared in the file.
  1413. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1414. cast<VarDecl>(Global)->hasInit()) {
  1415. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1416. CXXGlobalInits.push_back(nullptr);
  1417. }
  1418. StringRef MangledName = getMangledName(GD);
  1419. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1420. // The value has already been used and should therefore be emitted.
  1421. addDeferredDeclToEmit(GV, GD);
  1422. } else if (MustBeEmitted(Global)) {
  1423. // The value must be emitted, but cannot be emitted eagerly.
  1424. assert(!MayBeEmittedEagerly(Global));
  1425. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1426. } else {
  1427. // Otherwise, remember that we saw a deferred decl with this name. The
  1428. // first use of the mangled name will cause it to move into
  1429. // DeferredDeclsToEmit.
  1430. DeferredDecls[MangledName] = GD;
  1431. }
  1432. }
  1433. namespace {
  1434. struct FunctionIsDirectlyRecursive :
  1435. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1436. const StringRef Name;
  1437. const Builtin::Context &BI;
  1438. bool Result;
  1439. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1440. Name(N), BI(C), Result(false) {
  1441. }
  1442. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1443. bool TraverseCallExpr(CallExpr *E) {
  1444. const FunctionDecl *FD = E->getDirectCallee();
  1445. if (!FD)
  1446. return true;
  1447. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1448. if (Attr && Name == Attr->getLabel()) {
  1449. Result = true;
  1450. return false;
  1451. }
  1452. unsigned BuiltinID = FD->getBuiltinID();
  1453. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1454. return true;
  1455. StringRef BuiltinName = BI.getName(BuiltinID);
  1456. if (BuiltinName.startswith("__builtin_") &&
  1457. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1458. Result = true;
  1459. return false;
  1460. }
  1461. return true;
  1462. }
  1463. };
  1464. struct DLLImportFunctionVisitor
  1465. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1466. bool SafeToInline = true;
  1467. bool shouldVisitImplicitCode() const { return true; }
  1468. bool VisitVarDecl(VarDecl *VD) {
  1469. // A thread-local variable cannot be imported.
  1470. SafeToInline = !VD->getTLSKind();
  1471. return SafeToInline;
  1472. }
  1473. // Make sure we're not referencing non-imported vars or functions.
  1474. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1475. ValueDecl *VD = E->getDecl();
  1476. if (isa<FunctionDecl>(VD))
  1477. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1478. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1479. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1480. return SafeToInline;
  1481. }
  1482. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1483. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1484. return SafeToInline;
  1485. }
  1486. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1487. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1488. return SafeToInline;
  1489. }
  1490. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1491. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1492. return SafeToInline;
  1493. }
  1494. };
  1495. }
  1496. // isTriviallyRecursive - Check if this function calls another
  1497. // decl that, because of the asm attribute or the other decl being a builtin,
  1498. // ends up pointing to itself.
  1499. bool
  1500. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1501. StringRef Name;
  1502. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1503. // asm labels are a special kind of mangling we have to support.
  1504. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1505. if (!Attr)
  1506. return false;
  1507. Name = Attr->getLabel();
  1508. } else {
  1509. Name = FD->getName();
  1510. }
  1511. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1512. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1513. return Walker.Result;
  1514. }
  1515. // Check if T is a class type with a destructor that's not dllimport.
  1516. static bool HasNonDllImportDtor(QualType T) {
  1517. if (const RecordType *RT = dyn_cast<RecordType>(T))
  1518. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1519. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1520. return true;
  1521. return false;
  1522. }
  1523. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1524. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1525. return true;
  1526. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1527. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1528. return false;
  1529. if (F->hasAttr<DLLImportAttr>()) {
  1530. // Check whether it would be safe to inline this dllimport function.
  1531. DLLImportFunctionVisitor Visitor;
  1532. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1533. if (!Visitor.SafeToInline)
  1534. return false;
  1535. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1536. // Implicit destructor invocations aren't captured in the AST, so the
  1537. // check above can't see them. Check for them manually here.
  1538. for (const Decl *Member : Dtor->getParent()->decls())
  1539. if (isa<FieldDecl>(Member))
  1540. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1541. return false;
  1542. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1543. if (HasNonDllImportDtor(B.getType()))
  1544. return false;
  1545. }
  1546. }
  1547. // PR9614. Avoid cases where the source code is lying to us. An available
  1548. // externally function should have an equivalent function somewhere else,
  1549. // but a function that calls itself is clearly not equivalent to the real
  1550. // implementation.
  1551. // This happens in glibc's btowc and in some configure checks.
  1552. return !isTriviallyRecursive(F);
  1553. }
  1554. /// If the type for the method's class was generated by
  1555. /// CGDebugInfo::createContextChain(), the cache contains only a
  1556. /// limited DIType without any declarations. Since EmitFunctionStart()
  1557. /// needs to find the canonical declaration for each method, we need
  1558. /// to construct the complete type prior to emitting the method.
  1559. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1560. if (!D->isInstance())
  1561. return;
  1562. if (CGDebugInfo *DI = getModuleDebugInfo())
  1563. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  1564. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1565. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1566. }
  1567. }
  1568. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1569. const auto *D = cast<ValueDecl>(GD.getDecl());
  1570. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1571. Context.getSourceManager(),
  1572. "Generating code for declaration");
  1573. if (isa<FunctionDecl>(D)) {
  1574. // At -O0, don't generate IR for functions with available_externally
  1575. // linkage.
  1576. if (!shouldEmitFunction(GD))
  1577. return;
  1578. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1579. CompleteDIClassType(Method);
  1580. // Make sure to emit the definition(s) before we emit the thunks.
  1581. // This is necessary for the generation of certain thunks.
  1582. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1583. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1584. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1585. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1586. else
  1587. EmitGlobalFunctionDefinition(GD, GV);
  1588. if (Method->isVirtual())
  1589. getVTables().EmitThunks(GD);
  1590. return;
  1591. }
  1592. return EmitGlobalFunctionDefinition(GD, GV);
  1593. }
  1594. if (const auto *VD = dyn_cast<VarDecl>(D))
  1595. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1596. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1597. }
  1598. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1599. llvm::Function *NewFn);
  1600. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1601. /// module, create and return an llvm Function with the specified type. If there
  1602. /// is something in the module with the specified name, return it potentially
  1603. /// bitcasted to the right type.
  1604. ///
  1605. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1606. /// to set the attributes on the function when it is first created.
  1607. llvm::Constant *
  1608. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1609. llvm::Type *Ty,
  1610. GlobalDecl GD, bool ForVTable,
  1611. bool DontDefer, bool IsThunk,
  1612. llvm::AttributeSet ExtraAttrs,
  1613. ForDefinition_t IsForDefinition) {
  1614. const Decl *D = GD.getDecl();
  1615. // Lookup the entry, lazily creating it if necessary.
  1616. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1617. if (Entry) {
  1618. if (WeakRefReferences.erase(Entry)) {
  1619. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1620. if (FD && !FD->hasAttr<WeakAttr>())
  1621. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1622. }
  1623. // Handle dropped DLL attributes.
  1624. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1625. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1626. // If there are two attempts to define the same mangled name, issue an
  1627. // error.
  1628. if (IsForDefinition && !Entry->isDeclaration()) {
  1629. GlobalDecl OtherGD;
  1630. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  1631. // to make sure that we issue an error only once.
  1632. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  1633. (GD.getCanonicalDecl().getDecl() !=
  1634. OtherGD.getCanonicalDecl().getDecl()) &&
  1635. DiagnosedConflictingDefinitions.insert(GD).second) {
  1636. getDiags().Report(D->getLocation(),
  1637. diag::err_duplicate_mangled_name);
  1638. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1639. diag::note_previous_definition);
  1640. }
  1641. }
  1642. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  1643. (Entry->getType()->getElementType() == Ty)) {
  1644. return Entry;
  1645. }
  1646. // Make sure the result is of the correct type.
  1647. // (If function is requested for a definition, we always need to create a new
  1648. // function, not just return a bitcast.)
  1649. if (!IsForDefinition)
  1650. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1651. }
  1652. // This function doesn't have a complete type (for example, the return
  1653. // type is an incomplete struct). Use a fake type instead, and make
  1654. // sure not to try to set attributes.
  1655. bool IsIncompleteFunction = false;
  1656. llvm::FunctionType *FTy;
  1657. if (isa<llvm::FunctionType>(Ty)) {
  1658. FTy = cast<llvm::FunctionType>(Ty);
  1659. } else {
  1660. FTy = llvm::FunctionType::get(VoidTy, false);
  1661. IsIncompleteFunction = true;
  1662. }
  1663. llvm::Function *F =
  1664. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  1665. Entry ? StringRef() : MangledName, &getModule());
  1666. // If we already created a function with the same mangled name (but different
  1667. // type) before, take its name and add it to the list of functions to be
  1668. // replaced with F at the end of CodeGen.
  1669. //
  1670. // This happens if there is a prototype for a function (e.g. "int f()") and
  1671. // then a definition of a different type (e.g. "int f(int x)").
  1672. if (Entry) {
  1673. F->takeName(Entry);
  1674. // This might be an implementation of a function without a prototype, in
  1675. // which case, try to do special replacement of calls which match the new
  1676. // prototype. The really key thing here is that we also potentially drop
  1677. // arguments from the call site so as to make a direct call, which makes the
  1678. // inliner happier and suppresses a number of optimizer warnings (!) about
  1679. // dropping arguments.
  1680. if (!Entry->use_empty()) {
  1681. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  1682. Entry->removeDeadConstantUsers();
  1683. }
  1684. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  1685. F, Entry->getType()->getElementType()->getPointerTo());
  1686. addGlobalValReplacement(Entry, BC);
  1687. }
  1688. assert(F->getName() == MangledName && "name was uniqued!");
  1689. if (D)
  1690. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1691. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1692. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1693. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1694. llvm::AttributeSet::get(VMContext,
  1695. llvm::AttributeSet::FunctionIndex,
  1696. B));
  1697. }
  1698. if (!DontDefer) {
  1699. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1700. // each other bottoming out with the base dtor. Therefore we emit non-base
  1701. // dtors on usage, even if there is no dtor definition in the TU.
  1702. if (D && isa<CXXDestructorDecl>(D) &&
  1703. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1704. GD.getDtorType()))
  1705. addDeferredDeclToEmit(F, GD);
  1706. // This is the first use or definition of a mangled name. If there is a
  1707. // deferred decl with this name, remember that we need to emit it at the end
  1708. // of the file.
  1709. auto DDI = DeferredDecls.find(MangledName);
  1710. if (DDI != DeferredDecls.end()) {
  1711. // Move the potentially referenced deferred decl to the
  1712. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1713. // don't need it anymore).
  1714. addDeferredDeclToEmit(F, DDI->second);
  1715. DeferredDecls.erase(DDI);
  1716. // Otherwise, there are cases we have to worry about where we're
  1717. // using a declaration for which we must emit a definition but where
  1718. // we might not find a top-level definition:
  1719. // - member functions defined inline in their classes
  1720. // - friend functions defined inline in some class
  1721. // - special member functions with implicit definitions
  1722. // If we ever change our AST traversal to walk into class methods,
  1723. // this will be unnecessary.
  1724. //
  1725. // We also don't emit a definition for a function if it's going to be an
  1726. // entry in a vtable, unless it's already marked as used.
  1727. } else if (getLangOpts().CPlusPlus && D) {
  1728. // Look for a declaration that's lexically in a record.
  1729. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1730. FD = FD->getPreviousDecl()) {
  1731. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1732. if (FD->doesThisDeclarationHaveABody()) {
  1733. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1734. break;
  1735. }
  1736. }
  1737. }
  1738. }
  1739. }
  1740. // Make sure the result is of the requested type.
  1741. if (!IsIncompleteFunction) {
  1742. assert(F->getType()->getElementType() == Ty);
  1743. return F;
  1744. }
  1745. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1746. return llvm::ConstantExpr::getBitCast(F, PTy);
  1747. }
  1748. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1749. /// non-null, then this function will use the specified type if it has to
  1750. /// create it (this occurs when we see a definition of the function).
  1751. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1752. llvm::Type *Ty,
  1753. bool ForVTable,
  1754. bool DontDefer,
  1755. ForDefinition_t IsForDefinition) {
  1756. // If there was no specific requested type, just convert it now.
  1757. if (!Ty) {
  1758. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1759. auto CanonTy = Context.getCanonicalType(FD->getType());
  1760. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  1761. }
  1762. StringRef MangledName = getMangledName(GD);
  1763. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  1764. /*IsThunk=*/false, llvm::AttributeSet(),
  1765. IsForDefinition);
  1766. }
  1767. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1768. /// type and name.
  1769. llvm::Constant *
  1770. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1771. StringRef Name,
  1772. llvm::AttributeSet ExtraAttrs) {
  1773. llvm::Constant *C =
  1774. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1775. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1776. if (auto *F = dyn_cast<llvm::Function>(C))
  1777. if (F->empty())
  1778. F->setCallingConv(getRuntimeCC());
  1779. return C;
  1780. }
  1781. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1782. /// type and name.
  1783. llvm::Constant *
  1784. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
  1785. StringRef Name,
  1786. llvm::AttributeSet ExtraAttrs) {
  1787. llvm::Constant *C =
  1788. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1789. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1790. if (auto *F = dyn_cast<llvm::Function>(C))
  1791. if (F->empty())
  1792. F->setCallingConv(getBuiltinCC());
  1793. return C;
  1794. }
  1795. /// isTypeConstant - Determine whether an object of this type can be emitted
  1796. /// as a constant.
  1797. ///
  1798. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1799. /// will not be considered. The caller will need to verify that the object is
  1800. /// not written to during its construction.
  1801. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1802. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1803. return false;
  1804. if (Context.getLangOpts().CPlusPlus) {
  1805. if (const CXXRecordDecl *Record
  1806. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1807. return ExcludeCtor && !Record->hasMutableFields() &&
  1808. Record->hasTrivialDestructor();
  1809. }
  1810. return true;
  1811. }
  1812. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1813. /// create and return an llvm GlobalVariable with the specified type. If there
  1814. /// is something in the module with the specified name, return it potentially
  1815. /// bitcasted to the right type.
  1816. ///
  1817. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1818. /// to set the attributes on the global when it is first created.
  1819. ///
  1820. /// If IsForDefinition is true, it is guranteed that an actual global with
  1821. /// type Ty will be returned, not conversion of a variable with the same
  1822. /// mangled name but some other type.
  1823. llvm::Constant *
  1824. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1825. llvm::PointerType *Ty,
  1826. const VarDecl *D,
  1827. ForDefinition_t IsForDefinition) {
  1828. // Lookup the entry, lazily creating it if necessary.
  1829. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1830. if (Entry) {
  1831. if (WeakRefReferences.erase(Entry)) {
  1832. if (D && !D->hasAttr<WeakAttr>())
  1833. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1834. }
  1835. // Handle dropped DLL attributes.
  1836. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1837. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1838. if (Entry->getType() == Ty)
  1839. return Entry;
  1840. // If there are two attempts to define the same mangled name, issue an
  1841. // error.
  1842. if (IsForDefinition && !Entry->isDeclaration()) {
  1843. GlobalDecl OtherGD;
  1844. const VarDecl *OtherD;
  1845. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  1846. // to make sure that we issue an error only once.
  1847. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  1848. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  1849. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  1850. OtherD->hasInit() &&
  1851. DiagnosedConflictingDefinitions.insert(D).second) {
  1852. getDiags().Report(D->getLocation(),
  1853. diag::err_duplicate_mangled_name);
  1854. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1855. diag::note_previous_definition);
  1856. }
  1857. }
  1858. // Make sure the result is of the correct type.
  1859. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1860. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1861. // (If global is requested for a definition, we always need to create a new
  1862. // global, not just return a bitcast.)
  1863. if (!IsForDefinition)
  1864. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1865. }
  1866. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1867. auto *GV = new llvm::GlobalVariable(
  1868. getModule(), Ty->getElementType(), false,
  1869. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1870. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1871. // If we already created a global with the same mangled name (but different
  1872. // type) before, take its name and remove it from its parent.
  1873. if (Entry) {
  1874. GV->takeName(Entry);
  1875. if (!Entry->use_empty()) {
  1876. llvm::Constant *NewPtrForOldDecl =
  1877. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1878. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1879. }
  1880. Entry->eraseFromParent();
  1881. }
  1882. // This is the first use or definition of a mangled name. If there is a
  1883. // deferred decl with this name, remember that we need to emit it at the end
  1884. // of the file.
  1885. auto DDI = DeferredDecls.find(MangledName);
  1886. if (DDI != DeferredDecls.end()) {
  1887. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1888. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1889. addDeferredDeclToEmit(GV, DDI->second);
  1890. DeferredDecls.erase(DDI);
  1891. }
  1892. // Handle things which are present even on external declarations.
  1893. if (D) {
  1894. // FIXME: This code is overly simple and should be merged with other global
  1895. // handling.
  1896. GV->setConstant(isTypeConstant(D->getType(), false));
  1897. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1898. setLinkageAndVisibilityForGV(GV, D);
  1899. if (D->getTLSKind()) {
  1900. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1901. CXXThreadLocals.push_back(D);
  1902. setTLSMode(GV, *D);
  1903. }
  1904. // If required by the ABI, treat declarations of static data members with
  1905. // inline initializers as definitions.
  1906. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1907. EmitGlobalVarDefinition(D);
  1908. }
  1909. // Handle XCore specific ABI requirements.
  1910. if (getTriple().getArch() == llvm::Triple::xcore &&
  1911. D->getLanguageLinkage() == CLanguageLinkage &&
  1912. D->getType().isConstant(Context) &&
  1913. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1914. GV->setSection(".cp.rodata");
  1915. }
  1916. if (AddrSpace != Ty->getAddressSpace())
  1917. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1918. return GV;
  1919. }
  1920. llvm::Constant *
  1921. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  1922. ForDefinition_t IsForDefinition) {
  1923. if (isa<CXXConstructorDecl>(GD.getDecl()))
  1924. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
  1925. getFromCtorType(GD.getCtorType()),
  1926. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  1927. /*DontDefer=*/false, IsForDefinition);
  1928. else if (isa<CXXDestructorDecl>(GD.getDecl()))
  1929. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
  1930. getFromDtorType(GD.getDtorType()),
  1931. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  1932. /*DontDefer=*/false, IsForDefinition);
  1933. else if (isa<CXXMethodDecl>(GD.getDecl())) {
  1934. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  1935. cast<CXXMethodDecl>(GD.getDecl()));
  1936. auto Ty = getTypes().GetFunctionType(*FInfo);
  1937. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  1938. IsForDefinition);
  1939. } else if (isa<FunctionDecl>(GD.getDecl())) {
  1940. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1941. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1942. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  1943. IsForDefinition);
  1944. } else
  1945. return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
  1946. IsForDefinition);
  1947. }
  1948. llvm::GlobalVariable *
  1949. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1950. llvm::Type *Ty,
  1951. llvm::GlobalValue::LinkageTypes Linkage) {
  1952. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1953. llvm::GlobalVariable *OldGV = nullptr;
  1954. if (GV) {
  1955. // Check if the variable has the right type.
  1956. if (GV->getType()->getElementType() == Ty)
  1957. return GV;
  1958. // Because C++ name mangling, the only way we can end up with an already
  1959. // existing global with the same name is if it has been declared extern "C".
  1960. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1961. OldGV = GV;
  1962. }
  1963. // Create a new variable.
  1964. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1965. Linkage, nullptr, Name);
  1966. if (OldGV) {
  1967. // Replace occurrences of the old variable if needed.
  1968. GV->takeName(OldGV);
  1969. if (!OldGV->use_empty()) {
  1970. llvm::Constant *NewPtrForOldDecl =
  1971. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1972. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1973. }
  1974. OldGV->eraseFromParent();
  1975. }
  1976. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  1977. !GV->hasAvailableExternallyLinkage())
  1978. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1979. return GV;
  1980. }
  1981. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1982. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1983. /// then it will be created with the specified type instead of whatever the
  1984. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  1985. /// that an actual global with type Ty will be returned, not conversion of a
  1986. /// variable with the same mangled name but some other type.
  1987. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1988. llvm::Type *Ty,
  1989. ForDefinition_t IsForDefinition) {
  1990. assert(D->hasGlobalStorage() && "Not a global variable");
  1991. QualType ASTTy = D->getType();
  1992. if (!Ty)
  1993. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1994. llvm::PointerType *PTy =
  1995. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1996. StringRef MangledName = getMangledName(D);
  1997. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  1998. }
  1999. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2000. /// specified type and name.
  2001. llvm::Constant *
  2002. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2003. StringRef Name) {
  2004. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2005. }
  2006. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2007. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2008. StringRef MangledName = getMangledName(D);
  2009. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2010. // We already have a definition, not declaration, with the same mangled name.
  2011. // Emitting of declaration is not required (and actually overwrites emitted
  2012. // definition).
  2013. if (GV && !GV->isDeclaration())
  2014. return;
  2015. // If we have not seen a reference to this variable yet, place it into the
  2016. // deferred declarations table to be emitted if needed later.
  2017. if (!MustBeEmitted(D) && !GV) {
  2018. DeferredDecls[MangledName] = D;
  2019. return;
  2020. }
  2021. // The tentative definition is the only definition.
  2022. EmitGlobalVarDefinition(D);
  2023. }
  2024. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2025. return Context.toCharUnitsFromBits(
  2026. getDataLayout().getTypeStoreSizeInBits(Ty));
  2027. }
  2028. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  2029. unsigned AddrSpace) {
  2030. if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2031. if (D->hasAttr<CUDAConstantAttr>())
  2032. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  2033. else if (D->hasAttr<CUDASharedAttr>())
  2034. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  2035. else
  2036. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  2037. }
  2038. return AddrSpace;
  2039. }
  2040. template<typename SomeDecl>
  2041. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2042. llvm::GlobalValue *GV) {
  2043. if (!getLangOpts().CPlusPlus)
  2044. return;
  2045. // Must have 'used' attribute, or else inline assembly can't rely on
  2046. // the name existing.
  2047. if (!D->template hasAttr<UsedAttr>())
  2048. return;
  2049. // Must have internal linkage and an ordinary name.
  2050. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2051. return;
  2052. // Must be in an extern "C" context. Entities declared directly within
  2053. // a record are not extern "C" even if the record is in such a context.
  2054. const SomeDecl *First = D->getFirstDecl();
  2055. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2056. return;
  2057. // OK, this is an internal linkage entity inside an extern "C" linkage
  2058. // specification. Make a note of that so we can give it the "expected"
  2059. // mangled name if nothing else is using that name.
  2060. std::pair<StaticExternCMap::iterator, bool> R =
  2061. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2062. // If we have multiple internal linkage entities with the same name
  2063. // in extern "C" regions, none of them gets that name.
  2064. if (!R.second)
  2065. R.first->second = nullptr;
  2066. }
  2067. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2068. if (!CGM.supportsCOMDAT())
  2069. return false;
  2070. if (D.hasAttr<SelectAnyAttr>())
  2071. return true;
  2072. GVALinkage Linkage;
  2073. if (auto *VD = dyn_cast<VarDecl>(&D))
  2074. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2075. else
  2076. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2077. switch (Linkage) {
  2078. case GVA_Internal:
  2079. case GVA_AvailableExternally:
  2080. case GVA_StrongExternal:
  2081. return false;
  2082. case GVA_DiscardableODR:
  2083. case GVA_StrongODR:
  2084. return true;
  2085. }
  2086. llvm_unreachable("No such linkage");
  2087. }
  2088. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2089. llvm::GlobalObject &GO) {
  2090. if (!shouldBeInCOMDAT(*this, D))
  2091. return;
  2092. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2093. }
  2094. /// Pass IsTentative as true if you want to create a tentative definition.
  2095. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2096. bool IsTentative) {
  2097. // OpenCL global variables of sampler type are translated to function calls,
  2098. // therefore no need to be translated.
  2099. QualType ASTTy = D->getType();
  2100. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2101. return;
  2102. llvm::Constant *Init = nullptr;
  2103. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2104. bool NeedsGlobalCtor = false;
  2105. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2106. const VarDecl *InitDecl;
  2107. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2108. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2109. // as part of their declaration." Sema has already checked for
  2110. // error cases, so we just need to set Init to UndefValue.
  2111. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2112. D->hasAttr<CUDASharedAttr>())
  2113. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2114. else if (!InitExpr) {
  2115. // This is a tentative definition; tentative definitions are
  2116. // implicitly initialized with { 0 }.
  2117. //
  2118. // Note that tentative definitions are only emitted at the end of
  2119. // a translation unit, so they should never have incomplete
  2120. // type. In addition, EmitTentativeDefinition makes sure that we
  2121. // never attempt to emit a tentative definition if a real one
  2122. // exists. A use may still exists, however, so we still may need
  2123. // to do a RAUW.
  2124. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2125. Init = EmitNullConstant(D->getType());
  2126. } else {
  2127. initializedGlobalDecl = GlobalDecl(D);
  2128. Init = EmitConstantInit(*InitDecl);
  2129. if (!Init) {
  2130. QualType T = InitExpr->getType();
  2131. if (D->getType()->isReferenceType())
  2132. T = D->getType();
  2133. if (getLangOpts().CPlusPlus) {
  2134. Init = EmitNullConstant(T);
  2135. NeedsGlobalCtor = true;
  2136. } else {
  2137. ErrorUnsupported(D, "static initializer");
  2138. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2139. }
  2140. } else {
  2141. // We don't need an initializer, so remove the entry for the delayed
  2142. // initializer position (just in case this entry was delayed) if we
  2143. // also don't need to register a destructor.
  2144. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2145. DelayedCXXInitPosition.erase(D);
  2146. }
  2147. }
  2148. llvm::Type* InitType = Init->getType();
  2149. llvm::Constant *Entry =
  2150. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2151. // Strip off a bitcast if we got one back.
  2152. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2153. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2154. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2155. // All zero index gep.
  2156. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2157. Entry = CE->getOperand(0);
  2158. }
  2159. // Entry is now either a Function or GlobalVariable.
  2160. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2161. // We have a definition after a declaration with the wrong type.
  2162. // We must make a new GlobalVariable* and update everything that used OldGV
  2163. // (a declaration or tentative definition) with the new GlobalVariable*
  2164. // (which will be a definition).
  2165. //
  2166. // This happens if there is a prototype for a global (e.g.
  2167. // "extern int x[];") and then a definition of a different type (e.g.
  2168. // "int x[10];"). This also happens when an initializer has a different type
  2169. // from the type of the global (this happens with unions).
  2170. if (!GV ||
  2171. GV->getType()->getElementType() != InitType ||
  2172. GV->getType()->getAddressSpace() !=
  2173. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  2174. // Move the old entry aside so that we'll create a new one.
  2175. Entry->setName(StringRef());
  2176. // Make a new global with the correct type, this is now guaranteed to work.
  2177. GV = cast<llvm::GlobalVariable>(
  2178. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2179. // Replace all uses of the old global with the new global
  2180. llvm::Constant *NewPtrForOldDecl =
  2181. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2182. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2183. // Erase the old global, since it is no longer used.
  2184. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2185. }
  2186. MaybeHandleStaticInExternC(D, GV);
  2187. if (D->hasAttr<AnnotateAttr>())
  2188. AddGlobalAnnotations(D, GV);
  2189. // Set the llvm linkage type as appropriate.
  2190. llvm::GlobalValue::LinkageTypes Linkage =
  2191. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2192. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2193. // the device. [...]"
  2194. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2195. // __device__, declares a variable that: [...]
  2196. // Is accessible from all the threads within the grid and from the host
  2197. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2198. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2199. if (GV && LangOpts.CUDA) {
  2200. if (LangOpts.CUDAIsDevice) {
  2201. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2202. GV->setExternallyInitialized(true);
  2203. } else {
  2204. // Host-side shadows of external declarations of device-side
  2205. // global variables become internal definitions. These have to
  2206. // be internal in order to prevent name conflicts with global
  2207. // host variables with the same name in a different TUs.
  2208. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2209. Linkage = llvm::GlobalValue::InternalLinkage;
  2210. // Shadow variables and their properties must be registered
  2211. // with CUDA runtime.
  2212. unsigned Flags = 0;
  2213. if (!D->hasDefinition())
  2214. Flags |= CGCUDARuntime::ExternDeviceVar;
  2215. if (D->hasAttr<CUDAConstantAttr>())
  2216. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2217. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2218. } else if (D->hasAttr<CUDASharedAttr>())
  2219. // __shared__ variables are odd. Shadows do get created, but
  2220. // they are not registered with the CUDA runtime, so they
  2221. // can't really be used to access their device-side
  2222. // counterparts. It's not clear yet whether it's nvcc's bug or
  2223. // a feature, but we've got to do the same for compatibility.
  2224. Linkage = llvm::GlobalValue::InternalLinkage;
  2225. }
  2226. }
  2227. GV->setInitializer(Init);
  2228. // If it is safe to mark the global 'constant', do so now.
  2229. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2230. isTypeConstant(D->getType(), true));
  2231. // If it is in a read-only section, mark it 'constant'.
  2232. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2233. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2234. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2235. GV->setConstant(true);
  2236. }
  2237. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2238. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2239. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2240. // copies within a linkage unit; otherwise, the backing variable has
  2241. // internal linkage and all accesses should just be calls to the
  2242. // Itanium-specified entry point, which has the normal linkage of the
  2243. // variable. This is to preserve the ability to change the implementation
  2244. // behind the scenes.
  2245. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2246. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2247. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2248. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2249. Linkage = llvm::GlobalValue::InternalLinkage;
  2250. GV->setLinkage(Linkage);
  2251. if (D->hasAttr<DLLImportAttr>())
  2252. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2253. else if (D->hasAttr<DLLExportAttr>())
  2254. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2255. else
  2256. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2257. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  2258. // common vars aren't constant even if declared const.
  2259. GV->setConstant(false);
  2260. setNonAliasAttributes(D, GV);
  2261. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2262. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2263. CXXThreadLocals.push_back(D);
  2264. setTLSMode(GV, *D);
  2265. }
  2266. maybeSetTrivialComdat(*D, *GV);
  2267. // Emit the initializer function if necessary.
  2268. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2269. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2270. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2271. // Emit global variable debug information.
  2272. if (CGDebugInfo *DI = getModuleDebugInfo())
  2273. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2274. DI->EmitGlobalVariable(GV, D);
  2275. }
  2276. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2277. CodeGenModule &CGM, const VarDecl *D,
  2278. bool NoCommon) {
  2279. // Don't give variables common linkage if -fno-common was specified unless it
  2280. // was overridden by a NoCommon attribute.
  2281. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2282. return true;
  2283. // C11 6.9.2/2:
  2284. // A declaration of an identifier for an object that has file scope without
  2285. // an initializer, and without a storage-class specifier or with the
  2286. // storage-class specifier static, constitutes a tentative definition.
  2287. if (D->getInit() || D->hasExternalStorage())
  2288. return true;
  2289. // A variable cannot be both common and exist in a section.
  2290. if (D->hasAttr<SectionAttr>())
  2291. return true;
  2292. // Thread local vars aren't considered common linkage.
  2293. if (D->getTLSKind())
  2294. return true;
  2295. // Tentative definitions marked with WeakImportAttr are true definitions.
  2296. if (D->hasAttr<WeakImportAttr>())
  2297. return true;
  2298. // A variable cannot be both common and exist in a comdat.
  2299. if (shouldBeInCOMDAT(CGM, *D))
  2300. return true;
  2301. // Declarations with a required alignment do not have common linkage in MSVC
  2302. // mode.
  2303. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2304. if (D->hasAttr<AlignedAttr>())
  2305. return true;
  2306. QualType VarType = D->getType();
  2307. if (Context.isAlignmentRequired(VarType))
  2308. return true;
  2309. if (const auto *RT = VarType->getAs<RecordType>()) {
  2310. const RecordDecl *RD = RT->getDecl();
  2311. for (const FieldDecl *FD : RD->fields()) {
  2312. if (FD->isBitField())
  2313. continue;
  2314. if (FD->hasAttr<AlignedAttr>())
  2315. return true;
  2316. if (Context.isAlignmentRequired(FD->getType()))
  2317. return true;
  2318. }
  2319. }
  2320. }
  2321. return false;
  2322. }
  2323. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2324. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2325. if (Linkage == GVA_Internal)
  2326. return llvm::Function::InternalLinkage;
  2327. if (D->hasAttr<WeakAttr>()) {
  2328. if (IsConstantVariable)
  2329. return llvm::GlobalVariable::WeakODRLinkage;
  2330. else
  2331. return llvm::GlobalVariable::WeakAnyLinkage;
  2332. }
  2333. // We are guaranteed to have a strong definition somewhere else,
  2334. // so we can use available_externally linkage.
  2335. if (Linkage == GVA_AvailableExternally)
  2336. return llvm::Function::AvailableExternallyLinkage;
  2337. // Note that Apple's kernel linker doesn't support symbol
  2338. // coalescing, so we need to avoid linkonce and weak linkages there.
  2339. // Normally, this means we just map to internal, but for explicit
  2340. // instantiations we'll map to external.
  2341. // In C++, the compiler has to emit a definition in every translation unit
  2342. // that references the function. We should use linkonce_odr because
  2343. // a) if all references in this translation unit are optimized away, we
  2344. // don't need to codegen it. b) if the function persists, it needs to be
  2345. // merged with other definitions. c) C++ has the ODR, so we know the
  2346. // definition is dependable.
  2347. if (Linkage == GVA_DiscardableODR)
  2348. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2349. : llvm::Function::InternalLinkage;
  2350. // An explicit instantiation of a template has weak linkage, since
  2351. // explicit instantiations can occur in multiple translation units
  2352. // and must all be equivalent. However, we are not allowed to
  2353. // throw away these explicit instantiations.
  2354. //
  2355. // We don't currently support CUDA device code spread out across multiple TUs,
  2356. // so say that CUDA templates are either external (for kernels) or internal.
  2357. // This lets llvm perform aggressive inter-procedural optimizations.
  2358. if (Linkage == GVA_StrongODR) {
  2359. if (Context.getLangOpts().AppleKext)
  2360. return llvm::Function::ExternalLinkage;
  2361. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2362. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2363. : llvm::Function::InternalLinkage;
  2364. return llvm::Function::WeakODRLinkage;
  2365. }
  2366. // C++ doesn't have tentative definitions and thus cannot have common
  2367. // linkage.
  2368. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2369. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2370. CodeGenOpts.NoCommon))
  2371. return llvm::GlobalVariable::CommonLinkage;
  2372. // selectany symbols are externally visible, so use weak instead of
  2373. // linkonce. MSVC optimizes away references to const selectany globals, so
  2374. // all definitions should be the same and ODR linkage should be used.
  2375. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2376. if (D->hasAttr<SelectAnyAttr>())
  2377. return llvm::GlobalVariable::WeakODRLinkage;
  2378. // Otherwise, we have strong external linkage.
  2379. assert(Linkage == GVA_StrongExternal);
  2380. return llvm::GlobalVariable::ExternalLinkage;
  2381. }
  2382. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2383. const VarDecl *VD, bool IsConstant) {
  2384. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2385. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2386. }
  2387. /// Replace the uses of a function that was declared with a non-proto type.
  2388. /// We want to silently drop extra arguments from call sites
  2389. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2390. llvm::Function *newFn) {
  2391. // Fast path.
  2392. if (old->use_empty()) return;
  2393. llvm::Type *newRetTy = newFn->getReturnType();
  2394. SmallVector<llvm::Value*, 4> newArgs;
  2395. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2396. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2397. ui != ue; ) {
  2398. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2399. llvm::User *user = use->getUser();
  2400. // Recognize and replace uses of bitcasts. Most calls to
  2401. // unprototyped functions will use bitcasts.
  2402. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2403. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2404. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2405. continue;
  2406. }
  2407. // Recognize calls to the function.
  2408. llvm::CallSite callSite(user);
  2409. if (!callSite) continue;
  2410. if (!callSite.isCallee(&*use)) continue;
  2411. // If the return types don't match exactly, then we can't
  2412. // transform this call unless it's dead.
  2413. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2414. continue;
  2415. // Get the call site's attribute list.
  2416. SmallVector<llvm::AttributeSet, 8> newAttrs;
  2417. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  2418. // Collect any return attributes from the call.
  2419. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  2420. newAttrs.push_back(
  2421. llvm::AttributeSet::get(newFn->getContext(),
  2422. oldAttrs.getRetAttributes()));
  2423. // If the function was passed too few arguments, don't transform.
  2424. unsigned newNumArgs = newFn->arg_size();
  2425. if (callSite.arg_size() < newNumArgs) continue;
  2426. // If extra arguments were passed, we silently drop them.
  2427. // If any of the types mismatch, we don't transform.
  2428. unsigned argNo = 0;
  2429. bool dontTransform = false;
  2430. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  2431. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  2432. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  2433. dontTransform = true;
  2434. break;
  2435. }
  2436. // Add any parameter attributes.
  2437. if (oldAttrs.hasAttributes(argNo + 1))
  2438. newAttrs.
  2439. push_back(llvm::
  2440. AttributeSet::get(newFn->getContext(),
  2441. oldAttrs.getParamAttributes(argNo + 1)));
  2442. }
  2443. if (dontTransform)
  2444. continue;
  2445. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  2446. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  2447. oldAttrs.getFnAttributes()));
  2448. // Okay, we can transform this. Create the new call instruction and copy
  2449. // over the required information.
  2450. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2451. // Copy over any operand bundles.
  2452. callSite.getOperandBundlesAsDefs(newBundles);
  2453. llvm::CallSite newCall;
  2454. if (callSite.isCall()) {
  2455. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  2456. callSite.getInstruction());
  2457. } else {
  2458. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2459. newCall = llvm::InvokeInst::Create(newFn,
  2460. oldInvoke->getNormalDest(),
  2461. oldInvoke->getUnwindDest(),
  2462. newArgs, newBundles, "",
  2463. callSite.getInstruction());
  2464. }
  2465. newArgs.clear(); // for the next iteration
  2466. if (!newCall->getType()->isVoidTy())
  2467. newCall->takeName(callSite.getInstruction());
  2468. newCall.setAttributes(
  2469. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  2470. newCall.setCallingConv(callSite.getCallingConv());
  2471. // Finally, remove the old call, replacing any uses with the new one.
  2472. if (!callSite->use_empty())
  2473. callSite->replaceAllUsesWith(newCall.getInstruction());
  2474. // Copy debug location attached to CI.
  2475. if (callSite->getDebugLoc())
  2476. newCall->setDebugLoc(callSite->getDebugLoc());
  2477. callSite->eraseFromParent();
  2478. }
  2479. }
  2480. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2481. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2482. /// existing call uses of the old function in the module, this adjusts them to
  2483. /// call the new function directly.
  2484. ///
  2485. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2486. /// functions to be able to inline them. If there is a bitcast in the way, it
  2487. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2488. /// run at -O0.
  2489. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2490. llvm::Function *NewFn) {
  2491. // If we're redefining a global as a function, don't transform it.
  2492. if (!isa<llvm::Function>(Old)) return;
  2493. replaceUsesOfNonProtoConstant(Old, NewFn);
  2494. }
  2495. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2496. auto DK = VD->isThisDeclarationADefinition();
  2497. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  2498. return;
  2499. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2500. // If we have a definition, this might be a deferred decl. If the
  2501. // instantiation is explicit, make sure we emit it at the end.
  2502. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2503. GetAddrOfGlobalVar(VD);
  2504. EmitTopLevelDecl(VD);
  2505. }
  2506. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2507. llvm::GlobalValue *GV) {
  2508. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2509. // Compute the function info and LLVM type.
  2510. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2511. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2512. // Get or create the prototype for the function.
  2513. if (!GV || (GV->getType()->getElementType() != Ty))
  2514. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  2515. /*DontDefer=*/true,
  2516. ForDefinition));
  2517. // Already emitted.
  2518. if (!GV->isDeclaration())
  2519. return;
  2520. // We need to set linkage and visibility on the function before
  2521. // generating code for it because various parts of IR generation
  2522. // want to propagate this information down (e.g. to local static
  2523. // declarations).
  2524. auto *Fn = cast<llvm::Function>(GV);
  2525. setFunctionLinkage(GD, Fn);
  2526. setFunctionDLLStorageClass(GD, Fn);
  2527. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2528. setGlobalVisibility(Fn, D);
  2529. MaybeHandleStaticInExternC(D, Fn);
  2530. maybeSetTrivialComdat(*D, *Fn);
  2531. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2532. setFunctionDefinitionAttributes(D, Fn);
  2533. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2534. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2535. AddGlobalCtor(Fn, CA->getPriority());
  2536. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2537. AddGlobalDtor(Fn, DA->getPriority());
  2538. if (D->hasAttr<AnnotateAttr>())
  2539. AddGlobalAnnotations(D, Fn);
  2540. }
  2541. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2542. const auto *D = cast<ValueDecl>(GD.getDecl());
  2543. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2544. assert(AA && "Not an alias?");
  2545. StringRef MangledName = getMangledName(GD);
  2546. if (AA->getAliasee() == MangledName) {
  2547. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2548. return;
  2549. }
  2550. // If there is a definition in the module, then it wins over the alias.
  2551. // This is dubious, but allow it to be safe. Just ignore the alias.
  2552. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2553. if (Entry && !Entry->isDeclaration())
  2554. return;
  2555. Aliases.push_back(GD);
  2556. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2557. // Create a reference to the named value. This ensures that it is emitted
  2558. // if a deferred decl.
  2559. llvm::Constant *Aliasee;
  2560. if (isa<llvm::FunctionType>(DeclTy))
  2561. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2562. /*ForVTable=*/false);
  2563. else
  2564. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2565. llvm::PointerType::getUnqual(DeclTy),
  2566. /*D=*/nullptr);
  2567. // Create the new alias itself, but don't set a name yet.
  2568. auto *GA = llvm::GlobalAlias::create(
  2569. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2570. if (Entry) {
  2571. if (GA->getAliasee() == Entry) {
  2572. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2573. return;
  2574. }
  2575. assert(Entry->isDeclaration());
  2576. // If there is a declaration in the module, then we had an extern followed
  2577. // by the alias, as in:
  2578. // extern int test6();
  2579. // ...
  2580. // int test6() __attribute__((alias("test7")));
  2581. //
  2582. // Remove it and replace uses of it with the alias.
  2583. GA->takeName(Entry);
  2584. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2585. Entry->getType()));
  2586. Entry->eraseFromParent();
  2587. } else {
  2588. GA->setName(MangledName);
  2589. }
  2590. // Set attributes which are particular to an alias; this is a
  2591. // specialization of the attributes which may be set on a global
  2592. // variable/function.
  2593. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2594. D->isWeakImported()) {
  2595. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2596. }
  2597. if (const auto *VD = dyn_cast<VarDecl>(D))
  2598. if (VD->getTLSKind())
  2599. setTLSMode(GA, *VD);
  2600. setAliasAttributes(D, GA);
  2601. }
  2602. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  2603. const auto *D = cast<ValueDecl>(GD.getDecl());
  2604. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  2605. assert(IFA && "Not an ifunc?");
  2606. StringRef MangledName = getMangledName(GD);
  2607. if (IFA->getResolver() == MangledName) {
  2608. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2609. return;
  2610. }
  2611. // Report an error if some definition overrides ifunc.
  2612. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2613. if (Entry && !Entry->isDeclaration()) {
  2614. GlobalDecl OtherGD;
  2615. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2616. DiagnosedConflictingDefinitions.insert(GD).second) {
  2617. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2618. Diags.Report(OtherGD.getDecl()->getLocation(),
  2619. diag::note_previous_definition);
  2620. }
  2621. return;
  2622. }
  2623. Aliases.push_back(GD);
  2624. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2625. llvm::Constant *Resolver =
  2626. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  2627. /*ForVTable=*/false);
  2628. llvm::GlobalIFunc *GIF =
  2629. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  2630. "", Resolver, &getModule());
  2631. if (Entry) {
  2632. if (GIF->getResolver() == Entry) {
  2633. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2634. return;
  2635. }
  2636. assert(Entry->isDeclaration());
  2637. // If there is a declaration in the module, then we had an extern followed
  2638. // by the ifunc, as in:
  2639. // extern int test();
  2640. // ...
  2641. // int test() __attribute__((ifunc("resolver")));
  2642. //
  2643. // Remove it and replace uses of it with the ifunc.
  2644. GIF->takeName(Entry);
  2645. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  2646. Entry->getType()));
  2647. Entry->eraseFromParent();
  2648. } else
  2649. GIF->setName(MangledName);
  2650. SetCommonAttributes(D, GIF);
  2651. }
  2652. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2653. ArrayRef<llvm::Type*> Tys) {
  2654. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2655. Tys);
  2656. }
  2657. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2658. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2659. const StringLiteral *Literal, bool TargetIsLSB,
  2660. bool &IsUTF16, unsigned &StringLength) {
  2661. StringRef String = Literal->getString();
  2662. unsigned NumBytes = String.size();
  2663. // Check for simple case.
  2664. if (!Literal->containsNonAsciiOrNull()) {
  2665. StringLength = NumBytes;
  2666. return *Map.insert(std::make_pair(String, nullptr)).first;
  2667. }
  2668. // Otherwise, convert the UTF8 literals into a string of shorts.
  2669. IsUTF16 = true;
  2670. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2671. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  2672. llvm::UTF16 *ToPtr = &ToBuf[0];
  2673. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  2674. ToPtr + NumBytes, llvm::strictConversion);
  2675. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2676. StringLength = ToPtr - &ToBuf[0];
  2677. // Add an explicit null.
  2678. *ToPtr = 0;
  2679. return *Map.insert(std::make_pair(
  2680. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2681. (StringLength + 1) * 2),
  2682. nullptr)).first;
  2683. }
  2684. ConstantAddress
  2685. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2686. unsigned StringLength = 0;
  2687. bool isUTF16 = false;
  2688. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2689. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2690. getDataLayout().isLittleEndian(), isUTF16,
  2691. StringLength);
  2692. if (auto *C = Entry.second)
  2693. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  2694. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2695. llvm::Constant *Zeros[] = { Zero, Zero };
  2696. // If we don't already have it, get __CFConstantStringClassReference.
  2697. if (!CFConstantStringClassRef) {
  2698. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2699. Ty = llvm::ArrayType::get(Ty, 0);
  2700. llvm::Constant *GV =
  2701. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  2702. if (getTriple().isOSBinFormatCOFF()) {
  2703. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  2704. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  2705. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2706. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  2707. const VarDecl *VD = nullptr;
  2708. for (const auto &Result : DC->lookup(&II))
  2709. if ((VD = dyn_cast<VarDecl>(Result)))
  2710. break;
  2711. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  2712. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2713. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2714. } else {
  2715. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2716. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2717. }
  2718. }
  2719. // Decay array -> ptr
  2720. CFConstantStringClassRef =
  2721. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2722. }
  2723. QualType CFTy = getContext().getCFConstantStringType();
  2724. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2725. ConstantInitBuilder Builder(*this);
  2726. auto Fields = Builder.beginStruct(STy);
  2727. // Class pointer.
  2728. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  2729. // Flags.
  2730. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  2731. // String pointer.
  2732. llvm::Constant *C = nullptr;
  2733. if (isUTF16) {
  2734. auto Arr = llvm::makeArrayRef(
  2735. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2736. Entry.first().size() / 2);
  2737. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2738. } else {
  2739. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2740. }
  2741. // Note: -fwritable-strings doesn't make the backing store strings of
  2742. // CFStrings writable. (See <rdar://problem/10657500>)
  2743. auto *GV =
  2744. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2745. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2746. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2747. // Don't enforce the target's minimum global alignment, since the only use
  2748. // of the string is via this class initializer.
  2749. CharUnits Align = isUTF16
  2750. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  2751. : getContext().getTypeAlignInChars(getContext().CharTy);
  2752. GV->setAlignment(Align.getQuantity());
  2753. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  2754. // Without it LLVM can merge the string with a non unnamed_addr one during
  2755. // LTO. Doing that changes the section it ends in, which surprises ld64.
  2756. if (getTriple().isOSBinFormatMachO())
  2757. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  2758. : "__TEXT,__cstring,cstring_literals");
  2759. // String.
  2760. llvm::Constant *Str =
  2761. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2762. if (isUTF16)
  2763. // Cast the UTF16 string to the correct type.
  2764. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  2765. Fields.add(Str);
  2766. // String length.
  2767. auto Ty = getTypes().ConvertType(getContext().LongTy);
  2768. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  2769. CharUnits Alignment = getPointerAlign();
  2770. // The struct.
  2771. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  2772. /*isConstant=*/false,
  2773. llvm::GlobalVariable::PrivateLinkage);
  2774. switch (getTriple().getObjectFormat()) {
  2775. case llvm::Triple::UnknownObjectFormat:
  2776. llvm_unreachable("unknown file format");
  2777. case llvm::Triple::COFF:
  2778. case llvm::Triple::ELF:
  2779. GV->setSection("cfstring");
  2780. break;
  2781. case llvm::Triple::MachO:
  2782. GV->setSection("__DATA,__cfstring");
  2783. break;
  2784. }
  2785. Entry.second = GV;
  2786. return ConstantAddress(GV, Alignment);
  2787. }
  2788. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2789. if (ObjCFastEnumerationStateType.isNull()) {
  2790. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2791. D->startDefinition();
  2792. QualType FieldTypes[] = {
  2793. Context.UnsignedLongTy,
  2794. Context.getPointerType(Context.getObjCIdType()),
  2795. Context.getPointerType(Context.UnsignedLongTy),
  2796. Context.getConstantArrayType(Context.UnsignedLongTy,
  2797. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2798. };
  2799. for (size_t i = 0; i < 4; ++i) {
  2800. FieldDecl *Field = FieldDecl::Create(Context,
  2801. D,
  2802. SourceLocation(),
  2803. SourceLocation(), nullptr,
  2804. FieldTypes[i], /*TInfo=*/nullptr,
  2805. /*BitWidth=*/nullptr,
  2806. /*Mutable=*/false,
  2807. ICIS_NoInit);
  2808. Field->setAccess(AS_public);
  2809. D->addDecl(Field);
  2810. }
  2811. D->completeDefinition();
  2812. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2813. }
  2814. return ObjCFastEnumerationStateType;
  2815. }
  2816. llvm::Constant *
  2817. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2818. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2819. // Don't emit it as the address of the string, emit the string data itself
  2820. // as an inline array.
  2821. if (E->getCharByteWidth() == 1) {
  2822. SmallString<64> Str(E->getString());
  2823. // Resize the string to the right size, which is indicated by its type.
  2824. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2825. Str.resize(CAT->getSize().getZExtValue());
  2826. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2827. }
  2828. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2829. llvm::Type *ElemTy = AType->getElementType();
  2830. unsigned NumElements = AType->getNumElements();
  2831. // Wide strings have either 2-byte or 4-byte elements.
  2832. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2833. SmallVector<uint16_t, 32> Elements;
  2834. Elements.reserve(NumElements);
  2835. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2836. Elements.push_back(E->getCodeUnit(i));
  2837. Elements.resize(NumElements);
  2838. return llvm::ConstantDataArray::get(VMContext, Elements);
  2839. }
  2840. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2841. SmallVector<uint32_t, 32> Elements;
  2842. Elements.reserve(NumElements);
  2843. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2844. Elements.push_back(E->getCodeUnit(i));
  2845. Elements.resize(NumElements);
  2846. return llvm::ConstantDataArray::get(VMContext, Elements);
  2847. }
  2848. static llvm::GlobalVariable *
  2849. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2850. CodeGenModule &CGM, StringRef GlobalName,
  2851. CharUnits Alignment) {
  2852. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2853. unsigned AddrSpace = 0;
  2854. if (CGM.getLangOpts().OpenCL)
  2855. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2856. llvm::Module &M = CGM.getModule();
  2857. // Create a global variable for this string
  2858. auto *GV = new llvm::GlobalVariable(
  2859. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2860. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2861. GV->setAlignment(Alignment.getQuantity());
  2862. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2863. if (GV->isWeakForLinker()) {
  2864. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2865. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2866. }
  2867. return GV;
  2868. }
  2869. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2870. /// constant array for the given string literal.
  2871. ConstantAddress
  2872. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2873. StringRef Name) {
  2874. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  2875. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2876. llvm::GlobalVariable **Entry = nullptr;
  2877. if (!LangOpts.WritableStrings) {
  2878. Entry = &ConstantStringMap[C];
  2879. if (auto GV = *Entry) {
  2880. if (Alignment.getQuantity() > GV->getAlignment())
  2881. GV->setAlignment(Alignment.getQuantity());
  2882. return ConstantAddress(GV, Alignment);
  2883. }
  2884. }
  2885. SmallString<256> MangledNameBuffer;
  2886. StringRef GlobalVariableName;
  2887. llvm::GlobalValue::LinkageTypes LT;
  2888. // Mangle the string literal if the ABI allows for it. However, we cannot
  2889. // do this if we are compiling with ASan or -fwritable-strings because they
  2890. // rely on strings having normal linkage.
  2891. if (!LangOpts.WritableStrings &&
  2892. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2893. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2894. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2895. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2896. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2897. GlobalVariableName = MangledNameBuffer;
  2898. } else {
  2899. LT = llvm::GlobalValue::PrivateLinkage;
  2900. GlobalVariableName = Name;
  2901. }
  2902. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2903. if (Entry)
  2904. *Entry = GV;
  2905. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  2906. QualType());
  2907. return ConstantAddress(GV, Alignment);
  2908. }
  2909. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2910. /// array for the given ObjCEncodeExpr node.
  2911. ConstantAddress
  2912. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2913. std::string Str;
  2914. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2915. return GetAddrOfConstantCString(Str);
  2916. }
  2917. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2918. /// the literal and a terminating '\0' character.
  2919. /// The result has pointer to array type.
  2920. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  2921. const std::string &Str, const char *GlobalName) {
  2922. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2923. CharUnits Alignment =
  2924. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  2925. llvm::Constant *C =
  2926. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2927. // Don't share any string literals if strings aren't constant.
  2928. llvm::GlobalVariable **Entry = nullptr;
  2929. if (!LangOpts.WritableStrings) {
  2930. Entry = &ConstantStringMap[C];
  2931. if (auto GV = *Entry) {
  2932. if (Alignment.getQuantity() > GV->getAlignment())
  2933. GV->setAlignment(Alignment.getQuantity());
  2934. return ConstantAddress(GV, Alignment);
  2935. }
  2936. }
  2937. // Get the default prefix if a name wasn't specified.
  2938. if (!GlobalName)
  2939. GlobalName = ".str";
  2940. // Create a global variable for this.
  2941. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2942. GlobalName, Alignment);
  2943. if (Entry)
  2944. *Entry = GV;
  2945. return ConstantAddress(GV, Alignment);
  2946. }
  2947. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  2948. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2949. assert((E->getStorageDuration() == SD_Static ||
  2950. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2951. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2952. // If we're not materializing a subobject of the temporary, keep the
  2953. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2954. QualType MaterializedType = Init->getType();
  2955. if (Init == E->GetTemporaryExpr())
  2956. MaterializedType = E->getType();
  2957. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  2958. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  2959. return ConstantAddress(Slot, Align);
  2960. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2961. // we need to give each temporary the same name in every translation unit (and
  2962. // we also need to make the temporaries externally-visible).
  2963. SmallString<256> Name;
  2964. llvm::raw_svector_ostream Out(Name);
  2965. getCXXABI().getMangleContext().mangleReferenceTemporary(
  2966. VD, E->getManglingNumber(), Out);
  2967. APValue *Value = nullptr;
  2968. if (E->getStorageDuration() == SD_Static) {
  2969. // We might have a cached constant initializer for this temporary. Note
  2970. // that this might have a different value from the value computed by
  2971. // evaluating the initializer if the surrounding constant expression
  2972. // modifies the temporary.
  2973. Value = getContext().getMaterializedTemporaryValue(E, false);
  2974. if (Value && Value->isUninit())
  2975. Value = nullptr;
  2976. }
  2977. // Try evaluating it now, it might have a constant initializer.
  2978. Expr::EvalResult EvalResult;
  2979. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2980. !EvalResult.hasSideEffects())
  2981. Value = &EvalResult.Val;
  2982. llvm::Constant *InitialValue = nullptr;
  2983. bool Constant = false;
  2984. llvm::Type *Type;
  2985. if (Value) {
  2986. // The temporary has a constant initializer, use it.
  2987. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  2988. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2989. Type = InitialValue->getType();
  2990. } else {
  2991. // No initializer, the initialization will be provided when we
  2992. // initialize the declaration which performed lifetime extension.
  2993. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2994. }
  2995. // Create a global variable for this lifetime-extended temporary.
  2996. llvm::GlobalValue::LinkageTypes Linkage =
  2997. getLLVMLinkageVarDefinition(VD, Constant);
  2998. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  2999. const VarDecl *InitVD;
  3000. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3001. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3002. // Temporaries defined inside a class get linkonce_odr linkage because the
  3003. // class can be defined in multipe translation units.
  3004. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3005. } else {
  3006. // There is no need for this temporary to have external linkage if the
  3007. // VarDecl has external linkage.
  3008. Linkage = llvm::GlobalVariable::InternalLinkage;
  3009. }
  3010. }
  3011. unsigned AddrSpace = GetGlobalVarAddressSpace(
  3012. VD, getContext().getTargetAddressSpace(MaterializedType));
  3013. auto *GV = new llvm::GlobalVariable(
  3014. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3015. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  3016. AddrSpace);
  3017. setGlobalVisibility(GV, VD);
  3018. GV->setAlignment(Align.getQuantity());
  3019. if (supportsCOMDAT() && GV->isWeakForLinker())
  3020. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3021. if (VD->getTLSKind())
  3022. setTLSMode(GV, *VD);
  3023. MaterializedGlobalTemporaryMap[E] = GV;
  3024. return ConstantAddress(GV, Align);
  3025. }
  3026. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3027. /// properties for an implementation.
  3028. void CodeGenModule::EmitObjCPropertyImplementations(const
  3029. ObjCImplementationDecl *D) {
  3030. for (const auto *PID : D->property_impls()) {
  3031. // Dynamic is just for type-checking.
  3032. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3033. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3034. // Determine which methods need to be implemented, some may have
  3035. // been overridden. Note that ::isPropertyAccessor is not the method
  3036. // we want, that just indicates if the decl came from a
  3037. // property. What we want to know is if the method is defined in
  3038. // this implementation.
  3039. if (!D->getInstanceMethod(PD->getGetterName()))
  3040. CodeGenFunction(*this).GenerateObjCGetter(
  3041. const_cast<ObjCImplementationDecl *>(D), PID);
  3042. if (!PD->isReadOnly() &&
  3043. !D->getInstanceMethod(PD->getSetterName()))
  3044. CodeGenFunction(*this).GenerateObjCSetter(
  3045. const_cast<ObjCImplementationDecl *>(D), PID);
  3046. }
  3047. }
  3048. }
  3049. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3050. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3051. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3052. ivar; ivar = ivar->getNextIvar())
  3053. if (ivar->getType().isDestructedType())
  3054. return true;
  3055. return false;
  3056. }
  3057. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3058. ObjCImplementationDecl *D) {
  3059. CodeGenFunction CGF(CGM);
  3060. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3061. E = D->init_end(); B != E; ++B) {
  3062. CXXCtorInitializer *CtorInitExp = *B;
  3063. Expr *Init = CtorInitExp->getInit();
  3064. if (!CGF.isTrivialInitializer(Init))
  3065. return false;
  3066. }
  3067. return true;
  3068. }
  3069. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3070. /// for an implementation.
  3071. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3072. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3073. if (needsDestructMethod(D)) {
  3074. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3075. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3076. ObjCMethodDecl *DTORMethod =
  3077. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3078. cxxSelector, getContext().VoidTy, nullptr, D,
  3079. /*isInstance=*/true, /*isVariadic=*/false,
  3080. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3081. /*isDefined=*/false, ObjCMethodDecl::Required);
  3082. D->addInstanceMethod(DTORMethod);
  3083. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3084. D->setHasDestructors(true);
  3085. }
  3086. // If the implementation doesn't have any ivar initializers, we don't need
  3087. // a .cxx_construct.
  3088. if (D->getNumIvarInitializers() == 0 ||
  3089. AllTrivialInitializers(*this, D))
  3090. return;
  3091. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3092. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3093. // The constructor returns 'self'.
  3094. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3095. D->getLocation(),
  3096. D->getLocation(),
  3097. cxxSelector,
  3098. getContext().getObjCIdType(),
  3099. nullptr, D, /*isInstance=*/true,
  3100. /*isVariadic=*/false,
  3101. /*isPropertyAccessor=*/true,
  3102. /*isImplicitlyDeclared=*/true,
  3103. /*isDefined=*/false,
  3104. ObjCMethodDecl::Required);
  3105. D->addInstanceMethod(CTORMethod);
  3106. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3107. D->setHasNonZeroConstructors(true);
  3108. }
  3109. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3110. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3111. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3112. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3113. ErrorUnsupported(LSD, "linkage spec");
  3114. return;
  3115. }
  3116. EmitDeclContext(LSD);
  3117. }
  3118. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3119. for (auto *I : DC->decls()) {
  3120. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3121. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3122. // ObjCImplDecl does not recursively visit them. We need to do that in
  3123. // case they're nested inside another construct (LinkageSpecDecl /
  3124. // ExportDecl) that does stop them from being considered "top-level".
  3125. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3126. for (auto *M : OID->methods())
  3127. EmitTopLevelDecl(M);
  3128. }
  3129. EmitTopLevelDecl(I);
  3130. }
  3131. }
  3132. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3133. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3134. // Ignore dependent declarations.
  3135. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  3136. return;
  3137. switch (D->getKind()) {
  3138. case Decl::CXXConversion:
  3139. case Decl::CXXMethod:
  3140. case Decl::Function:
  3141. // Skip function templates
  3142. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3143. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3144. return;
  3145. EmitGlobal(cast<FunctionDecl>(D));
  3146. // Always provide some coverage mapping
  3147. // even for the functions that aren't emitted.
  3148. AddDeferredUnusedCoverageMapping(D);
  3149. break;
  3150. case Decl::Var:
  3151. case Decl::Decomposition:
  3152. // Skip variable templates
  3153. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  3154. return;
  3155. case Decl::VarTemplateSpecialization:
  3156. EmitGlobal(cast<VarDecl>(D));
  3157. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3158. for (auto *B : DD->bindings())
  3159. if (auto *HD = B->getHoldingVar())
  3160. EmitGlobal(HD);
  3161. break;
  3162. // Indirect fields from global anonymous structs and unions can be
  3163. // ignored; only the actual variable requires IR gen support.
  3164. case Decl::IndirectField:
  3165. break;
  3166. // C++ Decls
  3167. case Decl::Namespace:
  3168. EmitDeclContext(cast<NamespaceDecl>(D));
  3169. break;
  3170. case Decl::CXXRecord:
  3171. // Emit any static data members, they may be definitions.
  3172. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3173. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3174. EmitTopLevelDecl(I);
  3175. break;
  3176. // No code generation needed.
  3177. case Decl::UsingShadow:
  3178. case Decl::ClassTemplate:
  3179. case Decl::VarTemplate:
  3180. case Decl::VarTemplatePartialSpecialization:
  3181. case Decl::FunctionTemplate:
  3182. case Decl::TypeAliasTemplate:
  3183. case Decl::Block:
  3184. case Decl::Empty:
  3185. break;
  3186. case Decl::Using: // using X; [C++]
  3187. if (CGDebugInfo *DI = getModuleDebugInfo())
  3188. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3189. return;
  3190. case Decl::NamespaceAlias:
  3191. if (CGDebugInfo *DI = getModuleDebugInfo())
  3192. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3193. return;
  3194. case Decl::UsingDirective: // using namespace X; [C++]
  3195. if (CGDebugInfo *DI = getModuleDebugInfo())
  3196. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3197. return;
  3198. case Decl::CXXConstructor:
  3199. // Skip function templates
  3200. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3201. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3202. return;
  3203. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3204. break;
  3205. case Decl::CXXDestructor:
  3206. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  3207. return;
  3208. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3209. break;
  3210. case Decl::StaticAssert:
  3211. // Nothing to do.
  3212. break;
  3213. // Objective-C Decls
  3214. // Forward declarations, no (immediate) code generation.
  3215. case Decl::ObjCInterface:
  3216. case Decl::ObjCCategory:
  3217. break;
  3218. case Decl::ObjCProtocol: {
  3219. auto *Proto = cast<ObjCProtocolDecl>(D);
  3220. if (Proto->isThisDeclarationADefinition())
  3221. ObjCRuntime->GenerateProtocol(Proto);
  3222. break;
  3223. }
  3224. case Decl::ObjCCategoryImpl:
  3225. // Categories have properties but don't support synthesize so we
  3226. // can ignore them here.
  3227. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3228. break;
  3229. case Decl::ObjCImplementation: {
  3230. auto *OMD = cast<ObjCImplementationDecl>(D);
  3231. EmitObjCPropertyImplementations(OMD);
  3232. EmitObjCIvarInitializations(OMD);
  3233. ObjCRuntime->GenerateClass(OMD);
  3234. // Emit global variable debug information.
  3235. if (CGDebugInfo *DI = getModuleDebugInfo())
  3236. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3237. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3238. OMD->getClassInterface()), OMD->getLocation());
  3239. break;
  3240. }
  3241. case Decl::ObjCMethod: {
  3242. auto *OMD = cast<ObjCMethodDecl>(D);
  3243. // If this is not a prototype, emit the body.
  3244. if (OMD->getBody())
  3245. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3246. break;
  3247. }
  3248. case Decl::ObjCCompatibleAlias:
  3249. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3250. break;
  3251. case Decl::PragmaComment: {
  3252. const auto *PCD = cast<PragmaCommentDecl>(D);
  3253. switch (PCD->getCommentKind()) {
  3254. case PCK_Unknown:
  3255. llvm_unreachable("unexpected pragma comment kind");
  3256. case PCK_Linker:
  3257. AppendLinkerOptions(PCD->getArg());
  3258. break;
  3259. case PCK_Lib:
  3260. AddDependentLib(PCD->getArg());
  3261. break;
  3262. case PCK_Compiler:
  3263. case PCK_ExeStr:
  3264. case PCK_User:
  3265. break; // We ignore all of these.
  3266. }
  3267. break;
  3268. }
  3269. case Decl::PragmaDetectMismatch: {
  3270. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3271. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3272. break;
  3273. }
  3274. case Decl::LinkageSpec:
  3275. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3276. break;
  3277. case Decl::FileScopeAsm: {
  3278. // File-scope asm is ignored during device-side CUDA compilation.
  3279. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3280. break;
  3281. // File-scope asm is ignored during device-side OpenMP compilation.
  3282. if (LangOpts.OpenMPIsDevice)
  3283. break;
  3284. auto *AD = cast<FileScopeAsmDecl>(D);
  3285. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3286. break;
  3287. }
  3288. case Decl::Import: {
  3289. auto *Import = cast<ImportDecl>(D);
  3290. // If we've already imported this module, we're done.
  3291. if (!ImportedModules.insert(Import->getImportedModule()))
  3292. break;
  3293. // Emit debug information for direct imports.
  3294. if (!Import->getImportedOwningModule()) {
  3295. if (CGDebugInfo *DI = getModuleDebugInfo())
  3296. DI->EmitImportDecl(*Import);
  3297. }
  3298. // Find all of the submodules and emit the module initializers.
  3299. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3300. SmallVector<clang::Module *, 16> Stack;
  3301. Visited.insert(Import->getImportedModule());
  3302. Stack.push_back(Import->getImportedModule());
  3303. while (!Stack.empty()) {
  3304. clang::Module *Mod = Stack.pop_back_val();
  3305. if (!EmittedModuleInitializers.insert(Mod).second)
  3306. continue;
  3307. for (auto *D : Context.getModuleInitializers(Mod))
  3308. EmitTopLevelDecl(D);
  3309. // Visit the submodules of this module.
  3310. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3311. SubEnd = Mod->submodule_end();
  3312. Sub != SubEnd; ++Sub) {
  3313. // Skip explicit children; they need to be explicitly imported to emit
  3314. // the initializers.
  3315. if ((*Sub)->IsExplicit)
  3316. continue;
  3317. if (Visited.insert(*Sub).second)
  3318. Stack.push_back(*Sub);
  3319. }
  3320. }
  3321. break;
  3322. }
  3323. case Decl::Export:
  3324. EmitDeclContext(cast<ExportDecl>(D));
  3325. break;
  3326. case Decl::OMPThreadPrivate:
  3327. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3328. break;
  3329. case Decl::ClassTemplateSpecialization: {
  3330. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3331. if (DebugInfo &&
  3332. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3333. Spec->hasDefinition())
  3334. DebugInfo->completeTemplateDefinition(*Spec);
  3335. break;
  3336. }
  3337. case Decl::OMPDeclareReduction:
  3338. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3339. break;
  3340. default:
  3341. // Make sure we handled everything we should, every other kind is a
  3342. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3343. // function. Need to recode Decl::Kind to do that easily.
  3344. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3345. break;
  3346. }
  3347. }
  3348. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3349. // Do we need to generate coverage mapping?
  3350. if (!CodeGenOpts.CoverageMapping)
  3351. return;
  3352. switch (D->getKind()) {
  3353. case Decl::CXXConversion:
  3354. case Decl::CXXMethod:
  3355. case Decl::Function:
  3356. case Decl::ObjCMethod:
  3357. case Decl::CXXConstructor:
  3358. case Decl::CXXDestructor: {
  3359. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3360. return;
  3361. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3362. if (I == DeferredEmptyCoverageMappingDecls.end())
  3363. DeferredEmptyCoverageMappingDecls[D] = true;
  3364. break;
  3365. }
  3366. default:
  3367. break;
  3368. };
  3369. }
  3370. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3371. // Do we need to generate coverage mapping?
  3372. if (!CodeGenOpts.CoverageMapping)
  3373. return;
  3374. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3375. if (Fn->isTemplateInstantiation())
  3376. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3377. }
  3378. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3379. if (I == DeferredEmptyCoverageMappingDecls.end())
  3380. DeferredEmptyCoverageMappingDecls[D] = false;
  3381. else
  3382. I->second = false;
  3383. }
  3384. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3385. std::vector<const Decl *> DeferredDecls;
  3386. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3387. if (!I.second)
  3388. continue;
  3389. DeferredDecls.push_back(I.first);
  3390. }
  3391. // Sort the declarations by their location to make sure that the tests get a
  3392. // predictable order for the coverage mapping for the unused declarations.
  3393. if (CodeGenOpts.DumpCoverageMapping)
  3394. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3395. [] (const Decl *LHS, const Decl *RHS) {
  3396. return LHS->getLocStart() < RHS->getLocStart();
  3397. });
  3398. for (const auto *D : DeferredDecls) {
  3399. switch (D->getKind()) {
  3400. case Decl::CXXConversion:
  3401. case Decl::CXXMethod:
  3402. case Decl::Function:
  3403. case Decl::ObjCMethod: {
  3404. CodeGenPGO PGO(*this);
  3405. GlobalDecl GD(cast<FunctionDecl>(D));
  3406. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3407. getFunctionLinkage(GD));
  3408. break;
  3409. }
  3410. case Decl::CXXConstructor: {
  3411. CodeGenPGO PGO(*this);
  3412. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3413. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3414. getFunctionLinkage(GD));
  3415. break;
  3416. }
  3417. case Decl::CXXDestructor: {
  3418. CodeGenPGO PGO(*this);
  3419. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3420. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3421. getFunctionLinkage(GD));
  3422. break;
  3423. }
  3424. default:
  3425. break;
  3426. };
  3427. }
  3428. }
  3429. /// Turns the given pointer into a constant.
  3430. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3431. const void *Ptr) {
  3432. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3433. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3434. return llvm::ConstantInt::get(i64, PtrInt);
  3435. }
  3436. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3437. llvm::NamedMDNode *&GlobalMetadata,
  3438. GlobalDecl D,
  3439. llvm::GlobalValue *Addr) {
  3440. if (!GlobalMetadata)
  3441. GlobalMetadata =
  3442. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3443. // TODO: should we report variant information for ctors/dtors?
  3444. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3445. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3446. CGM.getLLVMContext(), D.getDecl()))};
  3447. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3448. }
  3449. /// For each function which is declared within an extern "C" region and marked
  3450. /// as 'used', but has internal linkage, create an alias from the unmangled
  3451. /// name to the mangled name if possible. People expect to be able to refer
  3452. /// to such functions with an unmangled name from inline assembly within the
  3453. /// same translation unit.
  3454. void CodeGenModule::EmitStaticExternCAliases() {
  3455. // Don't do anything if we're generating CUDA device code -- the NVPTX
  3456. // assembly target doesn't support aliases.
  3457. if (Context.getTargetInfo().getTriple().isNVPTX())
  3458. return;
  3459. for (auto &I : StaticExternCValues) {
  3460. IdentifierInfo *Name = I.first;
  3461. llvm::GlobalValue *Val = I.second;
  3462. if (Val && !getModule().getNamedValue(Name->getName()))
  3463. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3464. }
  3465. }
  3466. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3467. GlobalDecl &Result) const {
  3468. auto Res = Manglings.find(MangledName);
  3469. if (Res == Manglings.end())
  3470. return false;
  3471. Result = Res->getValue();
  3472. return true;
  3473. }
  3474. /// Emits metadata nodes associating all the global values in the
  3475. /// current module with the Decls they came from. This is useful for
  3476. /// projects using IR gen as a subroutine.
  3477. ///
  3478. /// Since there's currently no way to associate an MDNode directly
  3479. /// with an llvm::GlobalValue, we create a global named metadata
  3480. /// with the name 'clang.global.decl.ptrs'.
  3481. void CodeGenModule::EmitDeclMetadata() {
  3482. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3483. for (auto &I : MangledDeclNames) {
  3484. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3485. // Some mangled names don't necessarily have an associated GlobalValue
  3486. // in this module, e.g. if we mangled it for DebugInfo.
  3487. if (Addr)
  3488. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3489. }
  3490. }
  3491. /// Emits metadata nodes for all the local variables in the current
  3492. /// function.
  3493. void CodeGenFunction::EmitDeclMetadata() {
  3494. if (LocalDeclMap.empty()) return;
  3495. llvm::LLVMContext &Context = getLLVMContext();
  3496. // Find the unique metadata ID for this name.
  3497. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3498. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3499. for (auto &I : LocalDeclMap) {
  3500. const Decl *D = I.first;
  3501. llvm::Value *Addr = I.second.getPointer();
  3502. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3503. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3504. Alloca->setMetadata(
  3505. DeclPtrKind, llvm::MDNode::get(
  3506. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3507. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3508. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3509. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3510. }
  3511. }
  3512. }
  3513. void CodeGenModule::EmitVersionIdentMetadata() {
  3514. llvm::NamedMDNode *IdentMetadata =
  3515. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3516. std::string Version = getClangFullVersion();
  3517. llvm::LLVMContext &Ctx = TheModule.getContext();
  3518. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3519. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3520. }
  3521. void CodeGenModule::EmitTargetMetadata() {
  3522. // Warning, new MangledDeclNames may be appended within this loop.
  3523. // We rely on MapVector insertions adding new elements to the end
  3524. // of the container.
  3525. // FIXME: Move this loop into the one target that needs it, and only
  3526. // loop over those declarations for which we couldn't emit the target
  3527. // metadata when we emitted the declaration.
  3528. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3529. auto Val = *(MangledDeclNames.begin() + I);
  3530. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3531. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3532. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3533. }
  3534. }
  3535. void CodeGenModule::EmitCoverageFile() {
  3536. if (getCodeGenOpts().CoverageDataFile.empty() &&
  3537. getCodeGenOpts().CoverageNotesFile.empty())
  3538. return;
  3539. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  3540. if (!CUNode)
  3541. return;
  3542. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3543. llvm::LLVMContext &Ctx = TheModule.getContext();
  3544. auto *CoverageDataFile =
  3545. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  3546. auto *CoverageNotesFile =
  3547. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  3548. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3549. llvm::MDNode *CU = CUNode->getOperand(i);
  3550. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  3551. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3552. }
  3553. }
  3554. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3555. // Sema has checked that all uuid strings are of the form
  3556. // "12345678-1234-1234-1234-1234567890ab".
  3557. assert(Uuid.size() == 36);
  3558. for (unsigned i = 0; i < 36; ++i) {
  3559. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3560. else assert(isHexDigit(Uuid[i]));
  3561. }
  3562. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3563. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3564. llvm::Constant *Field3[8];
  3565. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3566. Field3[Idx] = llvm::ConstantInt::get(
  3567. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3568. llvm::Constant *Fields[4] = {
  3569. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3570. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3571. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3572. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3573. };
  3574. return llvm::ConstantStruct::getAnon(Fields);
  3575. }
  3576. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3577. bool ForEH) {
  3578. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3579. // FIXME: should we even be calling this method if RTTI is disabled
  3580. // and it's not for EH?
  3581. if (!ForEH && !getLangOpts().RTTI)
  3582. return llvm::Constant::getNullValue(Int8PtrTy);
  3583. if (ForEH && Ty->isObjCObjectPointerType() &&
  3584. LangOpts.ObjCRuntime.isGNUFamily())
  3585. return ObjCRuntime->GetEHType(Ty);
  3586. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3587. }
  3588. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3589. for (auto RefExpr : D->varlists()) {
  3590. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3591. bool PerformInit =
  3592. VD->getAnyInitializer() &&
  3593. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3594. /*ForRef=*/false);
  3595. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  3596. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3597. VD, Addr, RefExpr->getLocStart(), PerformInit))
  3598. CXXGlobalInits.push_back(InitFunction);
  3599. }
  3600. }
  3601. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  3602. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  3603. if (InternalId)
  3604. return InternalId;
  3605. if (isExternallyVisible(T->getLinkage())) {
  3606. std::string OutName;
  3607. llvm::raw_string_ostream Out(OutName);
  3608. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  3609. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  3610. } else {
  3611. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  3612. llvm::ArrayRef<llvm::Metadata *>());
  3613. }
  3614. return InternalId;
  3615. }
  3616. /// Returns whether this module needs the "all-vtables" type identifier.
  3617. bool CodeGenModule::NeedAllVtablesTypeId() const {
  3618. // Returns true if at least one of vtable-based CFI checkers is enabled and
  3619. // is not in the trapping mode.
  3620. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  3621. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  3622. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  3623. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  3624. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  3625. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  3626. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  3627. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  3628. }
  3629. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  3630. CharUnits Offset,
  3631. const CXXRecordDecl *RD) {
  3632. llvm::Metadata *MD =
  3633. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  3634. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3635. if (CodeGenOpts.SanitizeCfiCrossDso)
  3636. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  3637. VTable->addTypeMetadata(Offset.getQuantity(),
  3638. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  3639. if (NeedAllVtablesTypeId()) {
  3640. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  3641. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3642. }
  3643. }
  3644. // Fills in the supplied string map with the set of target features for the
  3645. // passed in function.
  3646. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  3647. const FunctionDecl *FD) {
  3648. StringRef TargetCPU = Target.getTargetOpts().CPU;
  3649. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  3650. // If we have a TargetAttr build up the feature map based on that.
  3651. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  3652. // Make a copy of the features as passed on the command line into the
  3653. // beginning of the additional features from the function to override.
  3654. ParsedAttr.first.insert(ParsedAttr.first.begin(),
  3655. Target.getTargetOpts().FeaturesAsWritten.begin(),
  3656. Target.getTargetOpts().FeaturesAsWritten.end());
  3657. if (ParsedAttr.second != "")
  3658. TargetCPU = ParsedAttr.second;
  3659. // Now populate the feature map, first with the TargetCPU which is either
  3660. // the default or a new one from the target attribute string. Then we'll use
  3661. // the passed in features (FeaturesAsWritten) along with the new ones from
  3662. // the attribute.
  3663. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
  3664. } else {
  3665. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  3666. Target.getTargetOpts().Features);
  3667. }
  3668. }
  3669. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  3670. if (!SanStats)
  3671. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  3672. return *SanStats;
  3673. }
  3674. llvm::Value *
  3675. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  3676. CodeGenFunction &CGF) {
  3677. llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
  3678. auto SamplerT = getOpenCLRuntime().getSamplerType();
  3679. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  3680. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  3681. "__translate_sampler_initializer"),
  3682. {C});
  3683. }