CodeGenModule.cpp 124 KB

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