CodeGenModule.cpp 162 KB

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