CodeGenModule.cpp 123 KB

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