CodeGenModule.cpp 125 KB

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