CodeGenModule.cpp 81 KB

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