CodeGenModule.cpp 136 KB

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