CodeGenModule.cpp 153 KB

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