CodeGenModule.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  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 "CGCXXABI.h"
  19. #include "CGObjCRuntime.h"
  20. #include "TargetInfo.h"
  21. #include "clang/Frontend/CodeGenOptions.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/CharUnits.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/Mangle.h"
  28. #include "clang/AST/RecordLayout.h"
  29. #include "clang/Basic/Builtins.h"
  30. #include "clang/Basic/Diagnostic.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Basic/ConvertUTF.h"
  34. #include "llvm/CallingConv.h"
  35. #include "llvm/Module.h"
  36. #include "llvm/Intrinsics.h"
  37. #include "llvm/LLVMContext.h"
  38. #include "llvm/ADT/Triple.h"
  39. #include "llvm/Target/TargetData.h"
  40. #include "llvm/Support/CallSite.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. using namespace clang;
  43. using namespace CodeGen;
  44. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  45. switch (CGM.getContext().Target.getCXXABI()) {
  46. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  47. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  48. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  49. }
  50. llvm_unreachable("invalid C++ ABI kind");
  51. return *CreateItaniumCXXABI(CGM);
  52. }
  53. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  54. llvm::Module &M, const llvm::TargetData &TD,
  55. Diagnostic &diags)
  56. : BlockModule(C, M, TD, Types, *this), Context(C),
  57. Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
  58. TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
  59. ABI(createCXXABI(*this)),
  60. Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
  61. TBAA(0),
  62. VTables(*this), Runtime(0),
  63. CFConstantStringClassRef(0), ConstantStringClassRef(0),
  64. VMContext(M.getContext()),
  65. NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
  66. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  67. BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
  68. BlockObjectAssign(0), BlockObjectDispose(0){
  69. if (!Features.ObjC1)
  70. Runtime = 0;
  71. else if (!Features.NeXTRuntime)
  72. Runtime = CreateGNUObjCRuntime(*this);
  73. else if (Features.ObjCNonFragileABI)
  74. Runtime = CreateMacNonFragileABIObjCRuntime(*this);
  75. else
  76. Runtime = CreateMacObjCRuntime(*this);
  77. // Enable TBAA unless it's suppressed.
  78. if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
  79. TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
  80. ABI.getMangleContext());
  81. // If debug info generation is enabled, create the CGDebugInfo object.
  82. DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
  83. }
  84. CodeGenModule::~CodeGenModule() {
  85. delete Runtime;
  86. delete &ABI;
  87. delete TBAA;
  88. delete DebugInfo;
  89. }
  90. void CodeGenModule::createObjCRuntime() {
  91. if (!Features.NeXTRuntime)
  92. Runtime = CreateGNUObjCRuntime(*this);
  93. else if (Features.ObjCNonFragileABI)
  94. Runtime = CreateMacNonFragileABIObjCRuntime(*this);
  95. else
  96. Runtime = CreateMacObjCRuntime(*this);
  97. }
  98. void CodeGenModule::Release() {
  99. EmitDeferred();
  100. EmitCXXGlobalInitFunc();
  101. EmitCXXGlobalDtorFunc();
  102. if (Runtime)
  103. if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
  104. AddGlobalCtor(ObjCInitFunction);
  105. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  106. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  107. EmitAnnotations();
  108. EmitLLVMUsed();
  109. SimplifyPersonality();
  110. if (getCodeGenOpts().EmitDeclMetadata)
  111. EmitDeclMetadata();
  112. }
  113. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  114. if (!TBAA)
  115. return 0;
  116. return TBAA->getTBAAInfo(QTy);
  117. }
  118. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  119. llvm::MDNode *TBAAInfo) {
  120. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  121. }
  122. bool CodeGenModule::isTargetDarwin() const {
  123. return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
  124. }
  125. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  126. /// specified stmt yet.
  127. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  128. bool OmitOnError) {
  129. if (OmitOnError && getDiags().hasErrorOccurred())
  130. return;
  131. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
  132. "cannot compile this %0 yet");
  133. std::string Msg = Type;
  134. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  135. << Msg << S->getSourceRange();
  136. }
  137. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  138. /// specified decl yet.
  139. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  140. bool OmitOnError) {
  141. if (OmitOnError && getDiags().hasErrorOccurred())
  142. return;
  143. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
  144. "cannot compile this %0 yet");
  145. std::string Msg = Type;
  146. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  147. }
  148. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  149. switch (V) {
  150. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  151. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  152. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  153. }
  154. llvm_unreachable("unknown visibility!");
  155. return llvm::GlobalValue::DefaultVisibility;
  156. }
  157. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  158. const NamedDecl *D,
  159. bool IsForDefinition) const {
  160. // Internal definitions always have default visibility.
  161. if (GV->hasLocalLinkage()) {
  162. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  163. return;
  164. }
  165. // Set visibility for definitions.
  166. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  167. if (LV.visibilityExplicit() ||
  168. (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
  169. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  170. }
  171. /// Set the symbol visibility of type information (vtable and RTTI)
  172. /// associated with the given type.
  173. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  174. const CXXRecordDecl *RD,
  175. bool IsForRTTI,
  176. bool IsForDefinition) const {
  177. setGlobalVisibility(GV, RD, IsForDefinition);
  178. if (!CodeGenOpts.HiddenWeakVTables)
  179. return;
  180. // We want to drop the visibility to hidden for weak type symbols.
  181. // This isn't possible if there might be unresolved references
  182. // elsewhere that rely on this symbol being visible.
  183. // This should be kept roughly in sync with setThunkVisibility
  184. // in CGVTables.cpp.
  185. // Preconditions.
  186. if (GV->getLinkage() != llvm::GlobalVariable::WeakODRLinkage ||
  187. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  188. return;
  189. // Don't override an explicit visibility attribute.
  190. if (RD->hasAttr<VisibilityAttr>())
  191. return;
  192. switch (RD->getTemplateSpecializationKind()) {
  193. // We have to disable the optimization if this is an EI definition
  194. // because there might be EI declarations in other shared objects.
  195. case TSK_ExplicitInstantiationDefinition:
  196. case TSK_ExplicitInstantiationDeclaration:
  197. return;
  198. // Every use of a non-template class's type information has to emit it.
  199. case TSK_Undeclared:
  200. break;
  201. // In theory, implicit instantiations can ignore the possibility of
  202. // an explicit instantiation declaration because there necessarily
  203. // must be an EI definition somewhere with default visibility. In
  204. // practice, it's possible to have an explicit instantiation for
  205. // an arbitrary template class, and linkers aren't necessarily able
  206. // to deal with mixed-visibility symbols.
  207. case TSK_ExplicitSpecialization:
  208. case TSK_ImplicitInstantiation:
  209. if (!CodeGenOpts.HiddenWeakTemplateVTables)
  210. return;
  211. break;
  212. }
  213. // If there's a key function, there may be translation units
  214. // that don't have the key function's definition. But ignore
  215. // this if we're emitting RTTI under -fno-rtti.
  216. if (!IsForRTTI || Features.RTTI)
  217. if (Context.getKeyFunction(RD))
  218. return;
  219. // Otherwise, drop the visibility to hidden.
  220. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  221. GV->setUnnamedAddr(true);
  222. }
  223. llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  224. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  225. llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  226. if (!Str.empty())
  227. return Str;
  228. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  229. IdentifierInfo *II = ND->getIdentifier();
  230. assert(II && "Attempt to mangle unnamed decl.");
  231. Str = II->getName();
  232. return Str;
  233. }
  234. llvm::SmallString<256> Buffer;
  235. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  236. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
  237. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  238. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
  239. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  240. getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
  241. else
  242. getCXXABI().getMangleContext().mangleName(ND, Buffer);
  243. // Allocate space for the mangled name.
  244. size_t Length = Buffer.size();
  245. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  246. std::copy(Buffer.begin(), Buffer.end(), Name);
  247. Str = llvm::StringRef(Name, Length);
  248. return Str;
  249. }
  250. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  251. const BlockDecl *BD) {
  252. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  253. const Decl *D = GD.getDecl();
  254. if (D == 0)
  255. MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
  256. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  257. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
  258. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  259. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
  260. else
  261. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
  262. }
  263. llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
  264. return getModule().getNamedValue(Name);
  265. }
  266. /// AddGlobalCtor - Add a function to the list that will be called before
  267. /// main() runs.
  268. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  269. // FIXME: Type coercion of void()* types.
  270. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  271. }
  272. /// AddGlobalDtor - Add a function to the list that will be called
  273. /// when the module is unloaded.
  274. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  275. // FIXME: Type coercion of void()* types.
  276. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  277. }
  278. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  279. // Ctor function type is void()*.
  280. llvm::FunctionType* CtorFTy =
  281. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
  282. std::vector<const llvm::Type*>(),
  283. false);
  284. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  285. // Get the type of a ctor entry, { i32, void ()* }.
  286. llvm::StructType* CtorStructTy =
  287. llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
  288. llvm::PointerType::getUnqual(CtorFTy), NULL);
  289. // Construct the constructor and destructor arrays.
  290. std::vector<llvm::Constant*> Ctors;
  291. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  292. std::vector<llvm::Constant*> S;
  293. S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  294. I->second, false));
  295. S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
  296. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  297. }
  298. if (!Ctors.empty()) {
  299. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  300. new llvm::GlobalVariable(TheModule, AT, false,
  301. llvm::GlobalValue::AppendingLinkage,
  302. llvm::ConstantArray::get(AT, Ctors),
  303. GlobalName);
  304. }
  305. }
  306. void CodeGenModule::EmitAnnotations() {
  307. if (Annotations.empty())
  308. return;
  309. // Create a new global variable for the ConstantStruct in the Module.
  310. llvm::Constant *Array =
  311. llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
  312. Annotations.size()),
  313. Annotations);
  314. llvm::GlobalValue *gv =
  315. new llvm::GlobalVariable(TheModule, Array->getType(), false,
  316. llvm::GlobalValue::AppendingLinkage, Array,
  317. "llvm.global.annotations");
  318. gv->setSection("llvm.metadata");
  319. }
  320. llvm::GlobalValue::LinkageTypes
  321. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  322. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  323. if (Linkage == GVA_Internal)
  324. return llvm::Function::InternalLinkage;
  325. if (D->hasAttr<DLLExportAttr>())
  326. return llvm::Function::DLLExportLinkage;
  327. if (D->hasAttr<WeakAttr>())
  328. return llvm::Function::WeakAnyLinkage;
  329. // In C99 mode, 'inline' functions are guaranteed to have a strong
  330. // definition somewhere else, so we can use available_externally linkage.
  331. if (Linkage == GVA_C99Inline)
  332. return llvm::Function::AvailableExternallyLinkage;
  333. // In C++, the compiler has to emit a definition in every translation unit
  334. // that references the function. We should use linkonce_odr because
  335. // a) if all references in this translation unit are optimized away, we
  336. // don't need to codegen it. b) if the function persists, it needs to be
  337. // merged with other definitions. c) C++ has the ODR, so we know the
  338. // definition is dependable.
  339. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  340. return llvm::Function::LinkOnceODRLinkage;
  341. // An explicit instantiation of a template has weak linkage, since
  342. // explicit instantiations can occur in multiple translation units
  343. // and must all be equivalent. However, we are not allowed to
  344. // throw away these explicit instantiations.
  345. if (Linkage == GVA_ExplicitTemplateInstantiation)
  346. return llvm::Function::WeakODRLinkage;
  347. // Otherwise, we have strong external linkage.
  348. assert(Linkage == GVA_StrongExternal);
  349. return llvm::Function::ExternalLinkage;
  350. }
  351. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  352. ///
  353. /// FIXME: This is currently only done for aliases and functions, but not for
  354. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  355. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  356. llvm::GlobalValue *GV) {
  357. SetCommonAttributes(D, GV);
  358. }
  359. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  360. const CGFunctionInfo &Info,
  361. llvm::Function *F) {
  362. unsigned CallingConv;
  363. AttributeListType AttributeList;
  364. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  365. F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
  366. AttributeList.size()));
  367. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  368. }
  369. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  370. llvm::Function *F) {
  371. if (!Features.Exceptions && !Features.ObjCNonFragileABI)
  372. F->addFnAttr(llvm::Attribute::NoUnwind);
  373. if (D->hasAttr<AlwaysInlineAttr>())
  374. F->addFnAttr(llvm::Attribute::AlwaysInline);
  375. if (D->hasAttr<NakedAttr>())
  376. F->addFnAttr(llvm::Attribute::Naked);
  377. if (D->hasAttr<NoInlineAttr>())
  378. F->addFnAttr(llvm::Attribute::NoInline);
  379. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  380. F->setUnnamedAddr(true);
  381. if (Features.getStackProtectorMode() == LangOptions::SSPOn)
  382. F->addFnAttr(llvm::Attribute::StackProtect);
  383. else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
  384. F->addFnAttr(llvm::Attribute::StackProtectReq);
  385. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  386. if (alignment)
  387. F->setAlignment(alignment);
  388. // C++ ABI requires 2-byte alignment for member functions.
  389. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  390. F->setAlignment(2);
  391. }
  392. void CodeGenModule::SetCommonAttributes(const Decl *D,
  393. llvm::GlobalValue *GV) {
  394. if (isa<NamedDecl>(D))
  395. setGlobalVisibility(GV, cast<NamedDecl>(D), /*ForDef*/ true);
  396. else
  397. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  398. if (D->hasAttr<UsedAttr>())
  399. AddUsedGlobal(GV);
  400. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  401. GV->setSection(SA->getName());
  402. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  403. }
  404. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  405. llvm::Function *F,
  406. const CGFunctionInfo &FI) {
  407. SetLLVMFunctionAttributes(D, FI, F);
  408. SetLLVMFunctionAttributesForDefinition(D, F);
  409. F->setLinkage(llvm::Function::InternalLinkage);
  410. SetCommonAttributes(D, F);
  411. }
  412. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  413. llvm::Function *F,
  414. bool IsIncompleteFunction) {
  415. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  416. if (!IsIncompleteFunction)
  417. SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
  418. // Only a few attributes are set on declarations; these may later be
  419. // overridden by a definition.
  420. if (FD->hasAttr<DLLImportAttr>()) {
  421. F->setLinkage(llvm::Function::DLLImportLinkage);
  422. } else if (FD->hasAttr<WeakAttr>() ||
  423. FD->hasAttr<WeakImportAttr>()) {
  424. // "extern_weak" is overloaded in LLVM; we probably should have
  425. // separate linkage types for this.
  426. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  427. } else {
  428. F->setLinkage(llvm::Function::ExternalLinkage);
  429. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  430. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  431. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  432. }
  433. }
  434. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  435. F->setSection(SA->getName());
  436. }
  437. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  438. assert(!GV->isDeclaration() &&
  439. "Only globals with definition can force usage.");
  440. LLVMUsed.push_back(GV);
  441. }
  442. void CodeGenModule::EmitLLVMUsed() {
  443. // Don't create llvm.used if there is no need.
  444. if (LLVMUsed.empty())
  445. return;
  446. const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
  447. // Convert LLVMUsed to what ConstantArray needs.
  448. std::vector<llvm::Constant*> UsedArray;
  449. UsedArray.resize(LLVMUsed.size());
  450. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  451. UsedArray[i] =
  452. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  453. i8PTy);
  454. }
  455. if (UsedArray.empty())
  456. return;
  457. llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
  458. llvm::GlobalVariable *GV =
  459. new llvm::GlobalVariable(getModule(), ATy, false,
  460. llvm::GlobalValue::AppendingLinkage,
  461. llvm::ConstantArray::get(ATy, UsedArray),
  462. "llvm.used");
  463. GV->setSection("llvm.metadata");
  464. }
  465. void CodeGenModule::EmitDeferred() {
  466. // Emit code for any potentially referenced deferred decls. Since a
  467. // previously unused static decl may become used during the generation of code
  468. // for a static function, iterate until no changes are made.
  469. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  470. if (!DeferredVTables.empty()) {
  471. const CXXRecordDecl *RD = DeferredVTables.back();
  472. DeferredVTables.pop_back();
  473. getVTables().GenerateClassData(getVTableLinkage(RD), RD);
  474. continue;
  475. }
  476. GlobalDecl D = DeferredDeclsToEmit.back();
  477. DeferredDeclsToEmit.pop_back();
  478. // Check to see if we've already emitted this. This is necessary
  479. // for a couple of reasons: first, decls can end up in the
  480. // deferred-decls queue multiple times, and second, decls can end
  481. // up with definitions in unusual ways (e.g. by an extern inline
  482. // function acquiring a strong function redefinition). Just
  483. // ignore these cases.
  484. //
  485. // TODO: That said, looking this up multiple times is very wasteful.
  486. llvm::StringRef Name = getMangledName(D);
  487. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  488. assert(CGRef && "Deferred decl wasn't referenced?");
  489. if (!CGRef->isDeclaration())
  490. continue;
  491. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  492. // purposes an alias counts as a definition.
  493. if (isa<llvm::GlobalAlias>(CGRef))
  494. continue;
  495. // Otherwise, emit the definition and move on to the next one.
  496. EmitGlobalDefinition(D);
  497. }
  498. }
  499. /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
  500. /// annotation information for a given GlobalValue. The annotation struct is
  501. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  502. /// GlobalValue being annotated. The second field is the constant string
  503. /// created from the AnnotateAttr's annotation. The third field is a constant
  504. /// string containing the name of the translation unit. The fourth field is
  505. /// the line number in the file of the annotated value declaration.
  506. ///
  507. /// FIXME: this does not unique the annotation string constants, as llvm-gcc
  508. /// appears to.
  509. ///
  510. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  511. const AnnotateAttr *AA,
  512. unsigned LineNo) {
  513. llvm::Module *M = &getModule();
  514. // get [N x i8] constants for the annotation string, and the filename string
  515. // which are the 2nd and 3rd elements of the global annotation structure.
  516. const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
  517. llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
  518. AA->getAnnotation(), true);
  519. llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
  520. M->getModuleIdentifier(),
  521. true);
  522. // Get the two global values corresponding to the ConstantArrays we just
  523. // created to hold the bytes of the strings.
  524. llvm::GlobalValue *annoGV =
  525. new llvm::GlobalVariable(*M, anno->getType(), false,
  526. llvm::GlobalValue::PrivateLinkage, anno,
  527. GV->getName());
  528. // translation unit name string, emitted into the llvm.metadata section.
  529. llvm::GlobalValue *unitGV =
  530. new llvm::GlobalVariable(*M, unit->getType(), false,
  531. llvm::GlobalValue::PrivateLinkage, unit,
  532. ".str");
  533. // Create the ConstantStruct for the global annotation.
  534. llvm::Constant *Fields[4] = {
  535. llvm::ConstantExpr::getBitCast(GV, SBP),
  536. llvm::ConstantExpr::getBitCast(annoGV, SBP),
  537. llvm::ConstantExpr::getBitCast(unitGV, SBP),
  538. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
  539. };
  540. return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
  541. }
  542. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  543. // Never defer when EmitAllDecls is specified.
  544. if (Features.EmitAllDecls)
  545. return false;
  546. return !getContext().DeclMustBeEmitted(Global);
  547. }
  548. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  549. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  550. assert(AA && "No alias?");
  551. const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  552. // See if there is already something with the target's name in the module.
  553. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  554. llvm::Constant *Aliasee;
  555. if (isa<llvm::FunctionType>(DeclTy))
  556. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
  557. else
  558. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  559. llvm::PointerType::getUnqual(DeclTy), 0);
  560. if (!Entry) {
  561. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  562. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  563. WeakRefReferences.insert(F);
  564. }
  565. return Aliasee;
  566. }
  567. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  568. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  569. // Weak references don't produce any output by themselves.
  570. if (Global->hasAttr<WeakRefAttr>())
  571. return;
  572. // If this is an alias definition (which otherwise looks like a declaration)
  573. // emit it now.
  574. if (Global->hasAttr<AliasAttr>())
  575. return EmitAliasDefinition(GD);
  576. // Ignore declarations, they will be emitted on their first use.
  577. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  578. if (FD->getIdentifier()) {
  579. llvm::StringRef Name = FD->getName();
  580. if (Name == "_Block_object_assign") {
  581. BlockObjectAssignDecl = FD;
  582. } else if (Name == "_Block_object_dispose") {
  583. BlockObjectDisposeDecl = FD;
  584. }
  585. }
  586. // Forward declarations are emitted lazily on first use.
  587. if (!FD->isThisDeclarationADefinition())
  588. return;
  589. } else {
  590. const VarDecl *VD = cast<VarDecl>(Global);
  591. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  592. if (VD->getIdentifier()) {
  593. llvm::StringRef Name = VD->getName();
  594. if (Name == "_NSConcreteGlobalBlock") {
  595. NSConcreteGlobalBlockDecl = VD;
  596. } else if (Name == "_NSConcreteStackBlock") {
  597. NSConcreteStackBlockDecl = VD;
  598. }
  599. }
  600. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  601. return;
  602. }
  603. // Defer code generation when possible if this is a static definition, inline
  604. // function etc. These we only want to emit if they are used.
  605. if (!MayDeferGeneration(Global)) {
  606. // Emit the definition if it can't be deferred.
  607. EmitGlobalDefinition(GD);
  608. return;
  609. }
  610. // If we're deferring emission of a C++ variable with an
  611. // initializer, remember the order in which it appeared in the file.
  612. if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
  613. cast<VarDecl>(Global)->hasInit()) {
  614. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  615. CXXGlobalInits.push_back(0);
  616. }
  617. // If the value has already been used, add it directly to the
  618. // DeferredDeclsToEmit list.
  619. llvm::StringRef MangledName = getMangledName(GD);
  620. if (GetGlobalValue(MangledName))
  621. DeferredDeclsToEmit.push_back(GD);
  622. else {
  623. // Otherwise, remember that we saw a deferred decl with this name. The
  624. // first use of the mangled name will cause it to move into
  625. // DeferredDeclsToEmit.
  626. DeferredDecls[MangledName] = GD;
  627. }
  628. }
  629. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  630. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  631. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  632. Context.getSourceManager(),
  633. "Generating code for declaration");
  634. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  635. // At -O0, don't generate IR for functions with available_externally
  636. // linkage.
  637. if (CodeGenOpts.OptimizationLevel == 0 &&
  638. !Function->hasAttr<AlwaysInlineAttr>() &&
  639. getFunctionLinkage(Function)
  640. == llvm::Function::AvailableExternallyLinkage)
  641. return;
  642. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  643. if (Method->isVirtual())
  644. getVTables().EmitThunks(GD);
  645. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  646. return EmitCXXConstructor(CD, GD.getCtorType());
  647. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
  648. return EmitCXXDestructor(DD, GD.getDtorType());
  649. }
  650. return EmitGlobalFunctionDefinition(GD);
  651. }
  652. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  653. return EmitGlobalVarDefinition(VD);
  654. assert(0 && "Invalid argument to EmitGlobalDefinition()");
  655. }
  656. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  657. /// module, create and return an llvm Function with the specified type. If there
  658. /// is something in the module with the specified name, return it potentially
  659. /// bitcasted to the right type.
  660. ///
  661. /// If D is non-null, it specifies a decl that correspond to this. This is used
  662. /// to set the attributes on the function when it is first created.
  663. llvm::Constant *
  664. CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
  665. const llvm::Type *Ty,
  666. GlobalDecl D) {
  667. // Lookup the entry, lazily creating it if necessary.
  668. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  669. if (Entry) {
  670. if (WeakRefReferences.count(Entry)) {
  671. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  672. if (FD && !FD->hasAttr<WeakAttr>())
  673. Entry->setLinkage(llvm::Function::ExternalLinkage);
  674. WeakRefReferences.erase(Entry);
  675. }
  676. if (Entry->getType()->getElementType() == Ty)
  677. return Entry;
  678. // Make sure the result is of the correct type.
  679. const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  680. return llvm::ConstantExpr::getBitCast(Entry, PTy);
  681. }
  682. // This function doesn't have a complete type (for example, the return
  683. // type is an incomplete struct). Use a fake type instead, and make
  684. // sure not to try to set attributes.
  685. bool IsIncompleteFunction = false;
  686. const llvm::FunctionType *FTy;
  687. if (isa<llvm::FunctionType>(Ty)) {
  688. FTy = cast<llvm::FunctionType>(Ty);
  689. } else {
  690. FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
  691. std::vector<const llvm::Type*>(), false);
  692. IsIncompleteFunction = true;
  693. }
  694. llvm::Function *F = llvm::Function::Create(FTy,
  695. llvm::Function::ExternalLinkage,
  696. MangledName, &getModule());
  697. assert(F->getName() == MangledName && "name was uniqued!");
  698. if (D.getDecl())
  699. SetFunctionAttributes(D, F, IsIncompleteFunction);
  700. // This is the first use or definition of a mangled name. If there is a
  701. // deferred decl with this name, remember that we need to emit it at the end
  702. // of the file.
  703. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  704. if (DDI != DeferredDecls.end()) {
  705. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  706. // list, and remove it from DeferredDecls (since we don't need it anymore).
  707. DeferredDeclsToEmit.push_back(DDI->second);
  708. DeferredDecls.erase(DDI);
  709. // Otherwise, there are cases we have to worry about where we're
  710. // using a declaration for which we must emit a definition but where
  711. // we might not find a top-level definition:
  712. // - member functions defined inline in their classes
  713. // - friend functions defined inline in some class
  714. // - special member functions with implicit definitions
  715. // If we ever change our AST traversal to walk into class methods,
  716. // this will be unnecessary.
  717. } else if (getLangOptions().CPlusPlus && D.getDecl()) {
  718. // Look for a declaration that's lexically in a record.
  719. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  720. do {
  721. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  722. if (FD->isImplicit()) {
  723. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  724. DeferredDeclsToEmit.push_back(D);
  725. break;
  726. } else if (FD->isThisDeclarationADefinition()) {
  727. DeferredDeclsToEmit.push_back(D);
  728. break;
  729. }
  730. }
  731. FD = FD->getPreviousDeclaration();
  732. } while (FD);
  733. }
  734. // Make sure the result is of the requested type.
  735. if (!IsIncompleteFunction) {
  736. assert(F->getType()->getElementType() == Ty);
  737. return F;
  738. }
  739. const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  740. return llvm::ConstantExpr::getBitCast(F, PTy);
  741. }
  742. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  743. /// non-null, then this function will use the specified type if it has to
  744. /// create it (this occurs when we see a definition of the function).
  745. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  746. const llvm::Type *Ty) {
  747. // If there was no specific requested type, just convert it now.
  748. if (!Ty)
  749. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  750. llvm::StringRef MangledName = getMangledName(GD);
  751. return GetOrCreateLLVMFunction(MangledName, Ty, GD);
  752. }
  753. /// CreateRuntimeFunction - Create a new runtime function with the specified
  754. /// type and name.
  755. llvm::Constant *
  756. CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
  757. llvm::StringRef Name) {
  758. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
  759. }
  760. static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
  761. if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
  762. return false;
  763. if (Context.getLangOptions().CPlusPlus &&
  764. Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
  765. // FIXME: We should do something fancier here!
  766. return false;
  767. }
  768. return true;
  769. }
  770. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  771. /// create and return an llvm GlobalVariable with the specified type. If there
  772. /// is something in the module with the specified name, return it potentially
  773. /// bitcasted to the right type.
  774. ///
  775. /// If D is non-null, it specifies a decl that correspond to this. This is used
  776. /// to set the attributes on the global when it is first created.
  777. llvm::Constant *
  778. CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
  779. const llvm::PointerType *Ty,
  780. const VarDecl *D) {
  781. // Lookup the entry, lazily creating it if necessary.
  782. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  783. if (Entry) {
  784. if (WeakRefReferences.count(Entry)) {
  785. if (D && !D->hasAttr<WeakAttr>())
  786. Entry->setLinkage(llvm::Function::ExternalLinkage);
  787. WeakRefReferences.erase(Entry);
  788. }
  789. if (Entry->getType() == Ty)
  790. return Entry;
  791. // Make sure the result is of the correct type.
  792. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  793. }
  794. // This is the first use or definition of a mangled name. If there is a
  795. // deferred decl with this name, remember that we need to emit it at the end
  796. // of the file.
  797. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  798. if (DDI != DeferredDecls.end()) {
  799. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  800. // list, and remove it from DeferredDecls (since we don't need it anymore).
  801. DeferredDeclsToEmit.push_back(DDI->second);
  802. DeferredDecls.erase(DDI);
  803. }
  804. llvm::GlobalVariable *GV =
  805. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  806. llvm::GlobalValue::ExternalLinkage,
  807. 0, MangledName, 0,
  808. false, Ty->getAddressSpace());
  809. // Handle things which are present even on external declarations.
  810. if (D) {
  811. // FIXME: This code is overly simple and should be merged with other global
  812. // handling.
  813. GV->setConstant(DeclIsConstantGlobal(Context, D));
  814. // Set linkage and visibility in case we never see a definition.
  815. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  816. if (LV.linkage() != ExternalLinkage) {
  817. GV->setLinkage(llvm::GlobalValue::InternalLinkage);
  818. } else {
  819. if (D->hasAttr<DLLImportAttr>())
  820. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  821. else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
  822. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  823. // Set visibility on a declaration only if it's explicit.
  824. if (LV.visibilityExplicit())
  825. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  826. }
  827. GV->setThreadLocal(D->isThreadSpecified());
  828. }
  829. return GV;
  830. }
  831. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  832. /// given global variable. If Ty is non-null and if the global doesn't exist,
  833. /// then it will be greated with the specified type instead of whatever the
  834. /// normal requested type would be.
  835. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  836. const llvm::Type *Ty) {
  837. assert(D->hasGlobalStorage() && "Not a global variable");
  838. QualType ASTTy = D->getType();
  839. if (Ty == 0)
  840. Ty = getTypes().ConvertTypeForMem(ASTTy);
  841. const llvm::PointerType *PTy =
  842. llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
  843. llvm::StringRef MangledName = getMangledName(D);
  844. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  845. }
  846. /// CreateRuntimeVariable - Create a new runtime global variable with the
  847. /// specified type and name.
  848. llvm::Constant *
  849. CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
  850. llvm::StringRef Name) {
  851. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
  852. }
  853. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  854. assert(!D->getInit() && "Cannot emit definite definitions here!");
  855. if (MayDeferGeneration(D)) {
  856. // If we have not seen a reference to this variable yet, place it
  857. // into the deferred declarations table to be emitted if needed
  858. // later.
  859. llvm::StringRef MangledName = getMangledName(D);
  860. if (!GetGlobalValue(MangledName)) {
  861. DeferredDecls[MangledName] = D;
  862. return;
  863. }
  864. }
  865. // The tentative definition is the only definition.
  866. EmitGlobalVarDefinition(D);
  867. }
  868. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  869. if (DefinitionRequired)
  870. getVTables().GenerateClassData(getVTableLinkage(Class), Class);
  871. }
  872. llvm::GlobalVariable::LinkageTypes
  873. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  874. if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
  875. return llvm::GlobalVariable::InternalLinkage;
  876. if (const CXXMethodDecl *KeyFunction
  877. = RD->getASTContext().getKeyFunction(RD)) {
  878. // If this class has a key function, use that to determine the linkage of
  879. // the vtable.
  880. const FunctionDecl *Def = 0;
  881. if (KeyFunction->hasBody(Def))
  882. KeyFunction = cast<CXXMethodDecl>(Def);
  883. switch (KeyFunction->getTemplateSpecializationKind()) {
  884. case TSK_Undeclared:
  885. case TSK_ExplicitSpecialization:
  886. if (KeyFunction->isInlined())
  887. return llvm::GlobalVariable::WeakODRLinkage;
  888. return llvm::GlobalVariable::ExternalLinkage;
  889. case TSK_ImplicitInstantiation:
  890. case TSK_ExplicitInstantiationDefinition:
  891. return llvm::GlobalVariable::WeakODRLinkage;
  892. case TSK_ExplicitInstantiationDeclaration:
  893. // FIXME: Use available_externally linkage. However, this currently
  894. // breaks LLVM's build due to undefined symbols.
  895. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  896. return llvm::GlobalVariable::WeakODRLinkage;
  897. }
  898. }
  899. switch (RD->getTemplateSpecializationKind()) {
  900. case TSK_Undeclared:
  901. case TSK_ExplicitSpecialization:
  902. case TSK_ImplicitInstantiation:
  903. case TSK_ExplicitInstantiationDefinition:
  904. return llvm::GlobalVariable::WeakODRLinkage;
  905. case TSK_ExplicitInstantiationDeclaration:
  906. // FIXME: Use available_externally linkage. However, this currently
  907. // breaks LLVM's build due to undefined symbols.
  908. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  909. return llvm::GlobalVariable::WeakODRLinkage;
  910. }
  911. // Silence GCC warning.
  912. return llvm::GlobalVariable::WeakODRLinkage;
  913. }
  914. CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
  915. return CharUnits::fromQuantity(
  916. TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
  917. }
  918. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  919. llvm::Constant *Init = 0;
  920. QualType ASTTy = D->getType();
  921. bool NonConstInit = false;
  922. const Expr *InitExpr = D->getAnyInitializer();
  923. if (!InitExpr) {
  924. // This is a tentative definition; tentative definitions are
  925. // implicitly initialized with { 0 }.
  926. //
  927. // Note that tentative definitions are only emitted at the end of
  928. // a translation unit, so they should never have incomplete
  929. // type. In addition, EmitTentativeDefinition makes sure that we
  930. // never attempt to emit a tentative definition if a real one
  931. // exists. A use may still exists, however, so we still may need
  932. // to do a RAUW.
  933. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  934. Init = EmitNullConstant(D->getType());
  935. } else {
  936. Init = EmitConstantExpr(InitExpr, D->getType());
  937. if (!Init) {
  938. QualType T = InitExpr->getType();
  939. if (D->getType()->isReferenceType())
  940. T = D->getType();
  941. if (getLangOptions().CPlusPlus) {
  942. Init = EmitNullConstant(T);
  943. NonConstInit = true;
  944. } else {
  945. ErrorUnsupported(D, "static initializer");
  946. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  947. }
  948. } else {
  949. // We don't need an initializer, so remove the entry for the delayed
  950. // initializer position (just in case this entry was delayed).
  951. if (getLangOptions().CPlusPlus)
  952. DelayedCXXInitPosition.erase(D);
  953. }
  954. }
  955. const llvm::Type* InitType = Init->getType();
  956. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  957. // Strip off a bitcast if we got one back.
  958. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  959. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  960. // all zero index gep.
  961. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  962. Entry = CE->getOperand(0);
  963. }
  964. // Entry is now either a Function or GlobalVariable.
  965. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  966. // We have a definition after a declaration with the wrong type.
  967. // We must make a new GlobalVariable* and update everything that used OldGV
  968. // (a declaration or tentative definition) with the new GlobalVariable*
  969. // (which will be a definition).
  970. //
  971. // This happens if there is a prototype for a global (e.g.
  972. // "extern int x[];") and then a definition of a different type (e.g.
  973. // "int x[10];"). This also happens when an initializer has a different type
  974. // from the type of the global (this happens with unions).
  975. if (GV == 0 ||
  976. GV->getType()->getElementType() != InitType ||
  977. GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
  978. // Move the old entry aside so that we'll create a new one.
  979. Entry->setName(llvm::StringRef());
  980. // Make a new global with the correct type, this is now guaranteed to work.
  981. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  982. // Replace all uses of the old global with the new global
  983. llvm::Constant *NewPtrForOldDecl =
  984. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  985. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  986. // Erase the old global, since it is no longer used.
  987. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  988. }
  989. if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
  990. SourceManager &SM = Context.getSourceManager();
  991. AddAnnotation(EmitAnnotateAttr(GV, AA,
  992. SM.getInstantiationLineNumber(D->getLocation())));
  993. }
  994. GV->setInitializer(Init);
  995. // If it is safe to mark the global 'constant', do so now.
  996. GV->setConstant(false);
  997. if (!NonConstInit && DeclIsConstantGlobal(Context, D))
  998. GV->setConstant(true);
  999. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1000. // Set the llvm linkage type as appropriate.
  1001. llvm::GlobalValue::LinkageTypes Linkage =
  1002. GetLLVMLinkageVarDefinition(D, GV);
  1003. GV->setLinkage(Linkage);
  1004. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1005. // common vars aren't constant even if declared const.
  1006. GV->setConstant(false);
  1007. SetCommonAttributes(D, GV);
  1008. // Emit the initializer function if necessary.
  1009. if (NonConstInit)
  1010. EmitCXXGlobalVarDeclInitFunc(D, GV);
  1011. // Emit global variable debug information.
  1012. if (CGDebugInfo *DI = getDebugInfo()) {
  1013. DI->setLocation(D->getLocation());
  1014. DI->EmitGlobalVariable(GV, D);
  1015. }
  1016. }
  1017. llvm::GlobalValue::LinkageTypes
  1018. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1019. llvm::GlobalVariable *GV) {
  1020. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1021. if (Linkage == GVA_Internal)
  1022. return llvm::Function::InternalLinkage;
  1023. else if (D->hasAttr<DLLImportAttr>())
  1024. return llvm::Function::DLLImportLinkage;
  1025. else if (D->hasAttr<DLLExportAttr>())
  1026. return llvm::Function::DLLExportLinkage;
  1027. else if (D->hasAttr<WeakAttr>()) {
  1028. if (GV->isConstant())
  1029. return llvm::GlobalVariable::WeakODRLinkage;
  1030. else
  1031. return llvm::GlobalVariable::WeakAnyLinkage;
  1032. } else if (Linkage == GVA_TemplateInstantiation ||
  1033. Linkage == GVA_ExplicitTemplateInstantiation)
  1034. // FIXME: It seems like we can provide more specific linkage here
  1035. // (LinkOnceODR, WeakODR).
  1036. return llvm::GlobalVariable::WeakAnyLinkage;
  1037. else if (!getLangOptions().CPlusPlus &&
  1038. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1039. D->getAttr<CommonAttr>()) &&
  1040. !D->hasExternalStorage() && !D->getInit() &&
  1041. !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
  1042. // Thread local vars aren't considered common linkage.
  1043. return llvm::GlobalVariable::CommonLinkage;
  1044. }
  1045. return llvm::GlobalVariable::ExternalLinkage;
  1046. }
  1047. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1048. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1049. /// existing call uses of the old function in the module, this adjusts them to
  1050. /// call the new function directly.
  1051. ///
  1052. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1053. /// functions to be able to inline them. If there is a bitcast in the way, it
  1054. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1055. /// run at -O0.
  1056. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1057. llvm::Function *NewFn) {
  1058. // If we're redefining a global as a function, don't transform it.
  1059. llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
  1060. if (OldFn == 0) return;
  1061. const llvm::Type *NewRetTy = NewFn->getReturnType();
  1062. llvm::SmallVector<llvm::Value*, 4> ArgList;
  1063. for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
  1064. UI != E; ) {
  1065. // TODO: Do invokes ever occur in C code? If so, we should handle them too.
  1066. llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
  1067. llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
  1068. if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
  1069. llvm::CallSite CS(CI);
  1070. if (!CI || !CS.isCallee(I)) continue;
  1071. // If the return types don't match exactly, and if the call isn't dead, then
  1072. // we can't transform this call.
  1073. if (CI->getType() != NewRetTy && !CI->use_empty())
  1074. continue;
  1075. // If the function was passed too few arguments, don't transform. If extra
  1076. // arguments were passed, we silently drop them. If any of the types
  1077. // mismatch, we don't transform.
  1078. unsigned ArgNo = 0;
  1079. bool DontTransform = false;
  1080. for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
  1081. E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
  1082. if (CS.arg_size() == ArgNo ||
  1083. CS.getArgument(ArgNo)->getType() != AI->getType()) {
  1084. DontTransform = true;
  1085. break;
  1086. }
  1087. }
  1088. if (DontTransform)
  1089. continue;
  1090. // Okay, we can transform this. Create the new call instruction and copy
  1091. // over the required information.
  1092. ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
  1093. llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
  1094. ArgList.end(), "", CI);
  1095. ArgList.clear();
  1096. if (!NewCall->getType()->isVoidTy())
  1097. NewCall->takeName(CI);
  1098. NewCall->setAttributes(CI->getAttributes());
  1099. NewCall->setCallingConv(CI->getCallingConv());
  1100. // Finally, remove the old call, replacing any uses with the new one.
  1101. if (!CI->use_empty())
  1102. CI->replaceAllUsesWith(NewCall);
  1103. // Copy debug location attached to CI.
  1104. if (!CI->getDebugLoc().isUnknown())
  1105. NewCall->setDebugLoc(CI->getDebugLoc());
  1106. CI->eraseFromParent();
  1107. }
  1108. }
  1109. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1110. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1111. const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
  1112. // Get or create the prototype for the function.
  1113. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1114. // Strip off a bitcast if we got one back.
  1115. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1116. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1117. Entry = CE->getOperand(0);
  1118. }
  1119. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1120. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1121. // If the types mismatch then we have to rewrite the definition.
  1122. assert(OldFn->isDeclaration() &&
  1123. "Shouldn't replace non-declaration");
  1124. // F is the Function* for the one with the wrong type, we must make a new
  1125. // Function* and update everything that used F (a declaration) with the new
  1126. // Function* (which will be a definition).
  1127. //
  1128. // This happens if there is a prototype for a function
  1129. // (e.g. "int f()") and then a definition of a different type
  1130. // (e.g. "int f(int x)"). Move the old function aside so that it
  1131. // doesn't interfere with GetAddrOfFunction.
  1132. OldFn->setName(llvm::StringRef());
  1133. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1134. // If this is an implementation of a function without a prototype, try to
  1135. // replace any existing uses of the function (which may be calls) with uses
  1136. // of the new function
  1137. if (D->getType()->isFunctionNoProtoType()) {
  1138. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1139. OldFn->removeDeadConstantUsers();
  1140. }
  1141. // Replace uses of F with the Function we will endow with a body.
  1142. if (!Entry->use_empty()) {
  1143. llvm::Constant *NewPtrForOldDecl =
  1144. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1145. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1146. }
  1147. // Ok, delete the old function now, which is dead.
  1148. OldFn->eraseFromParent();
  1149. Entry = NewFn;
  1150. }
  1151. // We need to set linkage and visibility on the function before
  1152. // generating code for it because various parts of IR generation
  1153. // want to propagate this information down (e.g. to local static
  1154. // declarations).
  1155. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1156. setFunctionLinkage(D, Fn);
  1157. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1158. setGlobalVisibility(Fn, D, /*ForDef*/ true);
  1159. CodeGenFunction(*this).GenerateCode(D, Fn);
  1160. SetFunctionDefinitionAttributes(D, Fn);
  1161. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1162. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1163. AddGlobalCtor(Fn, CA->getPriority());
  1164. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1165. AddGlobalDtor(Fn, DA->getPriority());
  1166. }
  1167. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1168. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1169. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1170. assert(AA && "Not an alias?");
  1171. llvm::StringRef MangledName = getMangledName(GD);
  1172. // If there is a definition in the module, then it wins over the alias.
  1173. // This is dubious, but allow it to be safe. Just ignore the alias.
  1174. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1175. if (Entry && !Entry->isDeclaration())
  1176. return;
  1177. const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1178. // Create a reference to the named value. This ensures that it is emitted
  1179. // if a deferred decl.
  1180. llvm::Constant *Aliasee;
  1181. if (isa<llvm::FunctionType>(DeclTy))
  1182. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
  1183. else
  1184. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1185. llvm::PointerType::getUnqual(DeclTy), 0);
  1186. // Create the new alias itself, but don't set a name yet.
  1187. llvm::GlobalValue *GA =
  1188. new llvm::GlobalAlias(Aliasee->getType(),
  1189. llvm::Function::ExternalLinkage,
  1190. "", Aliasee, &getModule());
  1191. if (Entry) {
  1192. assert(Entry->isDeclaration());
  1193. // If there is a declaration in the module, then we had an extern followed
  1194. // by the alias, as in:
  1195. // extern int test6();
  1196. // ...
  1197. // int test6() __attribute__((alias("test7")));
  1198. //
  1199. // Remove it and replace uses of it with the alias.
  1200. GA->takeName(Entry);
  1201. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1202. Entry->getType()));
  1203. Entry->eraseFromParent();
  1204. } else {
  1205. GA->setName(MangledName);
  1206. }
  1207. // Set attributes which are particular to an alias; this is a
  1208. // specialization of the attributes which may be set on a global
  1209. // variable/function.
  1210. if (D->hasAttr<DLLExportAttr>()) {
  1211. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1212. // The dllexport attribute is ignored for undefined symbols.
  1213. if (FD->hasBody())
  1214. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1215. } else {
  1216. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1217. }
  1218. } else if (D->hasAttr<WeakAttr>() ||
  1219. D->hasAttr<WeakRefAttr>() ||
  1220. D->hasAttr<WeakImportAttr>()) {
  1221. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1222. }
  1223. SetCommonAttributes(D, GA);
  1224. }
  1225. /// getBuiltinLibFunction - Given a builtin id for a function like
  1226. /// "__builtin_fabsf", return a Function* for "fabsf".
  1227. llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
  1228. unsigned BuiltinID) {
  1229. assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
  1230. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
  1231. "isn't a lib fn");
  1232. // Get the name, skip over the __builtin_ prefix (if necessary).
  1233. const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
  1234. if (Context.BuiltinInfo.isLibFunction(BuiltinID))
  1235. Name += 10;
  1236. const llvm::FunctionType *Ty =
  1237. cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
  1238. return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
  1239. }
  1240. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
  1241. unsigned NumTys) {
  1242. return llvm::Intrinsic::getDeclaration(&getModule(),
  1243. (llvm::Intrinsic::ID)IID, Tys, NumTys);
  1244. }
  1245. static llvm::StringMapEntry<llvm::Constant*> &
  1246. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1247. const StringLiteral *Literal,
  1248. bool TargetIsLSB,
  1249. bool &IsUTF16,
  1250. unsigned &StringLength) {
  1251. llvm::StringRef String = Literal->getString();
  1252. unsigned NumBytes = String.size();
  1253. // Check for simple case.
  1254. if (!Literal->containsNonAsciiOrNull()) {
  1255. StringLength = NumBytes;
  1256. return Map.GetOrCreateValue(String);
  1257. }
  1258. // Otherwise, convert the UTF8 literals into a byte string.
  1259. llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
  1260. const UTF8 *FromPtr = (UTF8 *)String.data();
  1261. UTF16 *ToPtr = &ToBuf[0];
  1262. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1263. &ToPtr, ToPtr + NumBytes,
  1264. strictConversion);
  1265. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1266. StringLength = ToPtr - &ToBuf[0];
  1267. // Render the UTF-16 string into a byte array and convert to the target byte
  1268. // order.
  1269. //
  1270. // FIXME: This isn't something we should need to do here.
  1271. llvm::SmallString<128> AsBytes;
  1272. AsBytes.reserve(StringLength * 2);
  1273. for (unsigned i = 0; i != StringLength; ++i) {
  1274. unsigned short Val = ToBuf[i];
  1275. if (TargetIsLSB) {
  1276. AsBytes.push_back(Val & 0xFF);
  1277. AsBytes.push_back(Val >> 8);
  1278. } else {
  1279. AsBytes.push_back(Val >> 8);
  1280. AsBytes.push_back(Val & 0xFF);
  1281. }
  1282. }
  1283. // Append one extra null character, the second is automatically added by our
  1284. // caller.
  1285. AsBytes.push_back(0);
  1286. IsUTF16 = true;
  1287. return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
  1288. }
  1289. llvm::Constant *
  1290. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1291. unsigned StringLength = 0;
  1292. bool isUTF16 = false;
  1293. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1294. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1295. getTargetData().isLittleEndian(),
  1296. isUTF16, StringLength);
  1297. if (llvm::Constant *C = Entry.getValue())
  1298. return C;
  1299. llvm::Constant *Zero =
  1300. llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
  1301. llvm::Constant *Zeros[] = { Zero, Zero };
  1302. // If we don't already have it, get __CFConstantStringClassReference.
  1303. if (!CFConstantStringClassRef) {
  1304. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1305. Ty = llvm::ArrayType::get(Ty, 0);
  1306. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1307. "__CFConstantStringClassReference");
  1308. // Decay array -> ptr
  1309. CFConstantStringClassRef =
  1310. llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1311. }
  1312. QualType CFTy = getContext().getCFConstantStringType();
  1313. const llvm::StructType *STy =
  1314. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1315. std::vector<llvm::Constant*> Fields(4);
  1316. // Class pointer.
  1317. Fields[0] = CFConstantStringClassRef;
  1318. // Flags.
  1319. const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1320. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1321. llvm::ConstantInt::get(Ty, 0x07C8);
  1322. // String pointer.
  1323. llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
  1324. llvm::GlobalValue::LinkageTypes Linkage;
  1325. bool isConstant;
  1326. if (isUTF16) {
  1327. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1328. Linkage = llvm::GlobalValue::InternalLinkage;
  1329. // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
  1330. // does make plain ascii ones writable.
  1331. isConstant = true;
  1332. } else {
  1333. Linkage = llvm::GlobalValue::PrivateLinkage;
  1334. isConstant = !Features.WritableStrings;
  1335. }
  1336. llvm::GlobalVariable *GV =
  1337. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1338. ".str");
  1339. if (isUTF16) {
  1340. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1341. GV->setAlignment(Align.getQuantity());
  1342. }
  1343. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1344. // String length.
  1345. Ty = getTypes().ConvertType(getContext().LongTy);
  1346. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1347. // The struct.
  1348. C = llvm::ConstantStruct::get(STy, Fields);
  1349. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1350. llvm::GlobalVariable::PrivateLinkage, C,
  1351. "_unnamed_cfstring_");
  1352. if (const char *Sect = getContext().Target.getCFStringSection())
  1353. GV->setSection(Sect);
  1354. Entry.setValue(GV);
  1355. return GV;
  1356. }
  1357. llvm::Constant *
  1358. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1359. unsigned StringLength = 0;
  1360. bool isUTF16 = false;
  1361. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1362. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1363. getTargetData().isLittleEndian(),
  1364. isUTF16, StringLength);
  1365. if (llvm::Constant *C = Entry.getValue())
  1366. return C;
  1367. llvm::Constant *Zero =
  1368. llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
  1369. llvm::Constant *Zeros[] = { Zero, Zero };
  1370. // If we don't already have it, get _NSConstantStringClassReference.
  1371. if (!ConstantStringClassRef) {
  1372. std::string StringClass(getLangOptions().ObjCConstantStringClass);
  1373. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1374. Ty = llvm::ArrayType::get(Ty, 0);
  1375. llvm::Constant *GV;
  1376. if (StringClass.empty())
  1377. GV = CreateRuntimeVariable(Ty,
  1378. Features.ObjCNonFragileABI ?
  1379. "OBJC_CLASS_$_NSConstantString" :
  1380. "_NSConstantStringClassReference");
  1381. else {
  1382. std::string str;
  1383. if (Features.ObjCNonFragileABI)
  1384. str = "OBJC_CLASS_$_" + StringClass;
  1385. else
  1386. str = "_" + StringClass + "ClassReference";
  1387. GV = CreateRuntimeVariable(Ty, str);
  1388. }
  1389. // Decay array -> ptr
  1390. ConstantStringClassRef =
  1391. llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1392. }
  1393. QualType NSTy = getContext().getNSConstantStringType();
  1394. const llvm::StructType *STy =
  1395. cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1396. std::vector<llvm::Constant*> Fields(3);
  1397. // Class pointer.
  1398. Fields[0] = ConstantStringClassRef;
  1399. // String pointer.
  1400. llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
  1401. llvm::GlobalValue::LinkageTypes Linkage;
  1402. bool isConstant;
  1403. if (isUTF16) {
  1404. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1405. Linkage = llvm::GlobalValue::InternalLinkage;
  1406. // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
  1407. // does make plain ascii ones writable.
  1408. isConstant = true;
  1409. } else {
  1410. Linkage = llvm::GlobalValue::PrivateLinkage;
  1411. isConstant = !Features.WritableStrings;
  1412. }
  1413. llvm::GlobalVariable *GV =
  1414. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1415. ".str");
  1416. if (isUTF16) {
  1417. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1418. GV->setAlignment(Align.getQuantity());
  1419. }
  1420. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
  1421. // String length.
  1422. const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1423. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1424. // The struct.
  1425. C = llvm::ConstantStruct::get(STy, Fields);
  1426. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1427. llvm::GlobalVariable::PrivateLinkage, C,
  1428. "_unnamed_nsstring_");
  1429. // FIXME. Fix section.
  1430. if (const char *Sect =
  1431. Features.ObjCNonFragileABI
  1432. ? getContext().Target.getNSStringNonFragileABISection()
  1433. : getContext().Target.getNSStringSection())
  1434. GV->setSection(Sect);
  1435. Entry.setValue(GV);
  1436. return GV;
  1437. }
  1438. /// GetStringForStringLiteral - Return the appropriate bytes for a
  1439. /// string literal, properly padded to match the literal type.
  1440. std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
  1441. const ConstantArrayType *CAT =
  1442. getContext().getAsConstantArrayType(E->getType());
  1443. assert(CAT && "String isn't pointer or array!");
  1444. // Resize the string to the right size.
  1445. uint64_t RealLen = CAT->getSize().getZExtValue();
  1446. if (E->isWide())
  1447. RealLen *= getContext().Target.getWCharWidth()/8;
  1448. std::string Str = E->getString().str();
  1449. Str.resize(RealLen, '\0');
  1450. return Str;
  1451. }
  1452. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  1453. /// constant array for the given string literal.
  1454. llvm::Constant *
  1455. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  1456. // FIXME: This can be more efficient.
  1457. // FIXME: We shouldn't need to bitcast the constant in the wide string case.
  1458. llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
  1459. if (S->isWide()) {
  1460. llvm::Type *DestTy =
  1461. llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
  1462. C = llvm::ConstantExpr::getBitCast(C, DestTy);
  1463. }
  1464. return C;
  1465. }
  1466. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  1467. /// array for the given ObjCEncodeExpr node.
  1468. llvm::Constant *
  1469. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  1470. std::string Str;
  1471. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1472. return GetAddrOfConstantCString(Str);
  1473. }
  1474. /// GenerateWritableString -- Creates storage for a string literal.
  1475. static llvm::Constant *GenerateStringLiteral(const std::string &str,
  1476. bool constant,
  1477. CodeGenModule &CGM,
  1478. const char *GlobalName) {
  1479. // Create Constant for this string literal. Don't add a '\0'.
  1480. llvm::Constant *C =
  1481. llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
  1482. // Create a global variable for this string
  1483. llvm::GlobalVariable *GV =
  1484. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  1485. llvm::GlobalValue::PrivateLinkage,
  1486. C, GlobalName);
  1487. GV->setUnnamedAddr(true);
  1488. return GV;
  1489. }
  1490. /// GetAddrOfConstantString - Returns a pointer to a character array
  1491. /// containing the literal. This contents are exactly that of the
  1492. /// given string, i.e. it will not be null terminated automatically;
  1493. /// see GetAddrOfConstantCString. Note that whether the result is
  1494. /// actually a pointer to an LLVM constant depends on
  1495. /// Feature.WriteableStrings.
  1496. ///
  1497. /// The result has pointer to array type.
  1498. llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
  1499. const char *GlobalName) {
  1500. bool IsConstant = !Features.WritableStrings;
  1501. // Get the default prefix if a name wasn't specified.
  1502. if (!GlobalName)
  1503. GlobalName = ".str";
  1504. // Don't share any string literals if strings aren't constant.
  1505. if (!IsConstant)
  1506. return GenerateStringLiteral(str, false, *this, GlobalName);
  1507. llvm::StringMapEntry<llvm::Constant *> &Entry =
  1508. ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
  1509. if (Entry.getValue())
  1510. return Entry.getValue();
  1511. // Create a global variable for this.
  1512. llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
  1513. Entry.setValue(C);
  1514. return C;
  1515. }
  1516. /// GetAddrOfConstantCString - Returns a pointer to a character
  1517. /// array containing the literal and a terminating '\-'
  1518. /// character. The result has pointer to array type.
  1519. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
  1520. const char *GlobalName){
  1521. return GetAddrOfConstantString(str + '\0', GlobalName);
  1522. }
  1523. /// EmitObjCPropertyImplementations - Emit information for synthesized
  1524. /// properties for an implementation.
  1525. void CodeGenModule::EmitObjCPropertyImplementations(const
  1526. ObjCImplementationDecl *D) {
  1527. for (ObjCImplementationDecl::propimpl_iterator
  1528. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  1529. ObjCPropertyImplDecl *PID = *i;
  1530. // Dynamic is just for type-checking.
  1531. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  1532. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  1533. // Determine which methods need to be implemented, some may have
  1534. // been overridden. Note that ::isSynthesized is not the method
  1535. // we want, that just indicates if the decl came from a
  1536. // property. What we want to know is if the method is defined in
  1537. // this implementation.
  1538. if (!D->getInstanceMethod(PD->getGetterName()))
  1539. CodeGenFunction(*this).GenerateObjCGetter(
  1540. const_cast<ObjCImplementationDecl *>(D), PID);
  1541. if (!PD->isReadOnly() &&
  1542. !D->getInstanceMethod(PD->getSetterName()))
  1543. CodeGenFunction(*this).GenerateObjCSetter(
  1544. const_cast<ObjCImplementationDecl *>(D), PID);
  1545. }
  1546. }
  1547. }
  1548. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  1549. /// for an implementation.
  1550. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  1551. if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
  1552. return;
  1553. DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
  1554. assert(DC && "EmitObjCIvarInitializations - null DeclContext");
  1555. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  1556. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  1557. ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
  1558. D->getLocation(),
  1559. D->getLocation(), cxxSelector,
  1560. getContext().VoidTy, 0,
  1561. DC, true, false, true, false,
  1562. ObjCMethodDecl::Required);
  1563. D->addInstanceMethod(DTORMethod);
  1564. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  1565. II = &getContext().Idents.get(".cxx_construct");
  1566. cxxSelector = getContext().Selectors.getSelector(0, &II);
  1567. // The constructor returns 'self'.
  1568. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  1569. D->getLocation(),
  1570. D->getLocation(), cxxSelector,
  1571. getContext().getObjCIdType(), 0,
  1572. DC, true, false, true, false,
  1573. ObjCMethodDecl::Required);
  1574. D->addInstanceMethod(CTORMethod);
  1575. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  1576. }
  1577. /// EmitNamespace - Emit all declarations in a namespace.
  1578. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  1579. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  1580. I != E; ++I)
  1581. EmitTopLevelDecl(*I);
  1582. }
  1583. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  1584. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  1585. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  1586. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  1587. ErrorUnsupported(LSD, "linkage spec");
  1588. return;
  1589. }
  1590. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  1591. I != E; ++I)
  1592. EmitTopLevelDecl(*I);
  1593. }
  1594. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  1595. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  1596. // If an error has occurred, stop code generation, but continue
  1597. // parsing and semantic analysis (to ensure all warnings and errors
  1598. // are emitted).
  1599. if (Diags.hasErrorOccurred())
  1600. return;
  1601. // Ignore dependent declarations.
  1602. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  1603. return;
  1604. switch (D->getKind()) {
  1605. case Decl::CXXConversion:
  1606. case Decl::CXXMethod:
  1607. case Decl::Function:
  1608. // Skip function templates
  1609. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
  1610. return;
  1611. EmitGlobal(cast<FunctionDecl>(D));
  1612. break;
  1613. case Decl::Var:
  1614. EmitGlobal(cast<VarDecl>(D));
  1615. break;
  1616. // C++ Decls
  1617. case Decl::Namespace:
  1618. EmitNamespace(cast<NamespaceDecl>(D));
  1619. break;
  1620. // No code generation needed.
  1621. case Decl::UsingShadow:
  1622. case Decl::Using:
  1623. case Decl::UsingDirective:
  1624. case Decl::ClassTemplate:
  1625. case Decl::FunctionTemplate:
  1626. case Decl::NamespaceAlias:
  1627. break;
  1628. case Decl::CXXConstructor:
  1629. // Skip function templates
  1630. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
  1631. return;
  1632. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  1633. break;
  1634. case Decl::CXXDestructor:
  1635. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  1636. break;
  1637. case Decl::StaticAssert:
  1638. // Nothing to do.
  1639. break;
  1640. // Objective-C Decls
  1641. // Forward declarations, no (immediate) code generation.
  1642. case Decl::ObjCClass:
  1643. case Decl::ObjCForwardProtocol:
  1644. case Decl::ObjCInterface:
  1645. break;
  1646. case Decl::ObjCCategory: {
  1647. ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
  1648. if (CD->IsClassExtension() && CD->hasSynthBitfield())
  1649. Context.ResetObjCLayout(CD->getClassInterface());
  1650. break;
  1651. }
  1652. case Decl::ObjCProtocol:
  1653. Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
  1654. break;
  1655. case Decl::ObjCCategoryImpl:
  1656. // Categories have properties but don't support synthesize so we
  1657. // can ignore them here.
  1658. Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  1659. break;
  1660. case Decl::ObjCImplementation: {
  1661. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  1662. if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
  1663. Context.ResetObjCLayout(OMD->getClassInterface());
  1664. EmitObjCPropertyImplementations(OMD);
  1665. EmitObjCIvarInitializations(OMD);
  1666. Runtime->GenerateClass(OMD);
  1667. break;
  1668. }
  1669. case Decl::ObjCMethod: {
  1670. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  1671. // If this is not a prototype, emit the body.
  1672. if (OMD->getBody())
  1673. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  1674. break;
  1675. }
  1676. case Decl::ObjCCompatibleAlias:
  1677. // compatibility-alias is a directive and has no code gen.
  1678. break;
  1679. case Decl::LinkageSpec:
  1680. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  1681. break;
  1682. case Decl::FileScopeAsm: {
  1683. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  1684. llvm::StringRef AsmString = AD->getAsmString()->getString();
  1685. const std::string &S = getModule().getModuleInlineAsm();
  1686. if (S.empty())
  1687. getModule().setModuleInlineAsm(AsmString);
  1688. else
  1689. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  1690. break;
  1691. }
  1692. default:
  1693. // Make sure we handled everything we should, every other kind is a
  1694. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  1695. // function. Need to recode Decl::Kind to do that easily.
  1696. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  1697. }
  1698. }
  1699. /// Turns the given pointer into a constant.
  1700. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  1701. const void *Ptr) {
  1702. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  1703. const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  1704. return llvm::ConstantInt::get(i64, PtrInt);
  1705. }
  1706. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  1707. llvm::NamedMDNode *&GlobalMetadata,
  1708. GlobalDecl D,
  1709. llvm::GlobalValue *Addr) {
  1710. if (!GlobalMetadata)
  1711. GlobalMetadata =
  1712. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  1713. // TODO: should we report variant information for ctors/dtors?
  1714. llvm::Value *Ops[] = {
  1715. Addr,
  1716. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  1717. };
  1718. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
  1719. }
  1720. /// Emits metadata nodes associating all the global values in the
  1721. /// current module with the Decls they came from. This is useful for
  1722. /// projects using IR gen as a subroutine.
  1723. ///
  1724. /// Since there's currently no way to associate an MDNode directly
  1725. /// with an llvm::GlobalValue, we create a global named metadata
  1726. /// with the name 'clang.global.decl.ptrs'.
  1727. void CodeGenModule::EmitDeclMetadata() {
  1728. llvm::NamedMDNode *GlobalMetadata = 0;
  1729. // StaticLocalDeclMap
  1730. for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
  1731. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  1732. I != E; ++I) {
  1733. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  1734. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  1735. }
  1736. }
  1737. /// Emits metadata nodes for all the local variables in the current
  1738. /// function.
  1739. void CodeGenFunction::EmitDeclMetadata() {
  1740. if (LocalDeclMap.empty()) return;
  1741. llvm::LLVMContext &Context = getLLVMContext();
  1742. // Find the unique metadata ID for this name.
  1743. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  1744. llvm::NamedMDNode *GlobalMetadata = 0;
  1745. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  1746. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  1747. const Decl *D = I->first;
  1748. llvm::Value *Addr = I->second;
  1749. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  1750. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  1751. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
  1752. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  1753. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  1754. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  1755. }
  1756. }
  1757. }
  1758. ///@name Custom Runtime Function Interfaces
  1759. ///@{
  1760. //
  1761. // FIXME: These can be eliminated once we can have clients just get the required
  1762. // AST nodes from the builtin tables.
  1763. llvm::Constant *CodeGenModule::getBlockObjectDispose() {
  1764. if (BlockObjectDispose)
  1765. return BlockObjectDispose;
  1766. // If we saw an explicit decl, use that.
  1767. if (BlockObjectDisposeDecl) {
  1768. return BlockObjectDispose = GetAddrOfFunction(
  1769. BlockObjectDisposeDecl,
  1770. getTypes().GetFunctionType(BlockObjectDisposeDecl));
  1771. }
  1772. // Otherwise construct the function by hand.
  1773. const llvm::FunctionType *FTy;
  1774. std::vector<const llvm::Type*> ArgTys;
  1775. const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
  1776. ArgTys.push_back(PtrToInt8Ty);
  1777. ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
  1778. FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
  1779. return BlockObjectDispose =
  1780. CreateRuntimeFunction(FTy, "_Block_object_dispose");
  1781. }
  1782. llvm::Constant *CodeGenModule::getBlockObjectAssign() {
  1783. if (BlockObjectAssign)
  1784. return BlockObjectAssign;
  1785. // If we saw an explicit decl, use that.
  1786. if (BlockObjectAssignDecl) {
  1787. return BlockObjectAssign = GetAddrOfFunction(
  1788. BlockObjectAssignDecl,
  1789. getTypes().GetFunctionType(BlockObjectAssignDecl));
  1790. }
  1791. // Otherwise construct the function by hand.
  1792. const llvm::FunctionType *FTy;
  1793. std::vector<const llvm::Type*> ArgTys;
  1794. const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
  1795. ArgTys.push_back(PtrToInt8Ty);
  1796. ArgTys.push_back(PtrToInt8Ty);
  1797. ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
  1798. FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
  1799. return BlockObjectAssign =
  1800. CreateRuntimeFunction(FTy, "_Block_object_assign");
  1801. }
  1802. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  1803. if (NSConcreteGlobalBlock)
  1804. return NSConcreteGlobalBlock;
  1805. // If we saw an explicit decl, use that.
  1806. if (NSConcreteGlobalBlockDecl) {
  1807. return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
  1808. NSConcreteGlobalBlockDecl,
  1809. getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
  1810. }
  1811. // Otherwise construct the variable by hand.
  1812. return NSConcreteGlobalBlock = CreateRuntimeVariable(
  1813. PtrToInt8Ty, "_NSConcreteGlobalBlock");
  1814. }
  1815. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  1816. if (NSConcreteStackBlock)
  1817. return NSConcreteStackBlock;
  1818. // If we saw an explicit decl, use that.
  1819. if (NSConcreteStackBlockDecl) {
  1820. return NSConcreteStackBlock = GetAddrOfGlobalVar(
  1821. NSConcreteStackBlockDecl,
  1822. getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
  1823. }
  1824. // Otherwise construct the variable by hand.
  1825. return NSConcreteStackBlock = CreateRuntimeVariable(
  1826. PtrToInt8Ty, "_NSConcreteStackBlock");
  1827. }
  1828. ///@}