CodeGenModule.cpp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746
  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 "CGDebugInfo.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenTBAA.h"
  17. #include "CGCall.h"
  18. #include "CGCUDARuntime.h"
  19. #include "CGCXXABI.h"
  20. #include "CGObjCRuntime.h"
  21. #include "CGOpenCLRuntime.h"
  22. #include "TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "clang/AST/ASTContext.h"
  25. #include "clang/AST/CharUnits.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclCXX.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/Diagnostic.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "clang/Basic/ConvertUTF.h"
  37. #include "llvm/CallingConv.h"
  38. #include "llvm/Module.h"
  39. #include "llvm/Intrinsics.h"
  40. #include "llvm/LLVMContext.h"
  41. #include "llvm/ADT/APSInt.h"
  42. #include "llvm/ADT/Triple.h"
  43. #include "llvm/Target/Mangler.h"
  44. #include "llvm/Target/TargetData.h"
  45. #include "llvm/Support/CallSite.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. using namespace clang;
  48. using namespace CodeGen;
  49. static const char AnnotationSection[] = "llvm.metadata";
  50. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  51. switch (CGM.getContext().getTargetInfo().getCXXABI()) {
  52. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  53. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  54. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  55. }
  56. llvm_unreachable("invalid C++ ABI kind");
  57. }
  58. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  59. llvm::Module &M, const llvm::TargetData &TD,
  60. DiagnosticsEngine &diags)
  61. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  62. TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
  63. ABI(createCXXABI(*this)),
  64. Types(*this),
  65. TBAA(0),
  66. VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
  67. DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
  68. RRData(0), CFConstantStringClassRef(0),
  69. ConstantStringClassRef(0), NSConstantStringType(0),
  70. VMContext(M.getContext()),
  71. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  72. BlockObjectAssign(0), BlockObjectDispose(0),
  73. BlockDescriptorType(0), GenericBlockLiteralType(0) {
  74. // Initialize the type cache.
  75. llvm::LLVMContext &LLVMContext = M.getContext();
  76. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  77. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  78. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  79. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  80. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  81. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  82. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  83. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  84. PointerAlignInBytes =
  85. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  86. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  87. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  88. Int8PtrTy = Int8Ty->getPointerTo(0);
  89. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  90. if (LangOpts.ObjC1)
  91. createObjCRuntime();
  92. if (LangOpts.OpenCL)
  93. createOpenCLRuntime();
  94. if (LangOpts.CUDA)
  95. createCUDARuntime();
  96. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  97. if (LangOpts.ThreadSanitizer ||
  98. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  99. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  100. ABI.getMangleContext());
  101. // If debug info or coverage generation is enabled, create the CGDebugInfo
  102. // object.
  103. if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
  104. CodeGenOpts.EmitGcovArcs ||
  105. CodeGenOpts.EmitGcovNotes)
  106. DebugInfo = new CGDebugInfo(*this);
  107. Block.GlobalUniqueCount = 0;
  108. if (C.getLangOpts().ObjCAutoRefCount)
  109. ARCData = new ARCEntrypoints();
  110. RRData = new RREntrypoints();
  111. }
  112. CodeGenModule::~CodeGenModule() {
  113. delete ObjCRuntime;
  114. delete OpenCLRuntime;
  115. delete CUDARuntime;
  116. delete TheTargetCodeGenInfo;
  117. delete &ABI;
  118. delete TBAA;
  119. delete DebugInfo;
  120. delete ARCData;
  121. delete RRData;
  122. }
  123. void CodeGenModule::createObjCRuntime() {
  124. // This is just isGNUFamily(), but we want to force implementors of
  125. // new ABIs to decide how best to do this.
  126. switch (LangOpts.ObjCRuntime.getKind()) {
  127. case ObjCRuntime::GNUstep:
  128. case ObjCRuntime::GCC:
  129. ObjCRuntime = CreateGNUObjCRuntime(*this);
  130. return;
  131. case ObjCRuntime::FragileMacOSX:
  132. case ObjCRuntime::MacOSX:
  133. case ObjCRuntime::iOS:
  134. ObjCRuntime = CreateMacObjCRuntime(*this);
  135. return;
  136. }
  137. llvm_unreachable("bad runtime kind");
  138. }
  139. void CodeGenModule::createOpenCLRuntime() {
  140. OpenCLRuntime = new CGOpenCLRuntime(*this);
  141. }
  142. void CodeGenModule::createCUDARuntime() {
  143. CUDARuntime = CreateNVCUDARuntime(*this);
  144. }
  145. void CodeGenModule::Release() {
  146. EmitDeferred();
  147. EmitCXXGlobalInitFunc();
  148. EmitCXXGlobalDtorFunc();
  149. if (ObjCRuntime)
  150. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  151. AddGlobalCtor(ObjCInitFunction);
  152. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  153. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  154. EmitGlobalAnnotations();
  155. EmitLLVMUsed();
  156. SimplifyPersonality();
  157. if (getCodeGenOpts().EmitDeclMetadata)
  158. EmitDeclMetadata();
  159. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  160. EmitCoverageFile();
  161. if (DebugInfo)
  162. DebugInfo->finalize();
  163. }
  164. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  165. // Make sure that this type is translated.
  166. Types.UpdateCompletedType(TD);
  167. }
  168. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  169. if (!TBAA)
  170. return 0;
  171. return TBAA->getTBAAInfo(QTy);
  172. }
  173. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  174. if (!TBAA)
  175. return 0;
  176. return TBAA->getTBAAInfoForVTablePtr();
  177. }
  178. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  179. llvm::MDNode *TBAAInfo) {
  180. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  181. }
  182. bool CodeGenModule::isTargetDarwin() const {
  183. return getContext().getTargetInfo().getTriple().isOSDarwin();
  184. }
  185. void CodeGenModule::Error(SourceLocation loc, StringRef error) {
  186. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
  187. getDiags().Report(Context.getFullLoc(loc), diagID);
  188. }
  189. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  190. /// specified stmt yet.
  191. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  192. bool OmitOnError) {
  193. if (OmitOnError && getDiags().hasErrorOccurred())
  194. return;
  195. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  196. "cannot compile this %0 yet");
  197. std::string Msg = Type;
  198. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  199. << Msg << S->getSourceRange();
  200. }
  201. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  202. /// specified decl yet.
  203. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  204. bool OmitOnError) {
  205. if (OmitOnError && getDiags().hasErrorOccurred())
  206. return;
  207. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  208. "cannot compile this %0 yet");
  209. std::string Msg = Type;
  210. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  211. }
  212. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  213. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  214. }
  215. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  216. const NamedDecl *D) const {
  217. // Internal definitions always have default visibility.
  218. if (GV->hasLocalLinkage()) {
  219. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  220. return;
  221. }
  222. // Set visibility for definitions.
  223. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  224. if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  225. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  226. }
  227. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  228. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  229. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  230. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  231. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  232. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  233. }
  234. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  235. CodeGenOptions::TLSModel M) {
  236. switch (M) {
  237. case CodeGenOptions::GeneralDynamicTLSModel:
  238. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  239. case CodeGenOptions::LocalDynamicTLSModel:
  240. return llvm::GlobalVariable::LocalDynamicTLSModel;
  241. case CodeGenOptions::InitialExecTLSModel:
  242. return llvm::GlobalVariable::InitialExecTLSModel;
  243. case CodeGenOptions::LocalExecTLSModel:
  244. return llvm::GlobalVariable::LocalExecTLSModel;
  245. }
  246. llvm_unreachable("Invalid TLS model!");
  247. }
  248. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  249. const VarDecl &D) const {
  250. assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
  251. llvm::GlobalVariable::ThreadLocalMode TLM;
  252. TLM = GetLLVMTLSModel(CodeGenOpts.DefaultTLSModel);
  253. // Override the TLS model if it is explicitly specified.
  254. if (D.hasAttr<TLSModelAttr>()) {
  255. const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
  256. TLM = GetLLVMTLSModel(Attr->getModel());
  257. }
  258. GV->setThreadLocalMode(TLM);
  259. }
  260. /// Set the symbol visibility of type information (vtable and RTTI)
  261. /// associated with the given type.
  262. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  263. const CXXRecordDecl *RD,
  264. TypeVisibilityKind TVK) const {
  265. setGlobalVisibility(GV, RD);
  266. if (!CodeGenOpts.HiddenWeakVTables)
  267. return;
  268. // We never want to drop the visibility for RTTI names.
  269. if (TVK == TVK_ForRTTIName)
  270. return;
  271. // We want to drop the visibility to hidden for weak type symbols.
  272. // This isn't possible if there might be unresolved references
  273. // elsewhere that rely on this symbol being visible.
  274. // This should be kept roughly in sync with setThunkVisibility
  275. // in CGVTables.cpp.
  276. // Preconditions.
  277. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  278. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  279. return;
  280. // Don't override an explicit visibility attribute.
  281. if (RD->getExplicitVisibility())
  282. return;
  283. switch (RD->getTemplateSpecializationKind()) {
  284. // We have to disable the optimization if this is an EI definition
  285. // because there might be EI declarations in other shared objects.
  286. case TSK_ExplicitInstantiationDefinition:
  287. case TSK_ExplicitInstantiationDeclaration:
  288. return;
  289. // Every use of a non-template class's type information has to emit it.
  290. case TSK_Undeclared:
  291. break;
  292. // In theory, implicit instantiations can ignore the possibility of
  293. // an explicit instantiation declaration because there necessarily
  294. // must be an EI definition somewhere with default visibility. In
  295. // practice, it's possible to have an explicit instantiation for
  296. // an arbitrary template class, and linkers aren't necessarily able
  297. // to deal with mixed-visibility symbols.
  298. case TSK_ExplicitSpecialization:
  299. case TSK_ImplicitInstantiation:
  300. if (!CodeGenOpts.HiddenWeakTemplateVTables)
  301. return;
  302. break;
  303. }
  304. // If there's a key function, there may be translation units
  305. // that don't have the key function's definition. But ignore
  306. // this if we're emitting RTTI under -fno-rtti.
  307. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  308. if (Context.getKeyFunction(RD))
  309. return;
  310. }
  311. // Otherwise, drop the visibility to hidden.
  312. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  313. GV->setUnnamedAddr(true);
  314. }
  315. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  316. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  317. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  318. if (!Str.empty())
  319. return Str;
  320. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  321. IdentifierInfo *II = ND->getIdentifier();
  322. assert(II && "Attempt to mangle unnamed decl.");
  323. Str = II->getName();
  324. return Str;
  325. }
  326. SmallString<256> Buffer;
  327. llvm::raw_svector_ostream Out(Buffer);
  328. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  329. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  330. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  331. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  332. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  333. getCXXABI().getMangleContext().mangleBlock(BD, Out,
  334. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
  335. else
  336. getCXXABI().getMangleContext().mangleName(ND, Out);
  337. // Allocate space for the mangled name.
  338. Out.flush();
  339. size_t Length = Buffer.size();
  340. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  341. std::copy(Buffer.begin(), Buffer.end(), Name);
  342. Str = StringRef(Name, Length);
  343. return Str;
  344. }
  345. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  346. const BlockDecl *BD) {
  347. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  348. const Decl *D = GD.getDecl();
  349. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  350. if (D == 0)
  351. MangleCtx.mangleGlobalBlock(BD,
  352. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  353. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  354. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  355. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  356. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  357. else
  358. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  359. }
  360. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  361. return getModule().getNamedValue(Name);
  362. }
  363. /// AddGlobalCtor - Add a function to the list that will be called before
  364. /// main() runs.
  365. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  366. // FIXME: Type coercion of void()* types.
  367. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  368. }
  369. /// AddGlobalDtor - Add a function to the list that will be called
  370. /// when the module is unloaded.
  371. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  372. // FIXME: Type coercion of void()* types.
  373. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  374. }
  375. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  376. // Ctor function type is void()*.
  377. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  378. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  379. // Get the type of a ctor entry, { i32, void ()* }.
  380. llvm::StructType *CtorStructTy =
  381. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  382. // Construct the constructor and destructor arrays.
  383. SmallVector<llvm::Constant*, 8> Ctors;
  384. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  385. llvm::Constant *S[] = {
  386. llvm::ConstantInt::get(Int32Ty, I->second, false),
  387. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  388. };
  389. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  390. }
  391. if (!Ctors.empty()) {
  392. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  393. new llvm::GlobalVariable(TheModule, AT, false,
  394. llvm::GlobalValue::AppendingLinkage,
  395. llvm::ConstantArray::get(AT, Ctors),
  396. GlobalName);
  397. }
  398. }
  399. llvm::GlobalValue::LinkageTypes
  400. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  401. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  402. if (Linkage == GVA_Internal)
  403. return llvm::Function::InternalLinkage;
  404. if (D->hasAttr<DLLExportAttr>())
  405. return llvm::Function::DLLExportLinkage;
  406. if (D->hasAttr<WeakAttr>())
  407. return llvm::Function::WeakAnyLinkage;
  408. // In C99 mode, 'inline' functions are guaranteed to have a strong
  409. // definition somewhere else, so we can use available_externally linkage.
  410. if (Linkage == GVA_C99Inline)
  411. return llvm::Function::AvailableExternallyLinkage;
  412. // Note that Apple's kernel linker doesn't support symbol
  413. // coalescing, so we need to avoid linkonce and weak linkages there.
  414. // Normally, this means we just map to internal, but for explicit
  415. // instantiations we'll map to external.
  416. // In C++, the compiler has to emit a definition in every translation unit
  417. // that references the function. We should use linkonce_odr because
  418. // a) if all references in this translation unit are optimized away, we
  419. // don't need to codegen it. b) if the function persists, it needs to be
  420. // merged with other definitions. c) C++ has the ODR, so we know the
  421. // definition is dependable.
  422. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  423. return !Context.getLangOpts().AppleKext
  424. ? llvm::Function::LinkOnceODRLinkage
  425. : llvm::Function::InternalLinkage;
  426. // An explicit instantiation of a template has weak linkage, since
  427. // explicit instantiations can occur in multiple translation units
  428. // and must all be equivalent. However, we are not allowed to
  429. // throw away these explicit instantiations.
  430. if (Linkage == GVA_ExplicitTemplateInstantiation)
  431. return !Context.getLangOpts().AppleKext
  432. ? llvm::Function::WeakODRLinkage
  433. : llvm::Function::ExternalLinkage;
  434. // Otherwise, we have strong external linkage.
  435. assert(Linkage == GVA_StrongExternal);
  436. return llvm::Function::ExternalLinkage;
  437. }
  438. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  439. ///
  440. /// FIXME: This is currently only done for aliases and functions, but not for
  441. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  442. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  443. llvm::GlobalValue *GV) {
  444. SetCommonAttributes(D, GV);
  445. }
  446. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  447. const CGFunctionInfo &Info,
  448. llvm::Function *F) {
  449. unsigned CallingConv;
  450. AttributeListType AttributeList;
  451. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  452. F->setAttributes(llvm::AttrListPtr::get(AttributeList));
  453. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  454. }
  455. /// Determines whether the language options require us to model
  456. /// unwind exceptions. We treat -fexceptions as mandating this
  457. /// except under the fragile ObjC ABI with only ObjC exceptions
  458. /// enabled. This means, for example, that C with -fexceptions
  459. /// enables this.
  460. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  461. // If exceptions are completely disabled, obviously this is false.
  462. if (!LangOpts.Exceptions) return false;
  463. // If C++ exceptions are enabled, this is true.
  464. if (LangOpts.CXXExceptions) return true;
  465. // If ObjC exceptions are enabled, this depends on the ABI.
  466. if (LangOpts.ObjCExceptions) {
  467. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  468. }
  469. return true;
  470. }
  471. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  472. llvm::Function *F) {
  473. if (CodeGenOpts.UnwindTables)
  474. F->setHasUWTable();
  475. if (!hasUnwindExceptions(LangOpts))
  476. F->addFnAttr(llvm::Attribute::NoUnwind);
  477. if (D->hasAttr<NakedAttr>()) {
  478. // Naked implies noinline: we should not be inlining such functions.
  479. F->addFnAttr(llvm::Attribute::Naked);
  480. F->addFnAttr(llvm::Attribute::NoInline);
  481. }
  482. if (D->hasAttr<NoInlineAttr>())
  483. F->addFnAttr(llvm::Attribute::NoInline);
  484. // (noinline wins over always_inline, and we can't specify both in IR)
  485. if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
  486. !F->hasFnAttr(llvm::Attribute::NoInline))
  487. F->addFnAttr(llvm::Attribute::AlwaysInline);
  488. // FIXME: Communicate hot and cold attributes to LLVM more directly.
  489. if (D->hasAttr<ColdAttr>())
  490. F->addFnAttr(llvm::Attribute::OptimizeForSize);
  491. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  492. F->setUnnamedAddr(true);
  493. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  494. F->addFnAttr(llvm::Attribute::StackProtect);
  495. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  496. F->addFnAttr(llvm::Attribute::StackProtectReq);
  497. if (LangOpts.AddressSanitizer) {
  498. // When AddressSanitizer is enabled, set AddressSafety attribute
  499. // unless __attribute__((no_address_safety_analysis)) is used.
  500. if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
  501. F->addFnAttr(llvm::Attribute::AddressSafety);
  502. }
  503. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  504. if (alignment)
  505. F->setAlignment(alignment);
  506. // C++ ABI requires 2-byte alignment for member functions.
  507. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  508. F->setAlignment(2);
  509. }
  510. void CodeGenModule::SetCommonAttributes(const Decl *D,
  511. llvm::GlobalValue *GV) {
  512. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  513. setGlobalVisibility(GV, ND);
  514. else
  515. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  516. if (D->hasAttr<UsedAttr>())
  517. AddUsedGlobal(GV);
  518. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  519. GV->setSection(SA->getName());
  520. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  521. }
  522. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  523. llvm::Function *F,
  524. const CGFunctionInfo &FI) {
  525. SetLLVMFunctionAttributes(D, FI, F);
  526. SetLLVMFunctionAttributesForDefinition(D, F);
  527. F->setLinkage(llvm::Function::InternalLinkage);
  528. SetCommonAttributes(D, F);
  529. }
  530. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  531. llvm::Function *F,
  532. bool IsIncompleteFunction) {
  533. if (unsigned IID = F->getIntrinsicID()) {
  534. // If this is an intrinsic function, set the function's attributes
  535. // to the intrinsic's attributes.
  536. F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
  537. return;
  538. }
  539. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  540. if (!IsIncompleteFunction)
  541. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  542. // Only a few attributes are set on declarations; these may later be
  543. // overridden by a definition.
  544. if (FD->hasAttr<DLLImportAttr>()) {
  545. F->setLinkage(llvm::Function::DLLImportLinkage);
  546. } else if (FD->hasAttr<WeakAttr>() ||
  547. FD->isWeakImported()) {
  548. // "extern_weak" is overloaded in LLVM; we probably should have
  549. // separate linkage types for this.
  550. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  551. } else {
  552. F->setLinkage(llvm::Function::ExternalLinkage);
  553. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  554. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  555. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  556. }
  557. }
  558. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  559. F->setSection(SA->getName());
  560. }
  561. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  562. assert(!GV->isDeclaration() &&
  563. "Only globals with definition can force usage.");
  564. LLVMUsed.push_back(GV);
  565. }
  566. void CodeGenModule::EmitLLVMUsed() {
  567. // Don't create llvm.used if there is no need.
  568. if (LLVMUsed.empty())
  569. return;
  570. // Convert LLVMUsed to what ConstantArray needs.
  571. SmallVector<llvm::Constant*, 8> UsedArray;
  572. UsedArray.resize(LLVMUsed.size());
  573. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  574. UsedArray[i] =
  575. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  576. Int8PtrTy);
  577. }
  578. if (UsedArray.empty())
  579. return;
  580. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  581. llvm::GlobalVariable *GV =
  582. new llvm::GlobalVariable(getModule(), ATy, false,
  583. llvm::GlobalValue::AppendingLinkage,
  584. llvm::ConstantArray::get(ATy, UsedArray),
  585. "llvm.used");
  586. GV->setSection("llvm.metadata");
  587. }
  588. void CodeGenModule::EmitDeferred() {
  589. // Emit code for any potentially referenced deferred decls. Since a
  590. // previously unused static decl may become used during the generation of code
  591. // for a static function, iterate until no changes are made.
  592. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  593. if (!DeferredVTables.empty()) {
  594. const CXXRecordDecl *RD = DeferredVTables.back();
  595. DeferredVTables.pop_back();
  596. getCXXABI().EmitVTables(RD);
  597. continue;
  598. }
  599. GlobalDecl D = DeferredDeclsToEmit.back();
  600. DeferredDeclsToEmit.pop_back();
  601. // Check to see if we've already emitted this. This is necessary
  602. // for a couple of reasons: first, decls can end up in the
  603. // deferred-decls queue multiple times, and second, decls can end
  604. // up with definitions in unusual ways (e.g. by an extern inline
  605. // function acquiring a strong function redefinition). Just
  606. // ignore these cases.
  607. //
  608. // TODO: That said, looking this up multiple times is very wasteful.
  609. StringRef Name = getMangledName(D);
  610. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  611. assert(CGRef && "Deferred decl wasn't referenced?");
  612. if (!CGRef->isDeclaration())
  613. continue;
  614. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  615. // purposes an alias counts as a definition.
  616. if (isa<llvm::GlobalAlias>(CGRef))
  617. continue;
  618. // Otherwise, emit the definition and move on to the next one.
  619. EmitGlobalDefinition(D);
  620. }
  621. }
  622. void CodeGenModule::EmitGlobalAnnotations() {
  623. if (Annotations.empty())
  624. return;
  625. // Create a new global variable for the ConstantStruct in the Module.
  626. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  627. Annotations[0]->getType(), Annotations.size()), Annotations);
  628. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  629. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  630. "llvm.global.annotations");
  631. gv->setSection(AnnotationSection);
  632. }
  633. llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
  634. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  635. if (i != AnnotationStrings.end())
  636. return i->second;
  637. // Not found yet, create a new global.
  638. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  639. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  640. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  641. gv->setSection(AnnotationSection);
  642. gv->setUnnamedAddr(true);
  643. AnnotationStrings[Str] = gv;
  644. return gv;
  645. }
  646. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  647. SourceManager &SM = getContext().getSourceManager();
  648. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  649. if (PLoc.isValid())
  650. return EmitAnnotationString(PLoc.getFilename());
  651. return EmitAnnotationString(SM.getBufferName(Loc));
  652. }
  653. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  654. SourceManager &SM = getContext().getSourceManager();
  655. PresumedLoc PLoc = SM.getPresumedLoc(L);
  656. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  657. SM.getExpansionLineNumber(L);
  658. return llvm::ConstantInt::get(Int32Ty, LineNo);
  659. }
  660. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  661. const AnnotateAttr *AA,
  662. SourceLocation L) {
  663. // Get the globals for file name, annotation, and the line number.
  664. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  665. *UnitGV = EmitAnnotationUnit(L),
  666. *LineNoCst = EmitAnnotationLineNo(L);
  667. // Create the ConstantStruct for the global annotation.
  668. llvm::Constant *Fields[4] = {
  669. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  670. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  671. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  672. LineNoCst
  673. };
  674. return llvm::ConstantStruct::getAnon(Fields);
  675. }
  676. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  677. llvm::GlobalValue *GV) {
  678. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  679. // Get the struct elements for these annotations.
  680. for (specific_attr_iterator<AnnotateAttr>
  681. ai = D->specific_attr_begin<AnnotateAttr>(),
  682. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  683. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  684. }
  685. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  686. // Never defer when EmitAllDecls is specified.
  687. if (LangOpts.EmitAllDecls)
  688. return false;
  689. return !getContext().DeclMustBeEmitted(Global);
  690. }
  691. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  692. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  693. assert(AA && "No alias?");
  694. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  695. // See if there is already something with the target's name in the module.
  696. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  697. llvm::Constant *Aliasee;
  698. if (isa<llvm::FunctionType>(DeclTy))
  699. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  700. /*ForVTable=*/false);
  701. else
  702. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  703. llvm::PointerType::getUnqual(DeclTy), 0);
  704. if (!Entry) {
  705. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  706. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  707. WeakRefReferences.insert(F);
  708. }
  709. return Aliasee;
  710. }
  711. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  712. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  713. // Weak references don't produce any output by themselves.
  714. if (Global->hasAttr<WeakRefAttr>())
  715. return;
  716. // If this is an alias definition (which otherwise looks like a declaration)
  717. // emit it now.
  718. if (Global->hasAttr<AliasAttr>())
  719. return EmitAliasDefinition(GD);
  720. // If this is CUDA, be selective about which declarations we emit.
  721. if (LangOpts.CUDA) {
  722. if (CodeGenOpts.CUDAIsDevice) {
  723. if (!Global->hasAttr<CUDADeviceAttr>() &&
  724. !Global->hasAttr<CUDAGlobalAttr>() &&
  725. !Global->hasAttr<CUDAConstantAttr>() &&
  726. !Global->hasAttr<CUDASharedAttr>())
  727. return;
  728. } else {
  729. if (!Global->hasAttr<CUDAHostAttr>() && (
  730. Global->hasAttr<CUDADeviceAttr>() ||
  731. Global->hasAttr<CUDAConstantAttr>() ||
  732. Global->hasAttr<CUDASharedAttr>()))
  733. return;
  734. }
  735. }
  736. // Ignore declarations, they will be emitted on their first use.
  737. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  738. // Forward declarations are emitted lazily on first use.
  739. if (!FD->doesThisDeclarationHaveABody()) {
  740. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  741. return;
  742. const FunctionDecl *InlineDefinition = 0;
  743. FD->getBody(InlineDefinition);
  744. StringRef MangledName = getMangledName(GD);
  745. DeferredDecls.erase(MangledName);
  746. EmitGlobalDefinition(InlineDefinition);
  747. return;
  748. }
  749. } else {
  750. const VarDecl *VD = cast<VarDecl>(Global);
  751. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  752. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  753. return;
  754. }
  755. // Defer code generation when possible if this is a static definition, inline
  756. // function etc. These we only want to emit if they are used.
  757. if (!MayDeferGeneration(Global)) {
  758. // Emit the definition if it can't be deferred.
  759. EmitGlobalDefinition(GD);
  760. return;
  761. }
  762. // If we're deferring emission of a C++ variable with an
  763. // initializer, remember the order in which it appeared in the file.
  764. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  765. cast<VarDecl>(Global)->hasInit()) {
  766. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  767. CXXGlobalInits.push_back(0);
  768. }
  769. // If the value has already been used, add it directly to the
  770. // DeferredDeclsToEmit list.
  771. StringRef MangledName = getMangledName(GD);
  772. if (GetGlobalValue(MangledName))
  773. DeferredDeclsToEmit.push_back(GD);
  774. else {
  775. // Otherwise, remember that we saw a deferred decl with this name. The
  776. // first use of the mangled name will cause it to move into
  777. // DeferredDeclsToEmit.
  778. DeferredDecls[MangledName] = GD;
  779. }
  780. }
  781. namespace {
  782. struct FunctionIsDirectlyRecursive :
  783. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  784. const StringRef Name;
  785. const Builtin::Context &BI;
  786. bool Result;
  787. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  788. Name(N), BI(C), Result(false) {
  789. }
  790. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  791. bool TraverseCallExpr(CallExpr *E) {
  792. const FunctionDecl *FD = E->getDirectCallee();
  793. if (!FD)
  794. return true;
  795. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  796. if (Attr && Name == Attr->getLabel()) {
  797. Result = true;
  798. return false;
  799. }
  800. unsigned BuiltinID = FD->getBuiltinID();
  801. if (!BuiltinID)
  802. return true;
  803. StringRef BuiltinName = BI.GetName(BuiltinID);
  804. if (BuiltinName.startswith("__builtin_") &&
  805. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  806. Result = true;
  807. return false;
  808. }
  809. return true;
  810. }
  811. };
  812. }
  813. // isTriviallyRecursive - Check if this function calls another
  814. // decl that, because of the asm attribute or the other decl being a builtin,
  815. // ends up pointing to itself.
  816. bool
  817. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  818. StringRef Name;
  819. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  820. // asm labels are a special kind of mangling we have to support.
  821. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  822. if (!Attr)
  823. return false;
  824. Name = Attr->getLabel();
  825. } else {
  826. Name = FD->getName();
  827. }
  828. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  829. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  830. return Walker.Result;
  831. }
  832. bool
  833. CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
  834. if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
  835. return true;
  836. if (CodeGenOpts.OptimizationLevel == 0 &&
  837. !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
  838. return false;
  839. // PR9614. Avoid cases where the source code is lying to us. An available
  840. // externally function should have an equivalent function somewhere else,
  841. // but a function that calls itself is clearly not equivalent to the real
  842. // implementation.
  843. // This happens in glibc's btowc and in some configure checks.
  844. return !isTriviallyRecursive(F);
  845. }
  846. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  847. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  848. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  849. Context.getSourceManager(),
  850. "Generating code for declaration");
  851. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  852. // At -O0, don't generate IR for functions with available_externally
  853. // linkage.
  854. if (!shouldEmitFunction(Function))
  855. return;
  856. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  857. // Make sure to emit the definition(s) before we emit the thunks.
  858. // This is necessary for the generation of certain thunks.
  859. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  860. EmitCXXConstructor(CD, GD.getCtorType());
  861. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  862. EmitCXXDestructor(DD, GD.getDtorType());
  863. else
  864. EmitGlobalFunctionDefinition(GD);
  865. if (Method->isVirtual())
  866. getVTables().EmitThunks(GD);
  867. return;
  868. }
  869. return EmitGlobalFunctionDefinition(GD);
  870. }
  871. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  872. return EmitGlobalVarDefinition(VD);
  873. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  874. }
  875. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  876. /// module, create and return an llvm Function with the specified type. If there
  877. /// is something in the module with the specified name, return it potentially
  878. /// bitcasted to the right type.
  879. ///
  880. /// If D is non-null, it specifies a decl that correspond to this. This is used
  881. /// to set the attributes on the function when it is first created.
  882. llvm::Constant *
  883. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  884. llvm::Type *Ty,
  885. GlobalDecl D, bool ForVTable,
  886. llvm::Attributes ExtraAttrs) {
  887. // Lookup the entry, lazily creating it if necessary.
  888. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  889. if (Entry) {
  890. if (WeakRefReferences.count(Entry)) {
  891. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  892. if (FD && !FD->hasAttr<WeakAttr>())
  893. Entry->setLinkage(llvm::Function::ExternalLinkage);
  894. WeakRefReferences.erase(Entry);
  895. }
  896. if (Entry->getType()->getElementType() == Ty)
  897. return Entry;
  898. // Make sure the result is of the correct type.
  899. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  900. }
  901. // This function doesn't have a complete type (for example, the return
  902. // type is an incomplete struct). Use a fake type instead, and make
  903. // sure not to try to set attributes.
  904. bool IsIncompleteFunction = false;
  905. llvm::FunctionType *FTy;
  906. if (isa<llvm::FunctionType>(Ty)) {
  907. FTy = cast<llvm::FunctionType>(Ty);
  908. } else {
  909. FTy = llvm::FunctionType::get(VoidTy, false);
  910. IsIncompleteFunction = true;
  911. }
  912. llvm::Function *F = llvm::Function::Create(FTy,
  913. llvm::Function::ExternalLinkage,
  914. MangledName, &getModule());
  915. assert(F->getName() == MangledName && "name was uniqued!");
  916. if (D.getDecl())
  917. SetFunctionAttributes(D, F, IsIncompleteFunction);
  918. if (ExtraAttrs != llvm::Attribute::None)
  919. F->addFnAttr(ExtraAttrs);
  920. // This is the first use or definition of a mangled name. If there is a
  921. // deferred decl with this name, remember that we need to emit it at the end
  922. // of the file.
  923. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  924. if (DDI != DeferredDecls.end()) {
  925. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  926. // list, and remove it from DeferredDecls (since we don't need it anymore).
  927. DeferredDeclsToEmit.push_back(DDI->second);
  928. DeferredDecls.erase(DDI);
  929. // Otherwise, there are cases we have to worry about where we're
  930. // using a declaration for which we must emit a definition but where
  931. // we might not find a top-level definition:
  932. // - member functions defined inline in their classes
  933. // - friend functions defined inline in some class
  934. // - special member functions with implicit definitions
  935. // If we ever change our AST traversal to walk into class methods,
  936. // this will be unnecessary.
  937. //
  938. // We also don't emit a definition for a function if it's going to be an entry
  939. // in a vtable, unless it's already marked as used.
  940. } else if (getLangOpts().CPlusPlus && D.getDecl()) {
  941. // Look for a declaration that's lexically in a record.
  942. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  943. FD = FD->getMostRecentDecl();
  944. do {
  945. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  946. if (FD->isImplicit() && !ForVTable) {
  947. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  948. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  949. break;
  950. } else if (FD->doesThisDeclarationHaveABody()) {
  951. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  952. break;
  953. }
  954. }
  955. FD = FD->getPreviousDecl();
  956. } while (FD);
  957. }
  958. // Make sure the result is of the requested type.
  959. if (!IsIncompleteFunction) {
  960. assert(F->getType()->getElementType() == Ty);
  961. return F;
  962. }
  963. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  964. return llvm::ConstantExpr::getBitCast(F, PTy);
  965. }
  966. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  967. /// non-null, then this function will use the specified type if it has to
  968. /// create it (this occurs when we see a definition of the function).
  969. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  970. llvm::Type *Ty,
  971. bool ForVTable) {
  972. // If there was no specific requested type, just convert it now.
  973. if (!Ty)
  974. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  975. StringRef MangledName = getMangledName(GD);
  976. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  977. }
  978. /// CreateRuntimeFunction - Create a new runtime function with the specified
  979. /// type and name.
  980. llvm::Constant *
  981. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  982. StringRef Name,
  983. llvm::Attributes ExtraAttrs) {
  984. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  985. ExtraAttrs);
  986. }
  987. /// isTypeConstant - Determine whether an object of this type can be emitted
  988. /// as a constant.
  989. ///
  990. /// If ExcludeCtor is true, the duration when the object's constructor runs
  991. /// will not be considered. The caller will need to verify that the object is
  992. /// not written to during its construction.
  993. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  994. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  995. return false;
  996. if (Context.getLangOpts().CPlusPlus) {
  997. if (const CXXRecordDecl *Record
  998. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  999. return ExcludeCtor && !Record->hasMutableFields() &&
  1000. Record->hasTrivialDestructor();
  1001. }
  1002. return true;
  1003. }
  1004. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1005. /// create and return an llvm GlobalVariable with the specified type. If there
  1006. /// is something in the module with the specified name, return it potentially
  1007. /// bitcasted to the right type.
  1008. ///
  1009. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1010. /// to set the attributes on the global when it is first created.
  1011. llvm::Constant *
  1012. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1013. llvm::PointerType *Ty,
  1014. const VarDecl *D,
  1015. bool UnnamedAddr) {
  1016. // Lookup the entry, lazily creating it if necessary.
  1017. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1018. if (Entry) {
  1019. if (WeakRefReferences.count(Entry)) {
  1020. if (D && !D->hasAttr<WeakAttr>())
  1021. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1022. WeakRefReferences.erase(Entry);
  1023. }
  1024. if (UnnamedAddr)
  1025. Entry->setUnnamedAddr(true);
  1026. if (Entry->getType() == Ty)
  1027. return Entry;
  1028. // Make sure the result is of the correct type.
  1029. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1030. }
  1031. // This is the first use or definition of a mangled name. If there is a
  1032. // deferred decl with this name, remember that we need to emit it at the end
  1033. // of the file.
  1034. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1035. if (DDI != DeferredDecls.end()) {
  1036. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1037. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1038. DeferredDeclsToEmit.push_back(DDI->second);
  1039. DeferredDecls.erase(DDI);
  1040. }
  1041. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1042. llvm::GlobalVariable *GV =
  1043. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  1044. llvm::GlobalValue::ExternalLinkage,
  1045. 0, MangledName, 0,
  1046. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1047. // Handle things which are present even on external declarations.
  1048. if (D) {
  1049. // FIXME: This code is overly simple and should be merged with other global
  1050. // handling.
  1051. GV->setConstant(isTypeConstant(D->getType(), false));
  1052. // Set linkage and visibility in case we never see a definition.
  1053. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  1054. if (LV.linkage() != ExternalLinkage) {
  1055. // Don't set internal linkage on declarations.
  1056. } else {
  1057. if (D->hasAttr<DLLImportAttr>())
  1058. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1059. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1060. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1061. // Set visibility on a declaration only if it's explicit.
  1062. if (LV.visibilityExplicit())
  1063. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  1064. }
  1065. if (D->isThreadSpecified())
  1066. setTLSMode(GV, *D);
  1067. }
  1068. if (AddrSpace != Ty->getAddressSpace())
  1069. return llvm::ConstantExpr::getBitCast(GV, Ty);
  1070. else
  1071. return GV;
  1072. }
  1073. llvm::GlobalVariable *
  1074. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1075. llvm::Type *Ty,
  1076. llvm::GlobalValue::LinkageTypes Linkage) {
  1077. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1078. llvm::GlobalVariable *OldGV = 0;
  1079. if (GV) {
  1080. // Check if the variable has the right type.
  1081. if (GV->getType()->getElementType() == Ty)
  1082. return GV;
  1083. // Because C++ name mangling, the only way we can end up with an already
  1084. // existing global with the same name is if it has been declared extern "C".
  1085. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1086. OldGV = GV;
  1087. }
  1088. // Create a new variable.
  1089. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1090. Linkage, 0, Name);
  1091. if (OldGV) {
  1092. // Replace occurrences of the old variable if needed.
  1093. GV->takeName(OldGV);
  1094. if (!OldGV->use_empty()) {
  1095. llvm::Constant *NewPtrForOldDecl =
  1096. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1097. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1098. }
  1099. OldGV->eraseFromParent();
  1100. }
  1101. return GV;
  1102. }
  1103. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1104. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1105. /// then it will be created with the specified type instead of whatever the
  1106. /// normal requested type would be.
  1107. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1108. llvm::Type *Ty) {
  1109. assert(D->hasGlobalStorage() && "Not a global variable");
  1110. QualType ASTTy = D->getType();
  1111. if (Ty == 0)
  1112. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1113. llvm::PointerType *PTy =
  1114. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1115. StringRef MangledName = getMangledName(D);
  1116. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1117. }
  1118. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1119. /// specified type and name.
  1120. llvm::Constant *
  1121. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1122. StringRef Name) {
  1123. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1124. true);
  1125. }
  1126. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1127. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1128. if (MayDeferGeneration(D)) {
  1129. // If we have not seen a reference to this variable yet, place it
  1130. // into the deferred declarations table to be emitted if needed
  1131. // later.
  1132. StringRef MangledName = getMangledName(D);
  1133. if (!GetGlobalValue(MangledName)) {
  1134. DeferredDecls[MangledName] = D;
  1135. return;
  1136. }
  1137. }
  1138. // The tentative definition is the only definition.
  1139. EmitGlobalVarDefinition(D);
  1140. }
  1141. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  1142. if (DefinitionRequired)
  1143. getCXXABI().EmitVTables(Class);
  1144. }
  1145. llvm::GlobalVariable::LinkageTypes
  1146. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  1147. if (RD->getLinkage() != ExternalLinkage)
  1148. return llvm::GlobalVariable::InternalLinkage;
  1149. if (const CXXMethodDecl *KeyFunction
  1150. = RD->getASTContext().getKeyFunction(RD)) {
  1151. // If this class has a key function, use that to determine the linkage of
  1152. // the vtable.
  1153. const FunctionDecl *Def = 0;
  1154. if (KeyFunction->hasBody(Def))
  1155. KeyFunction = cast<CXXMethodDecl>(Def);
  1156. switch (KeyFunction->getTemplateSpecializationKind()) {
  1157. case TSK_Undeclared:
  1158. case TSK_ExplicitSpecialization:
  1159. // When compiling with optimizations turned on, we emit all vtables,
  1160. // even if the key function is not defined in the current translation
  1161. // unit. If this is the case, use available_externally linkage.
  1162. if (!Def && CodeGenOpts.OptimizationLevel)
  1163. return llvm::GlobalVariable::AvailableExternallyLinkage;
  1164. if (KeyFunction->isInlined())
  1165. return !Context.getLangOpts().AppleKext ?
  1166. llvm::GlobalVariable::LinkOnceODRLinkage :
  1167. llvm::Function::InternalLinkage;
  1168. return llvm::GlobalVariable::ExternalLinkage;
  1169. case TSK_ImplicitInstantiation:
  1170. return !Context.getLangOpts().AppleKext ?
  1171. llvm::GlobalVariable::LinkOnceODRLinkage :
  1172. llvm::Function::InternalLinkage;
  1173. case TSK_ExplicitInstantiationDefinition:
  1174. return !Context.getLangOpts().AppleKext ?
  1175. llvm::GlobalVariable::WeakODRLinkage :
  1176. llvm::Function::InternalLinkage;
  1177. case TSK_ExplicitInstantiationDeclaration:
  1178. // FIXME: Use available_externally linkage. However, this currently
  1179. // breaks LLVM's build due to undefined symbols.
  1180. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1181. return !Context.getLangOpts().AppleKext ?
  1182. llvm::GlobalVariable::LinkOnceODRLinkage :
  1183. llvm::Function::InternalLinkage;
  1184. }
  1185. }
  1186. if (Context.getLangOpts().AppleKext)
  1187. return llvm::Function::InternalLinkage;
  1188. switch (RD->getTemplateSpecializationKind()) {
  1189. case TSK_Undeclared:
  1190. case TSK_ExplicitSpecialization:
  1191. case TSK_ImplicitInstantiation:
  1192. // FIXME: Use available_externally linkage. However, this currently
  1193. // breaks LLVM's build due to undefined symbols.
  1194. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1195. case TSK_ExplicitInstantiationDeclaration:
  1196. return llvm::GlobalVariable::LinkOnceODRLinkage;
  1197. case TSK_ExplicitInstantiationDefinition:
  1198. return llvm::GlobalVariable::WeakODRLinkage;
  1199. }
  1200. llvm_unreachable("Invalid TemplateSpecializationKind!");
  1201. }
  1202. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1203. return Context.toCharUnitsFromBits(
  1204. TheTargetData.getTypeStoreSizeInBits(Ty));
  1205. }
  1206. llvm::Constant *
  1207. CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
  1208. const Expr *rawInit) {
  1209. ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
  1210. if (const ExprWithCleanups *withCleanups =
  1211. dyn_cast<ExprWithCleanups>(rawInit)) {
  1212. cleanups = withCleanups->getObjects();
  1213. rawInit = withCleanups->getSubExpr();
  1214. }
  1215. const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
  1216. if (!init || !init->initializesStdInitializerList() ||
  1217. init->getNumInits() == 0)
  1218. return 0;
  1219. ASTContext &ctx = getContext();
  1220. unsigned numInits = init->getNumInits();
  1221. // FIXME: This check is here because we would otherwise silently miscompile
  1222. // nested global std::initializer_lists. Better would be to have a real
  1223. // implementation.
  1224. for (unsigned i = 0; i < numInits; ++i) {
  1225. const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
  1226. if (inner && inner->initializesStdInitializerList()) {
  1227. ErrorUnsupported(inner, "nested global std::initializer_list");
  1228. return 0;
  1229. }
  1230. }
  1231. // Synthesize a fake VarDecl for the array and initialize that.
  1232. QualType elementType = init->getInit(0)->getType();
  1233. llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
  1234. QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
  1235. ArrayType::Normal, 0);
  1236. IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
  1237. TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
  1238. arrayType, D->getLocation());
  1239. VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
  1240. D->getDeclContext()),
  1241. D->getLocStart(), D->getLocation(),
  1242. name, arrayType, sourceInfo,
  1243. SC_Static, SC_Static);
  1244. // Now clone the InitListExpr to initialize the array instead.
  1245. // Incredible hack: we want to use the existing InitListExpr here, so we need
  1246. // to tell it that it no longer initializes a std::initializer_list.
  1247. Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
  1248. const_cast<InitListExpr*>(init)->getInits(),
  1249. init->getNumInits(),
  1250. init->getRBraceLoc());
  1251. arrayInit->setType(arrayType);
  1252. if (!cleanups.empty())
  1253. arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
  1254. backingArray->setInit(arrayInit);
  1255. // Emit the definition of the array.
  1256. EmitGlobalVarDefinition(backingArray);
  1257. // Inspect the initializer list to validate it and determine its type.
  1258. // FIXME: doing this every time is probably inefficient; caching would be nice
  1259. RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
  1260. RecordDecl::field_iterator field = record->field_begin();
  1261. if (field == record->field_end()) {
  1262. ErrorUnsupported(D, "weird std::initializer_list");
  1263. return 0;
  1264. }
  1265. QualType elementPtr = ctx.getPointerType(elementType.withConst());
  1266. // Start pointer.
  1267. if (!ctx.hasSameType(field->getType(), elementPtr)) {
  1268. ErrorUnsupported(D, "weird std::initializer_list");
  1269. return 0;
  1270. }
  1271. ++field;
  1272. if (field == record->field_end()) {
  1273. ErrorUnsupported(D, "weird std::initializer_list");
  1274. return 0;
  1275. }
  1276. bool isStartEnd = false;
  1277. if (ctx.hasSameType(field->getType(), elementPtr)) {
  1278. // End pointer.
  1279. isStartEnd = true;
  1280. } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
  1281. ErrorUnsupported(D, "weird std::initializer_list");
  1282. return 0;
  1283. }
  1284. // Now build an APValue representing the std::initializer_list.
  1285. APValue initListValue(APValue::UninitStruct(), 0, 2);
  1286. APValue &startField = initListValue.getStructField(0);
  1287. APValue::LValuePathEntry startOffsetPathEntry;
  1288. startOffsetPathEntry.ArrayIndex = 0;
  1289. startField = APValue(APValue::LValueBase(backingArray),
  1290. CharUnits::fromQuantity(0),
  1291. llvm::makeArrayRef(startOffsetPathEntry),
  1292. /*IsOnePastTheEnd=*/false, 0);
  1293. if (isStartEnd) {
  1294. APValue &endField = initListValue.getStructField(1);
  1295. APValue::LValuePathEntry endOffsetPathEntry;
  1296. endOffsetPathEntry.ArrayIndex = numInits;
  1297. endField = APValue(APValue::LValueBase(backingArray),
  1298. ctx.getTypeSizeInChars(elementType) * numInits,
  1299. llvm::makeArrayRef(endOffsetPathEntry),
  1300. /*IsOnePastTheEnd=*/true, 0);
  1301. } else {
  1302. APValue &sizeField = initListValue.getStructField(1);
  1303. sizeField = APValue(llvm::APSInt(numElements));
  1304. }
  1305. // Emit the constant for the initializer_list.
  1306. llvm::Constant *llvmInit =
  1307. EmitConstantValueForMemory(initListValue, D->getType());
  1308. assert(llvmInit && "failed to initialize as constant");
  1309. return llvmInit;
  1310. }
  1311. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1312. unsigned AddrSpace) {
  1313. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1314. if (D->hasAttr<CUDAConstantAttr>())
  1315. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1316. else if (D->hasAttr<CUDASharedAttr>())
  1317. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1318. else
  1319. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1320. }
  1321. return AddrSpace;
  1322. }
  1323. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1324. llvm::Constant *Init = 0;
  1325. QualType ASTTy = D->getType();
  1326. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1327. bool NeedsGlobalCtor = false;
  1328. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1329. const VarDecl *InitDecl;
  1330. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1331. if (!InitExpr) {
  1332. // This is a tentative definition; tentative definitions are
  1333. // implicitly initialized with { 0 }.
  1334. //
  1335. // Note that tentative definitions are only emitted at the end of
  1336. // a translation unit, so they should never have incomplete
  1337. // type. In addition, EmitTentativeDefinition makes sure that we
  1338. // never attempt to emit a tentative definition if a real one
  1339. // exists. A use may still exists, however, so we still may need
  1340. // to do a RAUW.
  1341. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1342. Init = EmitNullConstant(D->getType());
  1343. } else {
  1344. // If this is a std::initializer_list, emit the special initializer.
  1345. Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
  1346. // An empty init list will perform zero-initialization, which happens
  1347. // to be exactly what we want.
  1348. // FIXME: It does so in a global constructor, which is *not* what we
  1349. // want.
  1350. if (!Init) {
  1351. initializedGlobalDecl = GlobalDecl(D);
  1352. Init = EmitConstantInit(*InitDecl);
  1353. }
  1354. if (!Init) {
  1355. QualType T = InitExpr->getType();
  1356. if (D->getType()->isReferenceType())
  1357. T = D->getType();
  1358. if (getLangOpts().CPlusPlus) {
  1359. Init = EmitNullConstant(T);
  1360. NeedsGlobalCtor = true;
  1361. } else {
  1362. ErrorUnsupported(D, "static initializer");
  1363. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1364. }
  1365. } else {
  1366. // We don't need an initializer, so remove the entry for the delayed
  1367. // initializer position (just in case this entry was delayed) if we
  1368. // also don't need to register a destructor.
  1369. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1370. DelayedCXXInitPosition.erase(D);
  1371. }
  1372. }
  1373. llvm::Type* InitType = Init->getType();
  1374. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1375. // Strip off a bitcast if we got one back.
  1376. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1377. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1378. // all zero index gep.
  1379. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1380. Entry = CE->getOperand(0);
  1381. }
  1382. // Entry is now either a Function or GlobalVariable.
  1383. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1384. // We have a definition after a declaration with the wrong type.
  1385. // We must make a new GlobalVariable* and update everything that used OldGV
  1386. // (a declaration or tentative definition) with the new GlobalVariable*
  1387. // (which will be a definition).
  1388. //
  1389. // This happens if there is a prototype for a global (e.g.
  1390. // "extern int x[];") and then a definition of a different type (e.g.
  1391. // "int x[10];"). This also happens when an initializer has a different type
  1392. // from the type of the global (this happens with unions).
  1393. if (GV == 0 ||
  1394. GV->getType()->getElementType() != InitType ||
  1395. GV->getType()->getAddressSpace() !=
  1396. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1397. // Move the old entry aside so that we'll create a new one.
  1398. Entry->setName(StringRef());
  1399. // Make a new global with the correct type, this is now guaranteed to work.
  1400. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1401. // Replace all uses of the old global with the new global
  1402. llvm::Constant *NewPtrForOldDecl =
  1403. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1404. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1405. // Erase the old global, since it is no longer used.
  1406. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1407. }
  1408. if (D->hasAttr<AnnotateAttr>())
  1409. AddGlobalAnnotations(D, GV);
  1410. GV->setInitializer(Init);
  1411. // If it is safe to mark the global 'constant', do so now.
  1412. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1413. isTypeConstant(D->getType(), true));
  1414. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1415. // Set the llvm linkage type as appropriate.
  1416. llvm::GlobalValue::LinkageTypes Linkage =
  1417. GetLLVMLinkageVarDefinition(D, GV);
  1418. GV->setLinkage(Linkage);
  1419. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1420. // common vars aren't constant even if declared const.
  1421. GV->setConstant(false);
  1422. SetCommonAttributes(D, GV);
  1423. // Emit the initializer function if necessary.
  1424. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1425. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1426. // Emit global variable debug information.
  1427. if (CGDebugInfo *DI = getModuleDebugInfo())
  1428. if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
  1429. DI->EmitGlobalVariable(GV, D);
  1430. }
  1431. llvm::GlobalValue::LinkageTypes
  1432. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1433. llvm::GlobalVariable *GV) {
  1434. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1435. if (Linkage == GVA_Internal)
  1436. return llvm::Function::InternalLinkage;
  1437. else if (D->hasAttr<DLLImportAttr>())
  1438. return llvm::Function::DLLImportLinkage;
  1439. else if (D->hasAttr<DLLExportAttr>())
  1440. return llvm::Function::DLLExportLinkage;
  1441. else if (D->hasAttr<WeakAttr>()) {
  1442. if (GV->isConstant())
  1443. return llvm::GlobalVariable::WeakODRLinkage;
  1444. else
  1445. return llvm::GlobalVariable::WeakAnyLinkage;
  1446. } else if (Linkage == GVA_TemplateInstantiation ||
  1447. Linkage == GVA_ExplicitTemplateInstantiation)
  1448. return llvm::GlobalVariable::WeakODRLinkage;
  1449. else if (!getLangOpts().CPlusPlus &&
  1450. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1451. D->getAttr<CommonAttr>()) &&
  1452. !D->hasExternalStorage() && !D->getInit() &&
  1453. !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
  1454. !D->getAttr<WeakImportAttr>()) {
  1455. // Thread local vars aren't considered common linkage.
  1456. return llvm::GlobalVariable::CommonLinkage;
  1457. }
  1458. return llvm::GlobalVariable::ExternalLinkage;
  1459. }
  1460. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1461. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1462. /// existing call uses of the old function in the module, this adjusts them to
  1463. /// call the new function directly.
  1464. ///
  1465. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1466. /// functions to be able to inline them. If there is a bitcast in the way, it
  1467. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1468. /// run at -O0.
  1469. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1470. llvm::Function *NewFn) {
  1471. // If we're redefining a global as a function, don't transform it.
  1472. llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
  1473. if (OldFn == 0) return;
  1474. llvm::Type *NewRetTy = NewFn->getReturnType();
  1475. SmallVector<llvm::Value*, 4> ArgList;
  1476. for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
  1477. UI != E; ) {
  1478. // TODO: Do invokes ever occur in C code? If so, we should handle them too.
  1479. llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
  1480. llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
  1481. if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
  1482. llvm::CallSite CS(CI);
  1483. if (!CI || !CS.isCallee(I)) continue;
  1484. // If the return types don't match exactly, and if the call isn't dead, then
  1485. // we can't transform this call.
  1486. if (CI->getType() != NewRetTy && !CI->use_empty())
  1487. continue;
  1488. // Get the attribute list.
  1489. llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
  1490. llvm::AttrListPtr AttrList = CI->getAttributes();
  1491. // Get any return attributes.
  1492. llvm::Attributes RAttrs = AttrList.getRetAttributes();
  1493. // Add the return attributes.
  1494. if (RAttrs)
  1495. AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
  1496. // If the function was passed too few arguments, don't transform. If extra
  1497. // arguments were passed, we silently drop them. If any of the types
  1498. // mismatch, we don't transform.
  1499. unsigned ArgNo = 0;
  1500. bool DontTransform = false;
  1501. for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
  1502. E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
  1503. if (CS.arg_size() == ArgNo ||
  1504. CS.getArgument(ArgNo)->getType() != AI->getType()) {
  1505. DontTransform = true;
  1506. break;
  1507. }
  1508. // Add any parameter attributes.
  1509. if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
  1510. AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
  1511. }
  1512. if (DontTransform)
  1513. continue;
  1514. if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
  1515. AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
  1516. // Okay, we can transform this. Create the new call instruction and copy
  1517. // over the required information.
  1518. ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
  1519. llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
  1520. ArgList.clear();
  1521. if (!NewCall->getType()->isVoidTy())
  1522. NewCall->takeName(CI);
  1523. NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
  1524. NewCall->setCallingConv(CI->getCallingConv());
  1525. // Finally, remove the old call, replacing any uses with the new one.
  1526. if (!CI->use_empty())
  1527. CI->replaceAllUsesWith(NewCall);
  1528. // Copy debug location attached to CI.
  1529. if (!CI->getDebugLoc().isUnknown())
  1530. NewCall->setDebugLoc(CI->getDebugLoc());
  1531. CI->eraseFromParent();
  1532. }
  1533. }
  1534. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1535. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1536. // If we have a definition, this might be a deferred decl. If the
  1537. // instantiation is explicit, make sure we emit it at the end.
  1538. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1539. GetAddrOfGlobalVar(VD);
  1540. }
  1541. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1542. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1543. // Compute the function info and LLVM type.
  1544. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1545. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1546. // Get or create the prototype for the function.
  1547. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1548. // Strip off a bitcast if we got one back.
  1549. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1550. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1551. Entry = CE->getOperand(0);
  1552. }
  1553. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1554. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1555. // If the types mismatch then we have to rewrite the definition.
  1556. assert(OldFn->isDeclaration() &&
  1557. "Shouldn't replace non-declaration");
  1558. // F is the Function* for the one with the wrong type, we must make a new
  1559. // Function* and update everything that used F (a declaration) with the new
  1560. // Function* (which will be a definition).
  1561. //
  1562. // This happens if there is a prototype for a function
  1563. // (e.g. "int f()") and then a definition of a different type
  1564. // (e.g. "int f(int x)"). Move the old function aside so that it
  1565. // doesn't interfere with GetAddrOfFunction.
  1566. OldFn->setName(StringRef());
  1567. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1568. // If this is an implementation of a function without a prototype, try to
  1569. // replace any existing uses of the function (which may be calls) with uses
  1570. // of the new function
  1571. if (D->getType()->isFunctionNoProtoType()) {
  1572. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1573. OldFn->removeDeadConstantUsers();
  1574. }
  1575. // Replace uses of F with the Function we will endow with a body.
  1576. if (!Entry->use_empty()) {
  1577. llvm::Constant *NewPtrForOldDecl =
  1578. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1579. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1580. }
  1581. // Ok, delete the old function now, which is dead.
  1582. OldFn->eraseFromParent();
  1583. Entry = NewFn;
  1584. }
  1585. // We need to set linkage and visibility on the function before
  1586. // generating code for it because various parts of IR generation
  1587. // want to propagate this information down (e.g. to local static
  1588. // declarations).
  1589. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1590. setFunctionLinkage(D, Fn);
  1591. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1592. setGlobalVisibility(Fn, D);
  1593. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1594. SetFunctionDefinitionAttributes(D, Fn);
  1595. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1596. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1597. AddGlobalCtor(Fn, CA->getPriority());
  1598. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1599. AddGlobalDtor(Fn, DA->getPriority());
  1600. if (D->hasAttr<AnnotateAttr>())
  1601. AddGlobalAnnotations(D, Fn);
  1602. }
  1603. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1604. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1605. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1606. assert(AA && "Not an alias?");
  1607. StringRef MangledName = getMangledName(GD);
  1608. // If there is a definition in the module, then it wins over the alias.
  1609. // This is dubious, but allow it to be safe. Just ignore the alias.
  1610. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1611. if (Entry && !Entry->isDeclaration())
  1612. return;
  1613. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1614. // Create a reference to the named value. This ensures that it is emitted
  1615. // if a deferred decl.
  1616. llvm::Constant *Aliasee;
  1617. if (isa<llvm::FunctionType>(DeclTy))
  1618. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  1619. /*ForVTable=*/false);
  1620. else
  1621. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1622. llvm::PointerType::getUnqual(DeclTy), 0);
  1623. // Create the new alias itself, but don't set a name yet.
  1624. llvm::GlobalValue *GA =
  1625. new llvm::GlobalAlias(Aliasee->getType(),
  1626. llvm::Function::ExternalLinkage,
  1627. "", Aliasee, &getModule());
  1628. if (Entry) {
  1629. assert(Entry->isDeclaration());
  1630. // If there is a declaration in the module, then we had an extern followed
  1631. // by the alias, as in:
  1632. // extern int test6();
  1633. // ...
  1634. // int test6() __attribute__((alias("test7")));
  1635. //
  1636. // Remove it and replace uses of it with the alias.
  1637. GA->takeName(Entry);
  1638. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1639. Entry->getType()));
  1640. Entry->eraseFromParent();
  1641. } else {
  1642. GA->setName(MangledName);
  1643. }
  1644. // Set attributes which are particular to an alias; this is a
  1645. // specialization of the attributes which may be set on a global
  1646. // variable/function.
  1647. if (D->hasAttr<DLLExportAttr>()) {
  1648. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1649. // The dllexport attribute is ignored for undefined symbols.
  1650. if (FD->hasBody())
  1651. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1652. } else {
  1653. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1654. }
  1655. } else if (D->hasAttr<WeakAttr>() ||
  1656. D->hasAttr<WeakRefAttr>() ||
  1657. D->isWeakImported()) {
  1658. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1659. }
  1660. SetCommonAttributes(D, GA);
  1661. }
  1662. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1663. ArrayRef<llvm::Type*> Tys) {
  1664. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1665. Tys);
  1666. }
  1667. static llvm::StringMapEntry<llvm::Constant*> &
  1668. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1669. const StringLiteral *Literal,
  1670. bool TargetIsLSB,
  1671. bool &IsUTF16,
  1672. unsigned &StringLength) {
  1673. StringRef String = Literal->getString();
  1674. unsigned NumBytes = String.size();
  1675. // Check for simple case.
  1676. if (!Literal->containsNonAsciiOrNull()) {
  1677. StringLength = NumBytes;
  1678. return Map.GetOrCreateValue(String);
  1679. }
  1680. // Otherwise, convert the UTF8 literals into a string of shorts.
  1681. IsUTF16 = true;
  1682. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1683. const UTF8 *FromPtr = (UTF8 *)String.data();
  1684. UTF16 *ToPtr = &ToBuf[0];
  1685. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1686. &ToPtr, ToPtr + NumBytes,
  1687. strictConversion);
  1688. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1689. StringLength = ToPtr - &ToBuf[0];
  1690. // Add an explicit null.
  1691. *ToPtr = 0;
  1692. return Map.
  1693. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1694. (StringLength + 1) * 2));
  1695. }
  1696. static llvm::StringMapEntry<llvm::Constant*> &
  1697. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1698. const StringLiteral *Literal,
  1699. unsigned &StringLength) {
  1700. StringRef String = Literal->getString();
  1701. StringLength = String.size();
  1702. return Map.GetOrCreateValue(String);
  1703. }
  1704. llvm::Constant *
  1705. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1706. unsigned StringLength = 0;
  1707. bool isUTF16 = false;
  1708. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1709. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1710. getTargetData().isLittleEndian(),
  1711. isUTF16, StringLength);
  1712. if (llvm::Constant *C = Entry.getValue())
  1713. return C;
  1714. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1715. llvm::Constant *Zeros[] = { Zero, Zero };
  1716. // If we don't already have it, get __CFConstantStringClassReference.
  1717. if (!CFConstantStringClassRef) {
  1718. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1719. Ty = llvm::ArrayType::get(Ty, 0);
  1720. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1721. "__CFConstantStringClassReference");
  1722. // Decay array -> ptr
  1723. CFConstantStringClassRef =
  1724. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1725. }
  1726. QualType CFTy = getContext().getCFConstantStringType();
  1727. llvm::StructType *STy =
  1728. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1729. llvm::Constant *Fields[4];
  1730. // Class pointer.
  1731. Fields[0] = CFConstantStringClassRef;
  1732. // Flags.
  1733. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1734. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1735. llvm::ConstantInt::get(Ty, 0x07C8);
  1736. // String pointer.
  1737. llvm::Constant *C = 0;
  1738. if (isUTF16) {
  1739. ArrayRef<uint16_t> Arr =
  1740. llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
  1741. Entry.getKey().size() / 2);
  1742. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1743. } else {
  1744. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1745. }
  1746. llvm::GlobalValue::LinkageTypes Linkage;
  1747. if (isUTF16)
  1748. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1749. Linkage = llvm::GlobalValue::InternalLinkage;
  1750. else
  1751. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1752. // when using private linkage. It is not clear if this is a bug in ld
  1753. // or a reasonable new restriction.
  1754. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1755. // Note: -fwritable-strings doesn't make the backing store strings of
  1756. // CFStrings writable. (See <rdar://problem/10657500>)
  1757. llvm::GlobalVariable *GV =
  1758. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1759. Linkage, C, ".str");
  1760. GV->setUnnamedAddr(true);
  1761. if (isUTF16) {
  1762. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1763. GV->setAlignment(Align.getQuantity());
  1764. } else {
  1765. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1766. GV->setAlignment(Align.getQuantity());
  1767. }
  1768. // String.
  1769. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1770. if (isUTF16)
  1771. // Cast the UTF16 string to the correct type.
  1772. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1773. // String length.
  1774. Ty = getTypes().ConvertType(getContext().LongTy);
  1775. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1776. // The struct.
  1777. C = llvm::ConstantStruct::get(STy, Fields);
  1778. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1779. llvm::GlobalVariable::PrivateLinkage, C,
  1780. "_unnamed_cfstring_");
  1781. if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
  1782. GV->setSection(Sect);
  1783. Entry.setValue(GV);
  1784. return GV;
  1785. }
  1786. static RecordDecl *
  1787. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1788. DeclContext *DC, IdentifierInfo *Id) {
  1789. SourceLocation Loc;
  1790. if (Ctx.getLangOpts().CPlusPlus)
  1791. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1792. else
  1793. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1794. }
  1795. llvm::Constant *
  1796. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1797. unsigned StringLength = 0;
  1798. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1799. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1800. if (llvm::Constant *C = Entry.getValue())
  1801. return C;
  1802. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1803. llvm::Constant *Zeros[] = { Zero, Zero };
  1804. // If we don't already have it, get _NSConstantStringClassReference.
  1805. if (!ConstantStringClassRef) {
  1806. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  1807. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1808. llvm::Constant *GV;
  1809. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1810. std::string str =
  1811. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  1812. : "OBJC_CLASS_$_" + StringClass;
  1813. GV = getObjCRuntime().GetClassGlobal(str);
  1814. // Make sure the result is of the correct type.
  1815. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1816. ConstantStringClassRef =
  1817. llvm::ConstantExpr::getBitCast(GV, PTy);
  1818. } else {
  1819. std::string str =
  1820. StringClass.empty() ? "_NSConstantStringClassReference"
  1821. : "_" + StringClass + "ClassReference";
  1822. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  1823. GV = CreateRuntimeVariable(PTy, str);
  1824. // Decay array -> ptr
  1825. ConstantStringClassRef =
  1826. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1827. }
  1828. }
  1829. if (!NSConstantStringType) {
  1830. // Construct the type for a constant NSString.
  1831. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1832. Context.getTranslationUnitDecl(),
  1833. &Context.Idents.get("__builtin_NSString"));
  1834. D->startDefinition();
  1835. QualType FieldTypes[3];
  1836. // const int *isa;
  1837. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  1838. // const char *str;
  1839. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  1840. // unsigned int length;
  1841. FieldTypes[2] = Context.UnsignedIntTy;
  1842. // Create fields
  1843. for (unsigned i = 0; i < 3; ++i) {
  1844. FieldDecl *Field = FieldDecl::Create(Context, D,
  1845. SourceLocation(),
  1846. SourceLocation(), 0,
  1847. FieldTypes[i], /*TInfo=*/0,
  1848. /*BitWidth=*/0,
  1849. /*Mutable=*/false,
  1850. ICIS_NoInit);
  1851. Field->setAccess(AS_public);
  1852. D->addDecl(Field);
  1853. }
  1854. D->completeDefinition();
  1855. QualType NSTy = Context.getTagDeclType(D);
  1856. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1857. }
  1858. llvm::Constant *Fields[3];
  1859. // Class pointer.
  1860. Fields[0] = ConstantStringClassRef;
  1861. // String pointer.
  1862. llvm::Constant *C =
  1863. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1864. llvm::GlobalValue::LinkageTypes Linkage;
  1865. bool isConstant;
  1866. Linkage = llvm::GlobalValue::PrivateLinkage;
  1867. isConstant = !LangOpts.WritableStrings;
  1868. llvm::GlobalVariable *GV =
  1869. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1870. ".str");
  1871. GV->setUnnamedAddr(true);
  1872. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1873. GV->setAlignment(Align.getQuantity());
  1874. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1875. // String length.
  1876. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1877. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1878. // The struct.
  1879. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  1880. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1881. llvm::GlobalVariable::PrivateLinkage, C,
  1882. "_unnamed_nsstring_");
  1883. // FIXME. Fix section.
  1884. if (const char *Sect =
  1885. LangOpts.ObjCRuntime.isNonFragile()
  1886. ? getContext().getTargetInfo().getNSStringNonFragileABISection()
  1887. : getContext().getTargetInfo().getNSStringSection())
  1888. GV->setSection(Sect);
  1889. Entry.setValue(GV);
  1890. return GV;
  1891. }
  1892. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  1893. if (ObjCFastEnumerationStateType.isNull()) {
  1894. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1895. Context.getTranslationUnitDecl(),
  1896. &Context.Idents.get("__objcFastEnumerationState"));
  1897. D->startDefinition();
  1898. QualType FieldTypes[] = {
  1899. Context.UnsignedLongTy,
  1900. Context.getPointerType(Context.getObjCIdType()),
  1901. Context.getPointerType(Context.UnsignedLongTy),
  1902. Context.getConstantArrayType(Context.UnsignedLongTy,
  1903. llvm::APInt(32, 5), ArrayType::Normal, 0)
  1904. };
  1905. for (size_t i = 0; i < 4; ++i) {
  1906. FieldDecl *Field = FieldDecl::Create(Context,
  1907. D,
  1908. SourceLocation(),
  1909. SourceLocation(), 0,
  1910. FieldTypes[i], /*TInfo=*/0,
  1911. /*BitWidth=*/0,
  1912. /*Mutable=*/false,
  1913. ICIS_NoInit);
  1914. Field->setAccess(AS_public);
  1915. D->addDecl(Field);
  1916. }
  1917. D->completeDefinition();
  1918. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  1919. }
  1920. return ObjCFastEnumerationStateType;
  1921. }
  1922. llvm::Constant *
  1923. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  1924. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  1925. // Don't emit it as the address of the string, emit the string data itself
  1926. // as an inline array.
  1927. if (E->getCharByteWidth() == 1) {
  1928. SmallString<64> Str(E->getString());
  1929. // Resize the string to the right size, which is indicated by its type.
  1930. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  1931. Str.resize(CAT->getSize().getZExtValue());
  1932. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  1933. }
  1934. llvm::ArrayType *AType =
  1935. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  1936. llvm::Type *ElemTy = AType->getElementType();
  1937. unsigned NumElements = AType->getNumElements();
  1938. // Wide strings have either 2-byte or 4-byte elements.
  1939. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  1940. SmallVector<uint16_t, 32> Elements;
  1941. Elements.reserve(NumElements);
  1942. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1943. Elements.push_back(E->getCodeUnit(i));
  1944. Elements.resize(NumElements);
  1945. return llvm::ConstantDataArray::get(VMContext, Elements);
  1946. }
  1947. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  1948. SmallVector<uint32_t, 32> Elements;
  1949. Elements.reserve(NumElements);
  1950. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1951. Elements.push_back(E->getCodeUnit(i));
  1952. Elements.resize(NumElements);
  1953. return llvm::ConstantDataArray::get(VMContext, Elements);
  1954. }
  1955. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  1956. /// constant array for the given string literal.
  1957. llvm::Constant *
  1958. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  1959. CharUnits Align = getContext().getTypeAlignInChars(S->getType());
  1960. if (S->isAscii() || S->isUTF8()) {
  1961. SmallString<64> Str(S->getString());
  1962. // Resize the string to the right size, which is indicated by its type.
  1963. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  1964. Str.resize(CAT->getSize().getZExtValue());
  1965. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  1966. }
  1967. // FIXME: the following does not memoize wide strings.
  1968. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  1969. llvm::GlobalVariable *GV =
  1970. new llvm::GlobalVariable(getModule(),C->getType(),
  1971. !LangOpts.WritableStrings,
  1972. llvm::GlobalValue::PrivateLinkage,
  1973. C,".str");
  1974. GV->setAlignment(Align.getQuantity());
  1975. GV->setUnnamedAddr(true);
  1976. return GV;
  1977. }
  1978. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  1979. /// array for the given ObjCEncodeExpr node.
  1980. llvm::Constant *
  1981. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  1982. std::string Str;
  1983. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1984. return GetAddrOfConstantCString(Str);
  1985. }
  1986. /// GenerateWritableString -- Creates storage for a string literal.
  1987. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  1988. bool constant,
  1989. CodeGenModule &CGM,
  1990. const char *GlobalName,
  1991. unsigned Alignment) {
  1992. // Create Constant for this string literal. Don't add a '\0'.
  1993. llvm::Constant *C =
  1994. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  1995. // Create a global variable for this string
  1996. llvm::GlobalVariable *GV =
  1997. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  1998. llvm::GlobalValue::PrivateLinkage,
  1999. C, GlobalName);
  2000. GV->setAlignment(Alignment);
  2001. GV->setUnnamedAddr(true);
  2002. return GV;
  2003. }
  2004. /// GetAddrOfConstantString - Returns a pointer to a character array
  2005. /// containing the literal. This contents are exactly that of the
  2006. /// given string, i.e. it will not be null terminated automatically;
  2007. /// see GetAddrOfConstantCString. Note that whether the result is
  2008. /// actually a pointer to an LLVM constant depends on
  2009. /// Feature.WriteableStrings.
  2010. ///
  2011. /// The result has pointer to array type.
  2012. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2013. const char *GlobalName,
  2014. unsigned Alignment) {
  2015. // Get the default prefix if a name wasn't specified.
  2016. if (!GlobalName)
  2017. GlobalName = ".str";
  2018. // Don't share any string literals if strings aren't constant.
  2019. if (LangOpts.WritableStrings)
  2020. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2021. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2022. ConstantStringMap.GetOrCreateValue(Str);
  2023. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2024. if (Alignment > GV->getAlignment()) {
  2025. GV->setAlignment(Alignment);
  2026. }
  2027. return GV;
  2028. }
  2029. // Create a global variable for this.
  2030. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2031. Alignment);
  2032. Entry.setValue(GV);
  2033. return GV;
  2034. }
  2035. /// GetAddrOfConstantCString - Returns a pointer to a character
  2036. /// array containing the literal and a terminating '\0'
  2037. /// character. The result has pointer to array type.
  2038. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2039. const char *GlobalName,
  2040. unsigned Alignment) {
  2041. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2042. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2043. }
  2044. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2045. /// properties for an implementation.
  2046. void CodeGenModule::EmitObjCPropertyImplementations(const
  2047. ObjCImplementationDecl *D) {
  2048. for (ObjCImplementationDecl::propimpl_iterator
  2049. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2050. ObjCPropertyImplDecl *PID = *i;
  2051. // Dynamic is just for type-checking.
  2052. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2053. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2054. // Determine which methods need to be implemented, some may have
  2055. // been overridden. Note that ::isSynthesized is not the method
  2056. // we want, that just indicates if the decl came from a
  2057. // property. What we want to know is if the method is defined in
  2058. // this implementation.
  2059. if (!D->getInstanceMethod(PD->getGetterName()))
  2060. CodeGenFunction(*this).GenerateObjCGetter(
  2061. const_cast<ObjCImplementationDecl *>(D), PID);
  2062. if (!PD->isReadOnly() &&
  2063. !D->getInstanceMethod(PD->getSetterName()))
  2064. CodeGenFunction(*this).GenerateObjCSetter(
  2065. const_cast<ObjCImplementationDecl *>(D), PID);
  2066. }
  2067. }
  2068. }
  2069. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2070. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2071. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2072. ivar; ivar = ivar->getNextIvar())
  2073. if (ivar->getType().isDestructedType())
  2074. return true;
  2075. return false;
  2076. }
  2077. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2078. /// for an implementation.
  2079. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2080. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2081. if (needsDestructMethod(D)) {
  2082. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2083. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2084. ObjCMethodDecl *DTORMethod =
  2085. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2086. cxxSelector, getContext().VoidTy, 0, D,
  2087. /*isInstance=*/true, /*isVariadic=*/false,
  2088. /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
  2089. /*isDefined=*/false, ObjCMethodDecl::Required);
  2090. D->addInstanceMethod(DTORMethod);
  2091. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2092. D->setHasCXXStructors(true);
  2093. }
  2094. // If the implementation doesn't have any ivar initializers, we don't need
  2095. // a .cxx_construct.
  2096. if (D->getNumIvarInitializers() == 0)
  2097. return;
  2098. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2099. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2100. // The constructor returns 'self'.
  2101. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2102. D->getLocation(),
  2103. D->getLocation(),
  2104. cxxSelector,
  2105. getContext().getObjCIdType(), 0,
  2106. D, /*isInstance=*/true,
  2107. /*isVariadic=*/false,
  2108. /*isSynthesized=*/true,
  2109. /*isImplicitlyDeclared=*/true,
  2110. /*isDefined=*/false,
  2111. ObjCMethodDecl::Required);
  2112. D->addInstanceMethod(CTORMethod);
  2113. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2114. D->setHasCXXStructors(true);
  2115. }
  2116. /// EmitNamespace - Emit all declarations in a namespace.
  2117. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2118. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2119. I != E; ++I)
  2120. EmitTopLevelDecl(*I);
  2121. }
  2122. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2123. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2124. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2125. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2126. ErrorUnsupported(LSD, "linkage spec");
  2127. return;
  2128. }
  2129. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2130. I != E; ++I)
  2131. EmitTopLevelDecl(*I);
  2132. }
  2133. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2134. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2135. // If an error has occurred, stop code generation, but continue
  2136. // parsing and semantic analysis (to ensure all warnings and errors
  2137. // are emitted).
  2138. if (Diags.hasErrorOccurred())
  2139. return;
  2140. // Ignore dependent declarations.
  2141. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2142. return;
  2143. switch (D->getKind()) {
  2144. case Decl::CXXConversion:
  2145. case Decl::CXXMethod:
  2146. case Decl::Function:
  2147. // Skip function templates
  2148. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2149. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2150. return;
  2151. EmitGlobal(cast<FunctionDecl>(D));
  2152. break;
  2153. case Decl::Var:
  2154. EmitGlobal(cast<VarDecl>(D));
  2155. break;
  2156. // Indirect fields from global anonymous structs and unions can be
  2157. // ignored; only the actual variable requires IR gen support.
  2158. case Decl::IndirectField:
  2159. break;
  2160. // C++ Decls
  2161. case Decl::Namespace:
  2162. EmitNamespace(cast<NamespaceDecl>(D));
  2163. break;
  2164. // No code generation needed.
  2165. case Decl::UsingShadow:
  2166. case Decl::Using:
  2167. case Decl::UsingDirective:
  2168. case Decl::ClassTemplate:
  2169. case Decl::FunctionTemplate:
  2170. case Decl::TypeAliasTemplate:
  2171. case Decl::NamespaceAlias:
  2172. case Decl::Block:
  2173. case Decl::Import:
  2174. break;
  2175. case Decl::CXXConstructor:
  2176. // Skip function templates
  2177. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2178. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2179. return;
  2180. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2181. break;
  2182. case Decl::CXXDestructor:
  2183. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2184. return;
  2185. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2186. break;
  2187. case Decl::StaticAssert:
  2188. // Nothing to do.
  2189. break;
  2190. // Objective-C Decls
  2191. // Forward declarations, no (immediate) code generation.
  2192. case Decl::ObjCInterface:
  2193. break;
  2194. case Decl::ObjCCategory: {
  2195. ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
  2196. if (CD->IsClassExtension() && CD->hasSynthBitfield())
  2197. Context.ResetObjCLayout(CD->getClassInterface());
  2198. break;
  2199. }
  2200. case Decl::ObjCProtocol: {
  2201. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2202. if (Proto->isThisDeclarationADefinition())
  2203. ObjCRuntime->GenerateProtocol(Proto);
  2204. break;
  2205. }
  2206. case Decl::ObjCCategoryImpl:
  2207. // Categories have properties but don't support synthesize so we
  2208. // can ignore them here.
  2209. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2210. break;
  2211. case Decl::ObjCImplementation: {
  2212. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2213. if (LangOpts.ObjCRuntime.isNonFragile() && OMD->hasSynthBitfield())
  2214. Context.ResetObjCLayout(OMD->getClassInterface());
  2215. EmitObjCPropertyImplementations(OMD);
  2216. EmitObjCIvarInitializations(OMD);
  2217. ObjCRuntime->GenerateClass(OMD);
  2218. // Emit global variable debug information.
  2219. if (CGDebugInfo *DI = getModuleDebugInfo())
  2220. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
  2221. OMD->getLocation());
  2222. break;
  2223. }
  2224. case Decl::ObjCMethod: {
  2225. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2226. // If this is not a prototype, emit the body.
  2227. if (OMD->getBody())
  2228. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2229. break;
  2230. }
  2231. case Decl::ObjCCompatibleAlias:
  2232. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2233. break;
  2234. case Decl::LinkageSpec:
  2235. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2236. break;
  2237. case Decl::FileScopeAsm: {
  2238. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2239. StringRef AsmString = AD->getAsmString()->getString();
  2240. const std::string &S = getModule().getModuleInlineAsm();
  2241. if (S.empty())
  2242. getModule().setModuleInlineAsm(AsmString);
  2243. else if (*--S.end() == '\n')
  2244. getModule().setModuleInlineAsm(S + AsmString.str());
  2245. else
  2246. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2247. break;
  2248. }
  2249. default:
  2250. // Make sure we handled everything we should, every other kind is a
  2251. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2252. // function. Need to recode Decl::Kind to do that easily.
  2253. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2254. }
  2255. }
  2256. /// Turns the given pointer into a constant.
  2257. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2258. const void *Ptr) {
  2259. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2260. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2261. return llvm::ConstantInt::get(i64, PtrInt);
  2262. }
  2263. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2264. llvm::NamedMDNode *&GlobalMetadata,
  2265. GlobalDecl D,
  2266. llvm::GlobalValue *Addr) {
  2267. if (!GlobalMetadata)
  2268. GlobalMetadata =
  2269. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2270. // TODO: should we report variant information for ctors/dtors?
  2271. llvm::Value *Ops[] = {
  2272. Addr,
  2273. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2274. };
  2275. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2276. }
  2277. /// Emits metadata nodes associating all the global values in the
  2278. /// current module with the Decls they came from. This is useful for
  2279. /// projects using IR gen as a subroutine.
  2280. ///
  2281. /// Since there's currently no way to associate an MDNode directly
  2282. /// with an llvm::GlobalValue, we create a global named metadata
  2283. /// with the name 'clang.global.decl.ptrs'.
  2284. void CodeGenModule::EmitDeclMetadata() {
  2285. llvm::NamedMDNode *GlobalMetadata = 0;
  2286. // StaticLocalDeclMap
  2287. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2288. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2289. I != E; ++I) {
  2290. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2291. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2292. }
  2293. }
  2294. /// Emits metadata nodes for all the local variables in the current
  2295. /// function.
  2296. void CodeGenFunction::EmitDeclMetadata() {
  2297. if (LocalDeclMap.empty()) return;
  2298. llvm::LLVMContext &Context = getLLVMContext();
  2299. // Find the unique metadata ID for this name.
  2300. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2301. llvm::NamedMDNode *GlobalMetadata = 0;
  2302. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2303. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2304. const Decl *D = I->first;
  2305. llvm::Value *Addr = I->second;
  2306. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2307. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2308. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2309. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2310. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2311. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2312. }
  2313. }
  2314. }
  2315. void CodeGenModule::EmitCoverageFile() {
  2316. if (!getCodeGenOpts().CoverageFile.empty()) {
  2317. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2318. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2319. llvm::LLVMContext &Ctx = TheModule.getContext();
  2320. llvm::MDString *CoverageFile =
  2321. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2322. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2323. llvm::MDNode *CU = CUNode->getOperand(i);
  2324. llvm::Value *node[] = { CoverageFile, CU };
  2325. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2326. GCov->addOperand(N);
  2327. }
  2328. }
  2329. }
  2330. }