CodeGenModule.cpp 92 KB

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