blob: 7f4546f07965d8fb55300f8d79b7567e3a5cd407 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Dan Gohman3d5aff52010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall4c40d982010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000036#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/Intrinsics.h"
Chris Lattnerd5b89022009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCall6374c332010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Rafael Espindolac4850c22011-02-10 23:59:36 +000040#include "llvm/Target/Mangler.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000042#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000043#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
45using namespace CodeGen;
46
John McCallf16aa102010-08-22 21:01:12 +000047static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
52 }
53
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
56}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058
Chandler Carruth2811ccf2009-11-12 17:24:48 +000059CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000060 llvm::Module &M, const llvm::TargetData &TD,
61 Diagnostic &diags)
John McCalld16c2cf2011-02-08 08:22:06 +000062 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman3d5aff52010-10-14 23:06:10 +000066 TBAA(0),
John McCallf85e1932011-06-15 23:02:42 +000067 VTables(*this), Runtime(0), DebugInfo(0), ARCData(0), RRData(0),
Fariborz Jahanian4c733072010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
John McCalld16c2cf2011-02-08 08:22:06 +000073 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
David Chisnall60be6072011-03-22 21:21:24 +000075 if (Features.ObjC1)
76 createObjCRuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000077
Dan Gohman3d5aff52010-10-14 23:06:10 +000078 // Enable TBAA unless it's suppressed.
79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000080 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000082
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000083 // If debug info or coverage generation is enabled, create the CGDebugInfo
84 // object.
85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86 CodeGenOpts.EmitGcovNotes)
87 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +000088
89 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +000090
John McCallf85e1932011-06-15 23:02:42 +000091 if (C.getLangOptions().ObjCAutoRefCount)
92 ARCData = new ARCEntrypoints();
93 RRData = new RREntrypoints();
94
John McCall5936e332011-02-15 09:22:45 +000095 // Initialize the type cache.
96 llvm::LLVMContext &LLVMContext = M.getContext();
John McCall0774cb82011-05-15 01:53:33 +000097 VoidTy = llvm::Type::getVoidTy(LLVMContext);
98 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
John McCall5936e332011-02-15 09:22:45 +0000101 PointerWidthInBits = C.Target.getPointerWidth(0);
John McCall34695852011-02-22 06:44:22 +0000102 PointerAlignInBytes =
103 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
John McCall5936e332011-02-15 09:22:45 +0000104 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
105 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
106 Int8PtrTy = Int8Ty->getPointerTo(0);
107 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000108}
109
110CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +0000111 delete Runtime;
John McCallf16aa102010-08-22 21:01:12 +0000112 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000113 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000114 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000115 delete ARCData;
116 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000117}
118
David Chisnall0d13f6f2010-01-23 02:40:42 +0000119void CodeGenModule::createObjCRuntime() {
120 if (!Features.NeXTRuntime)
121 Runtime = CreateGNUObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000122 else
123 Runtime = CreateMacObjCRuntime(*this);
124}
125
Ted Kremenek815c78f2008-08-05 18:50:11 +0000126void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000127 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000128 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000129 EmitCXXGlobalDtorFunc();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000130 if (Runtime)
131 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
132 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000133 EmitCtorList(GlobalCtors, "llvm.global_ctors");
134 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +0000135 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000136 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000137
John McCallb2593832010-09-16 06:16:50 +0000138 SimplifyPersonality();
139
John McCall744016d2010-07-06 23:57:41 +0000140 if (getCodeGenOpts().EmitDeclMetadata)
141 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000142
143 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000144 EmitCoverageFile();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000145}
146
Devang Patele80d5672011-03-23 16:29:39 +0000147void 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
Dan Gohman3d5aff52010-10-14 23:06:10 +0000154llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
155 if (!TBAA)
156 return 0;
157 return TBAA->getTBAAInfo(QTy);
158}
159
160void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
161 llvm::MDNode *TBAAInfo) {
162 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
163}
164
John McCall6374c332010-03-06 00:35:14 +0000165bool CodeGenModule::isTargetDarwin() const {
Daniel Dunbardb57a4c2011-04-19 21:43:27 +0000166 return getContext().Target.getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000167}
168
John McCall32096692011-03-18 02:56:14 +0000169void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
170 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
171 getDiags().Report(Context.getFullLoc(loc), diagID);
172}
173
Daniel Dunbar488e9932008-08-16 00:56:44 +0000174/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000175/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000176void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
177 bool OmitOnError) {
178 if (OmitOnError && getDiags().hasErrorOccurred())
179 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000180 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000181 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000182 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000183 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
184 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000185}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000186
Daniel Dunbar488e9932008-08-16 00:56:44 +0000187/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000188/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000189void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
190 bool OmitOnError) {
191 if (OmitOnError && getDiags().hasErrorOccurred())
192 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000193 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000194 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000195 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000196 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000197}
198
Mike Stump1eb44332009-09-09 15:08:12 +0000199void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000200 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000201 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000202 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000203 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000204 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000205 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000206
John McCallaf146032010-10-30 11:50:40 +0000207 // Set visibility for definitions.
208 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000209 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
210 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000211}
212
John McCallcbfe5022010-08-04 08:34:44 +0000213/// Set the symbol visibility of type information (vtable and RTTI)
214/// associated with the given type.
215void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
216 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000217 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000218 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000219
John McCall279b5eb2010-08-12 23:36:15 +0000220 if (!CodeGenOpts.HiddenWeakVTables)
221 return;
222
Anders Carlsson9a86a132011-01-29 20:36:11 +0000223 // We never want to drop the visibility for RTTI names.
224 if (TVK == TVK_ForRTTIName)
225 return;
226
John McCallcbfe5022010-08-04 08:34:44 +0000227 // We want to drop the visibility to hidden for weak type symbols.
228 // This isn't possible if there might be unresolved references
229 // elsewhere that rely on this symbol being visible.
230
John McCall7a536902010-08-05 20:39:18 +0000231 // This should be kept roughly in sync with setThunkVisibility
232 // in CGVTables.cpp.
233
John McCallcbfe5022010-08-04 08:34:44 +0000234 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000235 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000236 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
237 return;
238
239 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000240 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000241 return;
242
243 switch (RD->getTemplateSpecializationKind()) {
244 // We have to disable the optimization if this is an EI definition
245 // because there might be EI declarations in other shared objects.
246 case TSK_ExplicitInstantiationDefinition:
247 case TSK_ExplicitInstantiationDeclaration:
248 return;
249
John McCall7a536902010-08-05 20:39:18 +0000250 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000251 case TSK_Undeclared:
252 break;
253
John McCall7a536902010-08-05 20:39:18 +0000254 // In theory, implicit instantiations can ignore the possibility of
255 // an explicit instantiation declaration because there necessarily
256 // must be an EI definition somewhere with default visibility. In
257 // practice, it's possible to have an explicit instantiation for
258 // an arbitrary template class, and linkers aren't necessarily able
259 // to deal with mixed-visibility symbols.
260 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000261 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000262 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000263 return;
John McCallcbfe5022010-08-04 08:34:44 +0000264 break;
265 }
266
267 // If there's a key function, there may be translation units
268 // that don't have the key function's definition. But ignore
269 // this if we're emitting RTTI under -fno-rtti.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000270 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000271 if (Context.getKeyFunction(RD))
272 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000273 }
John McCallcbfe5022010-08-04 08:34:44 +0000274
275 // Otherwise, drop the visibility to hidden.
276 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000277 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000278}
279
Anders Carlsson793a9902010-06-22 16:05:32 +0000280llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
281 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
282
283 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
284 if (!Str.empty())
285 return Str;
286
John McCall4c40d982010-08-31 07:33:07 +0000287 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000288 IdentifierInfo *II = ND->getIdentifier();
289 assert(II && "Attempt to mangle unnamed decl.");
290
291 Str = II->getName();
292 return Str;
293 }
294
295 llvm::SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000296 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000297 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000298 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000299 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000300 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000301 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000302 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000303 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000304 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000305
306 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000307 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000308 size_t Length = Buffer.size();
309 char *Name = MangledNamesAllocator.Allocate<char>(Length);
310 std::copy(Buffer.begin(), Buffer.end(), Name);
311
312 Str = llvm::StringRef(Name, Length);
313
314 return Str;
315}
316
Peter Collingbourne14110472011-01-13 18:57:25 +0000317void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
318 const BlockDecl *BD) {
319 MangleContext &MangleCtx = getCXXABI().getMangleContext();
320 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000321 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000322 if (D == 0)
Rafael Espindolac4850c22011-02-10 23:59:36 +0000323 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000324 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000325 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000326 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000327 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000328 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000329 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000330}
331
John McCallf746aa62010-03-19 23:29:14 +0000332llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
333 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000334}
335
Chris Lattner6d397602008-03-14 17:18:18 +0000336/// AddGlobalCtor - Add a function to the list that will be called before
337/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000338void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000339 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000340 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000341}
342
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000343/// AddGlobalDtor - Add a function to the list that will be called
344/// when the module is unloaded.
345void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000346 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000347 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
348}
349
350void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
351 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000352 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000353 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000354
355 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000356 llvm::StructType *CtorStructTy =
Chris Lattner7650d952011-06-18 22:49:11 +0000357 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000358 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000359
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000360 // Construct the constructor and destructor arrays.
361 std::vector<llvm::Constant*> Ctors;
362 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
363 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000364 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000365 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000366 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000367 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000368 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000369
370 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000371 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000372 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000373 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000374 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000375 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000376 }
Chris Lattner6d397602008-03-14 17:18:18 +0000377}
378
Nate Begeman532485c2008-04-18 23:43:57 +0000379void CodeGenModule::EmitAnnotations() {
380 if (Annotations.empty())
381 return;
382
383 // Create a new global variable for the ConstantStruct in the Module.
384 llvm::Constant *Array =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000385 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000386 Annotations.size()),
387 Annotations);
Mike Stump1eb44332009-09-09 15:08:12 +0000388 llvm::GlobalValue *gv =
389 new llvm::GlobalVariable(TheModule, Array->getType(), false,
390 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000391 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000392 gv->setSection("llvm.metadata");
393}
394
John McCalld46f9852010-02-19 01:32:20 +0000395llvm::GlobalValue::LinkageTypes
396CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000397 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000398
Chris Lattnerf81530652010-06-30 16:58:07 +0000399 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000400 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000401
402 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000403 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000404
405 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000406 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000407
408 // In C99 mode, 'inline' functions are guaranteed to have a strong
409 // definition somewhere else, so we can use available_externally linkage.
410 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000411 return llvm::Function::AvailableExternallyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000412
413 // In C++, the compiler has to emit a definition in every translation unit
414 // that references the function. We should use linkonce_odr because
415 // a) if all references in this translation unit are optimized away, we
416 // don't need to codegen it. b) if the function persists, it needs to be
417 // merged with other definitions. c) C++ has the ODR, so we know the
418 // definition is dependable.
419 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000420 return !Context.getLangOptions().AppleKext
421 ? llvm::Function::LinkOnceODRLinkage
422 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000423
424 // An explicit instantiation of a template has weak linkage, since
425 // explicit instantiations can occur in multiple translation units
426 // and must all be equivalent. However, we are not allowed to
427 // throw away these explicit instantiations.
428 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000429 return !Context.getLangOptions().AppleKext
430 ? llvm::Function::WeakODRLinkage
431 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000432
433 // Otherwise, we have strong external linkage.
434 assert(Linkage == GVA_StrongExternal);
435 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000436}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000437
John McCalld46f9852010-02-19 01:32:20 +0000438
439/// SetFunctionDefinitionAttributes - Set attributes for a global.
440///
441/// FIXME: This is currently only done for aliases and functions, but not for
442/// variables (these details are set in EmitGlobalVarDefinition for variables).
443void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
444 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000445 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000446}
447
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000448void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000450 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000451 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000452 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000453 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000454 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000455 AttributeList.size()));
456 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000457}
458
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000459void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
460 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000461 if (CodeGenOpts.UnwindTables)
462 F->setHasUWTable();
463
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000464 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump1eb44332009-09-09 15:08:12 +0000465 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000466
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000467 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000468 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000470 if (D->hasAttr<NakedAttr>())
471 F->addFnAttr(llvm::Attribute::Naked);
472
Mike Stump1feade82009-08-26 22:31:08 +0000473 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000474 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000475
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000476 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
477 F->setUnnamedAddr(true);
478
Anders Carlssonfd015352009-11-16 16:56:03 +0000479 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
480 F->addFnAttr(llvm::Attribute::StackProtect);
481 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
482 F->addFnAttr(llvm::Attribute::StackProtectReq);
483
Sean Huntcf807c42010-08-18 23:23:40 +0000484 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
485 if (alignment)
486 F->setAlignment(alignment);
487
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000488 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000489 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
490 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000491}
492
Mike Stump1eb44332009-09-09 15:08:12 +0000493void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000494 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000495 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
496 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000497 else
498 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000499
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000500 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000501 AddUsedGlobal(GV);
502
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000503 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000504 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000505
506 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000507}
508
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000509void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
510 llvm::Function *F,
511 const CGFunctionInfo &FI) {
512 SetLLVMFunctionAttributes(D, FI, F);
513 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000514
515 F->setLinkage(llvm::Function::InternalLinkage);
516
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000517 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000518}
519
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000520void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000521 llvm::Function *F,
522 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000523 if (unsigned IID = F->getIntrinsicID()) {
524 // If this is an intrinsic function, set the function's attributes
525 // to the intrinsic's attributes.
526 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
527 return;
528 }
529
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000530 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
531
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000532 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000533 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000535 // Only a few attributes are set on declarations; these may later be
536 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000538 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000539 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000540 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000541 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000542 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000543 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000544 F->setLinkage(llvm::Function::ExternalWeakLinkage);
545 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000546 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000547
548 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
549 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
550 F->setVisibility(GetLLVMVisibility(LV.visibility()));
551 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000552 }
553
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000554 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000555 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000556}
557
Daniel Dunbar02698712009-02-13 20:29:50 +0000558void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000559 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000560 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000561 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000562}
563
564void CodeGenModule::EmitLLVMUsed() {
565 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000566 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000567 return;
568
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000569 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattner35f38a22009-03-31 22:37:52 +0000571 // Convert LLVMUsed to what ConstantArray needs.
572 std::vector<llvm::Constant*> UsedArray;
573 UsedArray.resize(LLVMUsed.size());
574 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 UsedArray[i] =
576 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000577 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000580 if (UsedArray.empty())
581 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000582 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000583
584 llvm::GlobalVariable *GV =
585 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000586 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000587 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000588 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000589
590 GV->setSection("llvm.metadata");
591}
592
593void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000594 // Emit code for any potentially referenced deferred decls. Since a
595 // previously unused static decl may become used during the generation of code
596 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000597
Anders Carlsson046c2942010-04-17 20:15:18 +0000598 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
599 if (!DeferredVTables.empty()) {
600 const CXXRecordDecl *RD = DeferredVTables.back();
601 DeferredVTables.pop_back();
602 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000603 continue;
604 }
605
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000606 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000607 DeferredDeclsToEmit.pop_back();
608
John McCallc76702c2010-05-27 01:45:30 +0000609 // Check to see if we've already emitted this. This is necessary
610 // for a couple of reasons: first, decls can end up in the
611 // deferred-decls queue multiple times, and second, decls can end
612 // up with definitions in unusual ways (e.g. by an extern inline
613 // function acquiring a strong function redefinition). Just
614 // ignore these cases.
615 //
616 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000617 llvm::StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000618 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000619 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner67b00522009-03-21 09:44:56 +0000621 if (!CGRef->isDeclaration())
622 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
John McCallc76702c2010-05-27 01:45:30 +0000624 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
625 // purposes an alias counts as a definition.
626 if (isa<llvm::GlobalAlias>(CGRef))
627 continue;
628
Chris Lattner67b00522009-03-21 09:44:56 +0000629 // Otherwise, emit the definition and move on to the next one.
630 EmitGlobalDefinition(D);
631 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000632}
633
Mike Stump1eb44332009-09-09 15:08:12 +0000634/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000635/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump1eb44332009-09-09 15:08:12 +0000636/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
637/// GlobalValue being annotated. The second field is the constant string
638/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000639/// string containing the name of the translation unit. The fourth field is
640/// the line number in the file of the annotated value declaration.
641///
642/// FIXME: this does not unique the annotation string constants, as llvm-gcc
643/// appears to.
644///
Mike Stump1eb44332009-09-09 15:08:12 +0000645llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000646 const AnnotateAttr *AA,
647 unsigned LineNo) {
648 llvm::Module *M = &getModule();
649
650 // get [N x i8] constants for the annotation string, and the filename string
651 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000652 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000653 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000654 AA->getAnnotation(), true);
655 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
656 M->getModuleIdentifier(),
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000657 true);
658
659 // Get the two global values corresponding to the ConstantArrays we just
660 // created to hold the bytes of the strings.
Mike Stump1eb44332009-09-09 15:08:12 +0000661 llvm::GlobalValue *annoGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000662 new llvm::GlobalVariable(*M, anno->getType(), false,
663 llvm::GlobalValue::PrivateLinkage, anno,
664 GV->getName());
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000665 // translation unit name string, emitted into the llvm.metadata section.
666 llvm::GlobalValue *unitGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000667 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump1eb44332009-09-09 15:08:12 +0000668 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner95b851e2009-07-16 05:03:48 +0000669 ".str");
Rafael Espindolad3d4e1e2011-01-17 22:22:52 +0000670 unitGV->setUnnamedAddr(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000671
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000672 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000673 llvm::Constant *Fields[4] = {
Owen Anderson3c4972d2009-07-29 18:54:39 +0000674 llvm::ConstantExpr::getBitCast(GV, SBP),
675 llvm::ConstantExpr::getBitCast(annoGV, SBP),
676 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson0032b272009-08-13 21:57:51 +0000677 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000678 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000679 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000680}
681
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000682bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000683 // Never defer when EmitAllDecls is specified.
684 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000685 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000686
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000687 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000688}
689
Rafael Espindola6a836702010-03-04 18:17:24 +0000690llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
691 const AliasAttr *AA = VD->getAttr<AliasAttr>();
692 assert(AA && "No alias?");
693
694 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
695
Rafael Espindola6a836702010-03-04 18:17:24 +0000696 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000697 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000698
699 llvm::Constant *Aliasee;
700 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000701 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
702 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000703 else
John McCallf746aa62010-03-19 23:29:14 +0000704 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000705 llvm::PointerType::getUnqual(DeclTy), 0);
706 if (!Entry) {
707 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
708 F->setLinkage(llvm::Function::ExternalWeakLinkage);
709 WeakRefReferences.insert(F);
710 }
711
712 return Aliasee;
713}
714
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000715void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000716 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Rafael Espindola6a836702010-03-04 18:17:24 +0000718 // Weak references don't produce any output by themselves.
719 if (Global->hasAttr<WeakRefAttr>())
720 return;
721
Chris Lattnerbd532712009-03-22 21:47:11 +0000722 // If this is an alias definition (which otherwise looks like a declaration)
723 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000724 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000725 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000726
Chris Lattner67b00522009-03-21 09:44:56 +0000727 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000728 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000729 if (FD->getIdentifier()) {
730 llvm::StringRef Name = FD->getName();
731 if (Name == "_Block_object_assign") {
732 BlockObjectAssignDecl = FD;
733 } else if (Name == "_Block_object_dispose") {
734 BlockObjectDisposeDecl = FD;
735 }
736 }
737
Daniel Dunbar73241df2009-02-13 21:18:01 +0000738 // Forward declarations are emitted lazily on first use.
Sean Hunt10620eb2011-05-06 20:44:56 +0000739 if (!FD->doesThisDeclarationHaveABody())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000740 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000741 } else {
742 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000743 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
744
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000745 if (VD->getIdentifier()) {
746 llvm::StringRef Name = VD->getName();
747 if (Name == "_NSConcreteGlobalBlock") {
748 NSConcreteGlobalBlockDecl = VD;
749 } else if (Name == "_NSConcreteStackBlock") {
750 NSConcreteStackBlockDecl = VD;
751 }
752 }
753
754
Douglas Gregora9a55c02010-02-06 05:15:45 +0000755 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000756 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000757 }
758
Chris Lattner67b00522009-03-21 09:44:56 +0000759 // Defer code generation when possible if this is a static definition, inline
760 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000761 if (!MayDeferGeneration(Global)) {
762 // Emit the definition if it can't be deferred.
763 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000764 return;
765 }
John McCallbf40cb52010-07-15 23:40:35 +0000766
767 // If we're deferring emission of a C++ variable with an
768 // initializer, remember the order in which it appeared in the file.
769 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
770 cast<VarDecl>(Global)->hasInit()) {
771 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
772 CXXGlobalInits.push_back(0);
773 }
Chris Lattner4357a822010-04-13 17:39:09 +0000774
775 // If the value has already been used, add it directly to the
776 // DeferredDeclsToEmit list.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000777 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000778 if (GetGlobalValue(MangledName))
779 DeferredDeclsToEmit.push_back(GD);
780 else {
781 // Otherwise, remember that we saw a deferred decl with this name. The
782 // first use of the mangled name will cause it to move into
783 // DeferredDeclsToEmit.
784 DeferredDecls[MangledName] = GD;
785 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000786}
787
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000788void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000789 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Dan Gohmancb421fa2010-04-19 16:39:44 +0000791 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000792 Context.getSourceManager(),
793 "Generating code for declaration");
794
Douglas Gregor44eac332010-07-13 06:02:28 +0000795 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
796 // At -O0, don't generate IR for functions with available_externally
797 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000798 if (CodeGenOpts.OptimizationLevel == 0 &&
799 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000800 getFunctionLinkage(Function)
801 == llvm::Function::AvailableExternallyLinkage)
802 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000803
Douglas Gregor44eac332010-07-13 06:02:28 +0000804 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000805 // 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
Douglas Gregor44eac332010-07-13 06:02:28 +0000814 if (Method->isVirtual())
815 getVTables().EmitThunks(GD);
816
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000817 return;
Douglas Gregor44eac332010-07-13 06:02:28 +0000818 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000819
Chris Lattnerb5e81562010-04-13 17:57:11 +0000820 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000821 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000822
823 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
824 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000825
826 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000827}
828
Chris Lattner74391b42009-03-22 21:03:39 +0000829/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
830/// module, create and return an llvm Function with the specified type. If there
831/// is something in the module with the specified name, return it potentially
832/// bitcasted to the right type.
833///
834/// If D is non-null, it specifies a decl that correspond to this. This is used
835/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000836llvm::Constant *
837CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
838 const llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +0000839 GlobalDecl D, bool ForVTable,
840 llvm::Attributes ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +0000841 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000842 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000843 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000844 if (WeakRefReferences.count(Entry)) {
845 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
846 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000847 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000848
849 WeakRefReferences.erase(Entry);
850 }
851
Chris Lattner0558e792009-03-21 09:25:43 +0000852 if (Entry->getType()->getElementType() == Ty)
853 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner0558e792009-03-21 09:25:43 +0000855 // Make sure the result is of the correct type.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000856 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000857 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Eli Friedman654ad402009-11-09 05:07:37 +0000860 // This function doesn't have a complete type (for example, the return
861 // type is an incomplete struct). Use a fake type instead, and make
862 // sure not to try to set attributes.
863 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000864
865 const llvm::FunctionType *FTy;
866 if (isa<llvm::FunctionType>(Ty)) {
867 FTy = cast<llvm::FunctionType>(Ty);
868 } else {
John McCall0774cb82011-05-15 01:53:33 +0000869 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +0000870 IsIncompleteFunction = true;
871 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000872
John McCall784f2112010-04-28 00:00:30 +0000873 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000874 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000875 MangledName, &getModule());
876 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000877 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000878 SetFunctionAttributes(D, F, IsIncompleteFunction);
John McCallf85e1932011-06-15 23:02:42 +0000879 if (ExtraAttrs != llvm::Attribute::None)
880 F->addFnAttr(ExtraAttrs);
Eli Friedman654ad402009-11-09 05:07:37 +0000881
Chris Lattner67b00522009-03-21 09:44:56 +0000882 // This is the first use or definition of a mangled name. If there is a
883 // deferred decl with this name, remember that we need to emit it at the end
884 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000885 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000886 if (DDI != DeferredDecls.end()) {
887 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
888 // list, and remove it from DeferredDecls (since we don't need it anymore).
889 DeferredDeclsToEmit.push_back(DDI->second);
890 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000891
892 // Otherwise, there are cases we have to worry about where we're
893 // using a declaration for which we must emit a definition but where
894 // we might not find a top-level definition:
895 // - member functions defined inline in their classes
896 // - friend functions defined inline in some class
897 // - special member functions with implicit definitions
898 // If we ever change our AST traversal to walk into class methods,
899 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000900 //
901 // We also don't emit a definition for a function if it's going to be an entry
902 // in a vtable, unless it's already marked as used.
Rafael Espindola01de7a42011-02-03 06:30:58 +0000903 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +0000904 // Look for a declaration that's lexically in a record.
905 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
906 do {
907 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000908 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +0000909 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +0000910 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000911 break;
Sean Hunt10620eb2011-05-06 20:44:56 +0000912 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +0000913 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000914 break;
915 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000916 }
John McCallbfdcdc82010-12-15 04:00:32 +0000917 FD = FD->getPreviousDeclaration();
918 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
John McCall784f2112010-04-28 00:00:30 +0000921 // Make sure the result is of the requested type.
922 if (!IsIncompleteFunction) {
923 assert(F->getType()->getElementType() == Ty);
924 return F;
925 }
926
927 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
928 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000929}
930
Chris Lattner74391b42009-03-22 21:03:39 +0000931/// GetAddrOfFunction - Return the address of the given function. If Ty is
932/// non-null, then this function will use the specified type if it has to
933/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000934llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000935 const llvm::Type *Ty,
936 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +0000937 // If there was no specific requested type, just convert it now.
938 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000939 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000940
Anders Carlsson9a20d552010-06-22 16:16:50 +0000941 llvm::StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000942 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +0000943}
Eli Friedman77ba7082008-05-30 19:50:47 +0000944
Chris Lattner74391b42009-03-22 21:03:39 +0000945/// CreateRuntimeFunction - Create a new runtime function with the specified
946/// type and name.
947llvm::Constant *
948CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCallf85e1932011-06-15 23:02:42 +0000949 llvm::StringRef Name,
950 llvm::Attributes ExtraAttrs) {
951 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
952 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +0000953}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000954
Douglas Gregorda550742011-05-07 22:06:45 +0000955static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
956 bool ConstantInit) {
John McCall88786862010-02-08 21:46:50 +0000957 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +0000958 return false;
Douglas Gregorda550742011-05-07 22:06:45 +0000959
960 if (Context.getLangOptions().CPlusPlus) {
961 if (const RecordType *Record
962 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
Douglas Gregor2bb11012011-05-13 01:05:07 +0000963 return ConstantInit &&
964 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
965 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
Eli Friedman20e098b2009-12-11 21:23:03 +0000966 }
Douglas Gregorda550742011-05-07 22:06:45 +0000967
Eli Friedman20e098b2009-12-11 21:23:03 +0000968 return true;
969}
970
Chris Lattner74391b42009-03-22 21:03:39 +0000971/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
972/// create and return an llvm GlobalVariable with the specified type. If there
973/// is something in the module with the specified name, return it potentially
974/// bitcasted to the right type.
975///
976/// If D is non-null, it specifies a decl that correspond to this. This is used
977/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000978llvm::Constant *
979CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
980 const llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +0000981 const VarDecl *D,
982 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000983 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000984 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000985 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000986 if (WeakRefReferences.count(Entry)) {
987 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000988 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000989
990 WeakRefReferences.erase(Entry);
991 }
992
Rafael Espindolac532b502011-01-18 21:07:57 +0000993 if (UnnamedAddr)
994 Entry->setUnnamedAddr(true);
995
Chris Lattner74391b42009-03-22 21:03:39 +0000996 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000997 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner99b53612009-03-21 08:03:33 +0000999 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001000 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001001 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner67b00522009-03-21 09:44:56 +00001003 // This is the first use or definition of a mangled name. If there is a
1004 // deferred decl with this name, remember that we need to emit it at the end
1005 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001006 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001007 if (DDI != DeferredDecls.end()) {
1008 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1009 // list, and remove it from DeferredDecls (since we don't need it anymore).
1010 DeferredDeclsToEmit.push_back(DDI->second);
1011 DeferredDecls.erase(DDI);
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
1014 llvm::GlobalVariable *GV =
1015 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001016 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001017 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +00001018 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +00001019
1020 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001021 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001022 // FIXME: This code is overly simple and should be merged with other global
1023 // handling.
Douglas Gregorda550742011-05-07 22:06:45 +00001024 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
Chris Lattner99b53612009-03-21 08:03:33 +00001025
John McCall110e8e52010-10-29 22:22:43 +00001026 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001027 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1028 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001029 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001030 } else {
1031 if (D->hasAttr<DLLImportAttr>())
1032 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001033 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001034 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001035
John McCallaf146032010-10-30 11:50:40 +00001036 // Set visibility on a declaration only if it's explicit.
1037 if (LV.visibilityExplicit())
1038 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001039 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001040
1041 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
John McCallf746aa62010-03-19 23:29:14 +00001044 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001045}
1046
Chris Lattner74391b42009-03-22 21:03:39 +00001047
Anders Carlsson3bd62022011-01-29 18:20:20 +00001048llvm::GlobalVariable *
1049CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1050 const llvm::Type *Ty,
1051 llvm::GlobalValue::LinkageTypes Linkage) {
1052 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1053 llvm::GlobalVariable *OldGV = 0;
1054
1055
1056 if (GV) {
1057 // Check if the variable has the right type.
1058 if (GV->getType()->getElementType() == Ty)
1059 return GV;
1060
1061 // Because C++ name mangling, the only way we can end up with an already
1062 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson96eaf292011-01-29 18:25:07 +00001063 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001064 OldGV = GV;
1065 }
1066
1067 // Create a new variable.
1068 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1069 Linkage, 0, Name);
1070
1071 if (OldGV) {
1072 // Replace occurrences of the old variable if needed.
1073 GV->takeName(OldGV);
1074
1075 if (!OldGV->use_empty()) {
1076 llvm::Constant *NewPtrForOldDecl =
1077 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1078 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1079 }
1080
1081 OldGV->eraseFromParent();
1082 }
1083
1084 return GV;
1085}
1086
Chris Lattner74391b42009-03-22 21:03:39 +00001087/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1088/// given global variable. If Ty is non-null and if the global doesn't exist,
1089/// then it will be greated with the specified type instead of whatever the
1090/// normal requested type would be.
1091llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1092 const llvm::Type *Ty) {
1093 assert(D->hasGlobalStorage() && "Not a global variable");
1094 QualType ASTTy = D->getType();
1095 if (Ty == 0)
1096 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
1098 const llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001099 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001100
Anders Carlsson9a20d552010-06-22 16:16:50 +00001101 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001102 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001103}
1104
1105/// CreateRuntimeVariable - Create a new runtime global variable with the
1106/// specified type and name.
1107llvm::Constant *
1108CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCallf746aa62010-03-19 23:29:14 +00001109 llvm::StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001110 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001111 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001112}
1113
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001114void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1115 assert(!D->getInit() && "Cannot emit definite definitions here!");
1116
Douglas Gregor7520bd12009-04-21 19:28:58 +00001117 if (MayDeferGeneration(D)) {
1118 // If we have not seen a reference to this variable yet, place it
1119 // into the deferred declarations table to be emitted if needed
1120 // later.
Anders Carlsson9a20d552010-06-22 16:16:50 +00001121 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001122 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001123 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001124 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001125 }
1126 }
1127
1128 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001129 EmitGlobalVarDefinition(D);
1130}
1131
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001132void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1133 if (DefinitionRequired)
1134 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1135}
1136
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001137llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001138CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedmancb5d2d02011-06-10 21:53:06 +00001139 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregordffb8012010-01-06 22:00:56 +00001140 return llvm::GlobalVariable::InternalLinkage;
1141
1142 if (const CXXMethodDecl *KeyFunction
1143 = RD->getASTContext().getKeyFunction(RD)) {
1144 // If this class has a key function, use that to determine the linkage of
1145 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001146 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001147 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001148 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001149
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001150 switch (KeyFunction->getTemplateSpecializationKind()) {
1151 case TSK_Undeclared:
1152 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001153 // When compiling with optimizations turned on, we emit all vtables,
1154 // even if the key function is not defined in the current translation
1155 // unit. If this is the case, use available_externally linkage.
1156 if (!Def && CodeGenOpts.OptimizationLevel)
1157 return llvm::GlobalVariable::AvailableExternallyLinkage;
1158
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001159 if (KeyFunction->isInlined())
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001160 return !Context.getLangOptions().AppleKext ?
1161 llvm::GlobalVariable::LinkOnceODRLinkage :
1162 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001163
1164 return llvm::GlobalVariable::ExternalLinkage;
1165
1166 case TSK_ImplicitInstantiation:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001167 return !Context.getLangOptions().AppleKext ?
1168 llvm::GlobalVariable::LinkOnceODRLinkage :
1169 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001170
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001171 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001172 return !Context.getLangOptions().AppleKext ?
1173 llvm::GlobalVariable::WeakODRLinkage :
1174 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001175
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001176 case TSK_ExplicitInstantiationDeclaration:
1177 // FIXME: Use available_externally linkage. However, this currently
1178 // breaks LLVM's build due to undefined symbols.
1179 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001180 return !Context.getLangOptions().AppleKext ?
1181 llvm::GlobalVariable::LinkOnceODRLinkage :
1182 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001183 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001184 }
1185
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001186 if (Context.getLangOptions().AppleKext)
1187 return llvm::Function::InternalLinkage;
1188
Douglas Gregordffb8012010-01-06 22:00:56 +00001189 switch (RD->getTemplateSpecializationKind()) {
1190 case TSK_Undeclared:
1191 case TSK_ExplicitSpecialization:
1192 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001193 // FIXME: Use available_externally linkage. However, this currently
1194 // breaks LLVM's build due to undefined symbols.
1195 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001196 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001197 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001198
1199 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001200 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001201 }
1202
1203 // Silence GCC warning.
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001204 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001205}
1206
Ken Dyck687cc4a2010-01-26 13:48:07 +00001207CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001208 return Context.toCharUnitsFromBits(
1209 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001210}
1211
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001212void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001213 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001214 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001215 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Sebastian Redl31310a22010-02-01 20:16:42 +00001217 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001218
1219 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001220 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001221 // implicitly initialized with { 0 }.
1222 //
1223 // Note that tentative definitions are only emitted at the end of
1224 // a translation unit, so they should never have incomplete
1225 // type. In addition, EmitTentativeDefinition makes sure that we
1226 // never attempt to emit a tentative definition if a real one
1227 // exists. A use may still exists, however, so we still may need
1228 // to do a RAUW.
1229 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001230 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001231 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001232 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001233 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001234 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001235 if (D->getType()->isReferenceType())
1236 T = D->getType();
1237
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001238 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001239 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001240 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001241 } else {
1242 ErrorUnsupported(D, "static initializer");
1243 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1244 }
John McCallbf40cb52010-07-15 23:40:35 +00001245 } else {
1246 // We don't need an initializer, so remove the entry for the delayed
1247 // initializer position (just in case this entry was delayed).
1248 if (getLangOptions().CPlusPlus)
1249 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001250 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001251 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001252
Chris Lattner2d584062009-03-21 08:13:05 +00001253 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001254 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Chris Lattner570585c2009-03-21 09:16:30 +00001256 // Strip off a bitcast if we got one back.
1257 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001258 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1259 // all zero index gep.
1260 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001261 Entry = CE->getOperand(0);
1262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattner570585c2009-03-21 09:16:30 +00001264 // Entry is now either a Function or GlobalVariable.
1265 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner570585c2009-03-21 09:16:30 +00001267 // We have a definition after a declaration with the wrong type.
1268 // We must make a new GlobalVariable* and update everything that used OldGV
1269 // (a declaration or tentative definition) with the new GlobalVariable*
1270 // (which will be a definition).
1271 //
1272 // This happens if there is a prototype for a global (e.g.
1273 // "extern int x[];") and then a definition of a different type (e.g.
1274 // "int x[10];"). This also happens when an initializer has a different type
1275 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001276 if (GV == 0 ||
1277 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001278 GV->getType()->getAddressSpace() !=
1279 getContext().getTargetAddressSpace(ASTTy)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001280
John McCallf746aa62010-03-19 23:29:14 +00001281 // Move the old entry aside so that we'll create a new one.
1282 Entry->setName(llvm::StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001283
Chris Lattner570585c2009-03-21 09:16:30 +00001284 // Make a new global with the correct type, this is now guaranteed to work.
1285 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001286
Eli Friedman77ba7082008-05-30 19:50:47 +00001287 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001288 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001289 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001290 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001291
1292 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001293 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001294 }
Devang Patel8e53e722007-10-26 16:31:40 +00001295
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001296 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001297 SourceManager &SM = Context.getSourceManager();
1298 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00001299 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001300 }
1301
Chris Lattner88a69ad2007-07-13 05:13:43 +00001302 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001303
1304 // If it is safe to mark the global 'constant', do so now.
1305 GV->setConstant(false);
Douglas Gregorda550742011-05-07 22:06:45 +00001306 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001307 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Ken Dyck8b752f12010-01-27 17:10:57 +00001309 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001310
Chris Lattner88a69ad2007-07-13 05:13:43 +00001311 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001312 llvm::GlobalValue::LinkageTypes Linkage =
1313 GetLLVMLinkageVarDefinition(D, GV);
1314 GV->setLinkage(Linkage);
1315 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001316 // common vars aren't constant even if declared const.
1317 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001318
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001319 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001320
John McCall3030eb82010-11-06 09:44:32 +00001321 // Emit the initializer function if necessary.
1322 if (NonConstInit)
1323 EmitCXXGlobalVarDeclInitFunc(D, GV);
1324
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001325 // Emit global variable debug information.
Devang Patelaa112892011-03-07 18:45:56 +00001326 if (CGDebugInfo *DI = getModuleDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001327 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001328 DI->EmitGlobalVariable(GV, D);
1329 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001330}
Reid Spencer5f016e22007-07-11 17:01:13 +00001331
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001332llvm::GlobalValue::LinkageTypes
1333CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1334 llvm::GlobalVariable *GV) {
1335 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1336 if (Linkage == GVA_Internal)
1337 return llvm::Function::InternalLinkage;
1338 else if (D->hasAttr<DLLImportAttr>())
1339 return llvm::Function::DLLImportLinkage;
1340 else if (D->hasAttr<DLLExportAttr>())
1341 return llvm::Function::DLLExportLinkage;
1342 else if (D->hasAttr<WeakAttr>()) {
1343 if (GV->isConstant())
1344 return llvm::GlobalVariable::WeakODRLinkage;
1345 else
1346 return llvm::GlobalVariable::WeakAnyLinkage;
1347 } else if (Linkage == GVA_TemplateInstantiation ||
1348 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001349 return llvm::GlobalVariable::WeakODRLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001350 else if (!getLangOptions().CPlusPlus &&
1351 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1352 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001353 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001354 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1355 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001356 // Thread local vars aren't considered common linkage.
1357 return llvm::GlobalVariable::CommonLinkage;
1358 }
1359 return llvm::GlobalVariable::ExternalLinkage;
1360}
1361
Chris Lattnerbdb01322009-05-05 06:16:31 +00001362/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1363/// implement a function with no prototype, e.g. "int foo() {}". If there are
1364/// existing call uses of the old function in the module, this adjusts them to
1365/// call the new function directly.
1366///
1367/// This is not just a cleanup: the always_inline pass requires direct calls to
1368/// functions to be able to inline them. If there is a bitcast in the way, it
1369/// won't inline them. Instcombine normally deletes these calls, but it isn't
1370/// run at -O0.
1371static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1372 llvm::Function *NewFn) {
1373 // If we're redefining a global as a function, don't transform it.
1374 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1375 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattnerbdb01322009-05-05 06:16:31 +00001377 const llvm::Type *NewRetTy = NewFn->getReturnType();
1378 llvm::SmallVector<llvm::Value*, 4> ArgList;
1379
1380 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001381 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001382 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001383 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1384 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001385 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001386 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001387 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattnerbdb01322009-05-05 06:16:31 +00001389 // If the return types don't match exactly, and if the call isn't dead, then
1390 // we can't transform this call.
1391 if (CI->getType() != NewRetTy && !CI->use_empty())
1392 continue;
1393
1394 // If the function was passed too few arguments, don't transform. If extra
1395 // arguments were passed, we silently drop them. If any of the types
1396 // mismatch, we don't transform.
1397 unsigned ArgNo = 0;
1398 bool DontTransform = false;
1399 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1400 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001401 if (CS.arg_size() == ArgNo ||
1402 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001403 DontTransform = true;
1404 break;
1405 }
1406 }
1407 if (DontTransform)
1408 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Chris Lattnerbdb01322009-05-05 06:16:31 +00001410 // Okay, we can transform this. Create the new call instruction and copy
1411 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001412 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001413 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1414 ArgList.end(), "", CI);
1415 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001416 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001417 NewCall->takeName(CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001418 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001419 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001420
1421 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001422 if (!CI->use_empty())
1423 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001424
Chris Lattnerc6034632010-04-01 06:31:43 +00001425 // Copy debug location attached to CI.
1426 if (!CI->getDebugLoc().isUnknown())
1427 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001428 CI->eraseFromParent();
1429 }
1430}
1431
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001432
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001433void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001434 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001435
John McCall1f6f9612011-03-09 08:12:35 +00001436 // Compute the function info and LLVM type.
John McCalld26bc762011-03-09 04:27:21 +00001437 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
John McCall1f6f9612011-03-09 08:12:35 +00001438 bool variadic = false;
1439 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1440 variadic = fpt->isVariadic();
1441 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
John McCalld26bc762011-03-09 04:27:21 +00001442
Chris Lattner9fa959d2009-05-12 20:58:15 +00001443 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001444 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattner0558e792009-03-21 09:25:43 +00001446 // Strip off a bitcast if we got one back.
1447 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1448 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1449 Entry = CE->getOperand(0);
1450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
1452
Chris Lattner0558e792009-03-21 09:25:43 +00001453 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001454 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Daniel Dunbar42745812009-03-09 23:53:08 +00001456 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001457 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001458 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001459
Chris Lattner62b33ea2009-03-21 08:38:50 +00001460 // F is the Function* for the one with the wrong type, we must make a new
1461 // Function* and update everything that used F (a declaration) with the new
1462 // Function* (which will be a definition).
1463 //
1464 // This happens if there is a prototype for a function
1465 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001466 // (e.g. "int f(int x)"). Move the old function aside so that it
1467 // doesn't interfere with GetAddrOfFunction.
1468 OldFn->setName(llvm::StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001469 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Chris Lattnerbdb01322009-05-05 06:16:31 +00001471 // If this is an implementation of a function without a prototype, try to
1472 // replace any existing uses of the function (which may be calls) with uses
1473 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001474 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001475 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001476 OldFn->removeDeadConstantUsers();
1477 }
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattner62b33ea2009-03-21 08:38:50 +00001479 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001480 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001481 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001482 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001483 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Chris Lattner62b33ea2009-03-21 08:38:50 +00001486 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001487 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Chris Lattner0558e792009-03-21 09:25:43 +00001489 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCall112c9672010-11-02 21:04:24 +00001492 // We need to set linkage and visibility on the function before
1493 // generating code for it because various parts of IR generation
1494 // want to propagate this information down (e.g. to local static
1495 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001496 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001497 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001498
John McCall112c9672010-11-02 21:04:24 +00001499 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001500 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001501
John McCalld26bc762011-03-09 04:27:21 +00001502 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001503
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001504 SetFunctionDefinitionAttributes(D, Fn);
1505 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001507 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001508 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001509 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001510 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001511}
1512
John McCallf746aa62010-03-19 23:29:14 +00001513void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1514 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001515 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001516 assert(AA && "Not an alias?");
1517
Anders Carlsson9a20d552010-06-22 16:16:50 +00001518 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
John McCallf746aa62010-03-19 23:29:14 +00001520 // If there is a definition in the module, then it wins over the alias.
1521 // This is dubious, but allow it to be safe. Just ignore the alias.
1522 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1523 if (Entry && !Entry->isDeclaration())
1524 return;
1525
1526 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001527
1528 // Create a reference to the named value. This ensures that it is emitted
1529 // if a deferred decl.
1530 llvm::Constant *Aliasee;
1531 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001532 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1533 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00001534 else
John McCallf746aa62010-03-19 23:29:14 +00001535 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001536 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001537
1538 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001539 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001540 new llvm::GlobalAlias(Aliasee->getType(),
1541 llvm::Function::ExternalLinkage,
1542 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Chris Lattnerbd532712009-03-22 21:47:11 +00001544 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001545 assert(Entry->isDeclaration());
1546
Chris Lattnerbd532712009-03-22 21:47:11 +00001547 // If there is a declaration in the module, then we had an extern followed
1548 // by the alias, as in:
1549 // extern int test6();
1550 // ...
1551 // int test6() __attribute__((alias("test7")));
1552 //
1553 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001554 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Owen Anderson3c4972d2009-07-29 18:54:39 +00001556 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001557 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001558 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001559 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001560 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001563 // Set attributes which are particular to an alias; this is a
1564 // specialization of the attributes which may be set on a global
1565 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001566 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001569 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001570 GA->setLinkage(llvm::Function::DLLExportLinkage);
1571 } else {
1572 GA->setLinkage(llvm::Function::DLLExportLinkage);
1573 }
Mike Stump1eb44332009-09-09 15:08:12 +00001574 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001575 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001576 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001577 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1578 }
1579
1580 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001581}
1582
Chris Lattnerb808c952009-03-22 21:56:56 +00001583/// getBuiltinLibFunction - Given a builtin id for a function like
1584/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbar34771b52009-09-14 04:33:21 +00001585llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1586 unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001587 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001588 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +00001589 "isn't a lib fn");
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor3e41d602009-02-13 23:20:09 +00001591 // Get the name, skip over the __builtin_ prefix (if necessary).
Joerg Sonnenberger4fe497d2011-05-13 21:12:10 +00001592 llvm::StringRef Name;
1593 GlobalDecl D(FD);
1594
1595 // If the builtin has been declared explicitly with an assembler label,
1596 // use the mangled name. This differs from the plain label on platforms
1597 // that prefix labels.
Joerg Sonnenberger62c296e2011-05-13 22:58:37 +00001598 if (FD->hasAttr<AsmLabelAttr>())
Joerg Sonnenberger4fe497d2011-05-13 21:12:10 +00001599 Name = getMangledName(D);
1600 else if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1601 Name = Context.BuiltinInfo.GetName(BuiltinID) + 10;
1602 else
1603 Name = Context.BuiltinInfo.GetName(BuiltinID);
1604
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Mike Stump1eb44332009-09-09 15:08:12 +00001606 const llvm::FunctionType *Ty =
Eli Friedman386ca782009-12-09 03:05:59 +00001607 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001608
Joerg Sonnenberger4fe497d2011-05-13 21:12:10 +00001609 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001610}
1611
Chris Lattner7acda7c2007-12-18 00:25:38 +00001612llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1613 unsigned NumTys) {
1614 return llvm::Intrinsic::getDeclaration(&getModule(),
1615 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1616}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001617
Daniel Dunbar1d552912009-07-23 22:52:48 +00001618static llvm::StringMapEntry<llvm::Constant*> &
1619GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1620 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001621 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001622 bool &IsUTF16,
1623 unsigned &StringLength) {
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001624 llvm::StringRef String = Literal->getString();
1625 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001626
Daniel Dunbarf015b032009-09-22 10:03:52 +00001627 // Check for simple case.
1628 if (!Literal->containsNonAsciiOrNull()) {
1629 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001630 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001631 }
1632
Daniel Dunbar1d552912009-07-23 22:52:48 +00001633 // Otherwise, convert the UTF8 literals into a byte string.
1634 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001635 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001636 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001638 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1639 &ToPtr, ToPtr + NumBytes,
1640 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001642 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001643 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001644
1645 // Render the UTF-16 string into a byte array and convert to the target byte
1646 // order.
1647 //
1648 // FIXME: This isn't something we should need to do here.
1649 llvm::SmallString<128> AsBytes;
1650 AsBytes.reserve(StringLength * 2);
1651 for (unsigned i = 0; i != StringLength; ++i) {
1652 unsigned short Val = ToBuf[i];
1653 if (TargetIsLSB) {
1654 AsBytes.push_back(Val & 0xFF);
1655 AsBytes.push_back(Val >> 8);
1656 } else {
1657 AsBytes.push_back(Val >> 8);
1658 AsBytes.push_back(Val & 0xFF);
1659 }
1660 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001661 // Append one extra null character, the second is automatically added by our
1662 // caller.
1663 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001664
Daniel Dunbar1d552912009-07-23 22:52:48 +00001665 IsUTF16 = true;
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001666 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001667}
1668
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001669static llvm::StringMapEntry<llvm::Constant*> &
1670GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1671 const StringLiteral *Literal,
1672 unsigned &StringLength)
1673{
1674 llvm::StringRef String = Literal->getString();
1675 StringLength = String.size();
1676 return Map.GetOrCreateValue(String);
1677}
1678
Daniel Dunbar1d552912009-07-23 22:52:48 +00001679llvm::Constant *
1680CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1681 unsigned StringLength = 0;
1682 bool isUTF16 = false;
1683 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001684 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001685 getTargetData().isLittleEndian(),
1686 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Daniel Dunbar1d552912009-07-23 22:52:48 +00001688 if (llvm::Constant *C = Entry.getValue())
1689 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Owen Anderson0032b272009-08-13 21:57:51 +00001691 llvm::Constant *Zero =
1692 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001693 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001695 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001696 if (!CFConstantStringClassRef) {
1697 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001698 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001699 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001700 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001701 // Decay array -> ptr
1702 CFConstantStringClassRef =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001703 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Anders Carlssone3daa762008-11-15 18:54:24 +00001706 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001707
Mike Stump1eb44332009-09-09 15:08:12 +00001708 const llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001709 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1710
Anders Carlsson5add6832009-08-16 05:55:31 +00001711 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001712
Anders Carlssonc9e20912007-08-21 00:21:21 +00001713 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001714 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlssonc9e20912007-08-21 00:21:21 +00001716 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001717 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001718 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001719 llvm::ConstantInt::get(Ty, 0x07C8);
1720
Anders Carlssonc9e20912007-08-21 00:21:21 +00001721 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001722 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001723
Chris Lattner95b851e2009-07-16 05:03:48 +00001724 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001725 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001726 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001727 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001728 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001729 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1730 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001731 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001732 } else {
Rafael Espindola584acf22011-03-14 17:55:00 +00001733 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1734 // when using private linkage. It is not clear if this is a bug in ld
1735 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00001736 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001737 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001738 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001739
Mike Stump1eb44332009-09-09 15:08:12 +00001740 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001741 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1742 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001743 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001744 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001745 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1746 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00001747 } else {
1748 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1749 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001750 }
Anders Carlsson5add6832009-08-16 05:55:31 +00001751 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1752
Anders Carlssonc9e20912007-08-21 00:21:21 +00001753 // String length.
1754 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001755 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Anders Carlssonc9e20912007-08-21 00:21:21 +00001757 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001758 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001759 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1760 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001761 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001762 if (const char *Sect = getContext().Target.getCFStringSection())
1763 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001764 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Anders Carlsson0c678292007-11-01 00:41:52 +00001766 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001767}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001768
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001769llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001770CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001771 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001772 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001773 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001774
1775 if (llvm::Constant *C = Entry.getValue())
1776 return C;
1777
1778 llvm::Constant *Zero =
1779 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1780 llvm::Constant *Zeros[] = { Zero, Zero };
1781
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001782 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001783 if (!ConstantStringClassRef) {
1784 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001785 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001786 llvm::Constant *GV;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001787 if (Features.ObjCNonFragileABI) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001788 std::string str =
1789 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1790 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001791 GV = getObjCRuntime().GetClassGlobal(str);
1792 // Make sure the result is of the correct type.
1793 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1794 ConstantStringClassRef =
1795 llvm::ConstantExpr::getBitCast(GV, PTy);
1796 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001797 std::string str =
1798 StringClass.empty() ? "_NSConstantStringClassReference"
1799 : "_" + StringClass + "ClassReference";
1800 const llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1801 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001802 // Decay array -> ptr
1803 ConstantStringClassRef =
1804 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001805 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001806 }
1807
1808 QualType NSTy = getContext().getNSConstantStringType();
1809
1810 const llvm::StructType *STy =
1811 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1812
1813 std::vector<llvm::Constant*> Fields(3);
1814
1815 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001816 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001817
1818 // String pointer.
1819 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1820
1821 llvm::GlobalValue::LinkageTypes Linkage;
1822 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001823 Linkage = llvm::GlobalValue::PrivateLinkage;
1824 isConstant = !Features.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001825
1826 llvm::GlobalVariable *GV =
1827 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1828 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001829 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001830 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1831 GV->setAlignment(Align.getQuantity());
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001832 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1833
1834 // String length.
1835 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1836 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1837
1838 // The struct.
1839 C = llvm::ConstantStruct::get(STy, Fields);
1840 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1841 llvm::GlobalVariable::PrivateLinkage, C,
1842 "_unnamed_nsstring_");
1843 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001844 if (const char *Sect =
1845 Features.ObjCNonFragileABI
1846 ? getContext().Target.getNSStringNonFragileABISection()
1847 : getContext().Target.getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001848 GV->setSection(Sect);
1849 Entry.setValue(GV);
1850
1851 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001852}
1853
Daniel Dunbar61432932008-08-13 23:20:05 +00001854/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001855/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001856std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dyck3b8037a2011-01-29 17:53:12 +00001857 const ASTContext &Context = getContext();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001858 const ConstantArrayType *CAT =
Ken Dyck3b8037a2011-01-29 17:53:12 +00001859 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar1e049762008-08-10 20:25:57 +00001860 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001862 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001863 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001865 if (E->isWide())
Ken Dyck3b8037a2011-01-29 17:53:12 +00001866 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001868 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001869 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Daniel Dunbar1e049762008-08-10 20:25:57 +00001871 return Str;
1872}
1873
Daniel Dunbar61432932008-08-13 23:20:05 +00001874/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1875/// constant array for the given string literal.
1876llvm::Constant *
1877CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1878 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001879 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1880 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1881 if (S->isWide()) {
1882 llvm::Type *DestTy =
1883 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1884 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1885 }
1886 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00001887}
1888
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001889/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1890/// array for the given ObjCEncodeExpr node.
1891llvm::Constant *
1892CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1893 std::string Str;
1894 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001895
1896 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001897}
1898
1899
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001900/// GenerateWritableString -- Creates storage for a string literal.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001901static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001902 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001903 CodeGenModule &CGM,
1904 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001905 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00001906 llvm::Constant *C =
1907 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001909 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00001910 llvm::GlobalVariable *GV =
1911 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1912 llvm::GlobalValue::PrivateLinkage,
1913 C, GlobalName);
Eli Friedmanb0dd6702011-05-27 22:13:20 +00001914 GV->setAlignment(1);
Rafael Espindola1257bc62011-01-10 22:34:03 +00001915 GV->setUnnamedAddr(true);
1916 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001917}
1918
Daniel Dunbar61432932008-08-13 23:20:05 +00001919/// GetAddrOfConstantString - Returns a pointer to a character array
1920/// containing the literal. This contents are exactly that of the
1921/// given string, i.e. it will not be null terminated automatically;
1922/// see GetAddrOfConstantCString. Note that whether the result is
1923/// actually a pointer to an LLVM constant depends on
1924/// Feature.WriteableStrings.
1925///
1926/// The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001927llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001928 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001929 bool IsConstant = !Features.WritableStrings;
1930
1931 // Get the default prefix if a name wasn't specified.
1932 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001933 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001934
1935 // Don't share any string literals if strings aren't constant.
1936 if (!IsConstant)
Benjamin Kramer9de43422011-03-05 13:45:23 +00001937 return GenerateStringLiteral(Str, false, *this, GlobalName);
Mike Stump1eb44332009-09-09 15:08:12 +00001938
1939 llvm::StringMapEntry<llvm::Constant *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00001940 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001941
1942 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001943 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001944
1945 // Create a global variable for this.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001946 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001947 Entry.setValue(C);
1948 return C;
1949}
Daniel Dunbar61432932008-08-13 23:20:05 +00001950
1951/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00001952/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00001953/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001954llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001955 const char *GlobalName){
Benjamin Kramer9de43422011-03-05 13:45:23 +00001956 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1957 return GetAddrOfConstantString(StrWithNull, GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001958}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001959
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001960/// EmitObjCPropertyImplementations - Emit information for synthesized
1961/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00001962void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001963 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001964 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001965 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001966 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001968 // Dynamic is just for type-checking.
1969 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1970 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1971
1972 // Determine which methods need to be implemented, some may have
1973 // been overridden. Note that ::isSynthesized is not the method
1974 // we want, that just indicates if the decl came from a
1975 // property. What we want to know is if the method is defined in
1976 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001977 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001978 CodeGenFunction(*this).GenerateObjCGetter(
1979 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001980 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001981 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001982 CodeGenFunction(*this).GenerateObjCSetter(
1983 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001984 }
1985 }
1986}
1987
John McCalle81ac692011-03-22 07:05:39 +00001988static bool needsDestructMethod(ObjCImplementationDecl *impl) {
1989 ObjCInterfaceDecl *iface
1990 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1991 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1992 ivar; ivar = ivar->getNextIvar())
1993 if (ivar->getType().isDestructedType())
1994 return true;
1995
1996 return false;
1997}
1998
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001999/// EmitObjCIvarInitializations - Emit information for ivar initialization
2000/// for an implementation.
2001void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002002 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2003 if (needsDestructMethod(D)) {
2004 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2005 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2006 ObjCMethodDecl *DTORMethod =
2007 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2008 cxxSelector, getContext().VoidTy, 0, D, true,
2009 false, true, false, ObjCMethodDecl::Required);
2010 D->addInstanceMethod(DTORMethod);
2011 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallf85e1932011-06-15 23:02:42 +00002012 D->setHasCXXStructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002013 }
2014
2015 // If the implementation doesn't have any ivar initializers, we don't need
2016 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002017 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002018 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002019
John McCalle81ac692011-03-22 07:05:39 +00002020 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2021 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002022 // The constructor returns 'self'.
2023 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2024 D->getLocation(),
2025 D->getLocation(), cxxSelector,
2026 getContext().getObjCIdType(), 0,
John McCalle81ac692011-03-22 07:05:39 +00002027 D, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002028 ObjCMethodDecl::Required);
2029 D->addInstanceMethod(CTORMethod);
2030 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallf85e1932011-06-15 23:02:42 +00002031 D->setHasCXXStructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002032}
2033
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002034/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002035void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002036 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002037 I != E; ++I)
2038 EmitTopLevelDecl(*I);
2039}
2040
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002041// EmitLinkageSpec - Emit all declarations in a linkage spec.
2042void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002043 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2044 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002045 ErrorUnsupported(LSD, "linkage spec");
2046 return;
2047 }
2048
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002049 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002050 I != E; ++I)
2051 EmitTopLevelDecl(*I);
2052}
2053
Daniel Dunbar41071de2008-08-15 23:26:23 +00002054/// EmitTopLevelDecl - Emit code for a single top level declaration.
2055void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2056 // If an error has occurred, stop code generation, but continue
2057 // parsing and semantic analysis (to ensure all warnings and errors
2058 // are emitted).
2059 if (Diags.hasErrorOccurred())
2060 return;
2061
Douglas Gregor16e8be22009-06-29 17:30:29 +00002062 // Ignore dependent declarations.
2063 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Daniel Dunbar41071de2008-08-15 23:26:23 +00002066 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002067 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002068 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002069 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002070 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002071 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2072 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002073 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002075 EmitGlobal(cast<FunctionDecl>(D));
2076 break;
2077
Daniel Dunbar41071de2008-08-15 23:26:23 +00002078 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002079 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002080 break;
2081
John McCall26fbc722011-04-12 01:01:22 +00002082 // Indirect fields from global anonymous structs and unions can be
2083 // ignored; only the actual variable requires IR gen support.
2084 case Decl::IndirectField:
2085 break;
2086
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002087 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002088 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002089 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002090 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002091 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002092 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002093 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002094 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002095 case Decl::ClassTemplate:
2096 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002097 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002098 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002099 case Decl::Block:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002100 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002101 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002102 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002103 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2104 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002105 return;
2106
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002107 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2108 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002109 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002110 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2111 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002112 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2113 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002114
2115 case Decl::StaticAssert:
2116 // Nothing to do.
2117 break;
2118
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002119 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002121 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002122 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002123 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00002124 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002125 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002126
Chris Lattnerbaf101d2011-04-09 07:11:53 +00002127 case Decl::ObjCCategory: {
2128 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2129 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2130 Context.ResetObjCLayout(CD->getClassInterface());
2131 break;
2132 }
Chris Lattner285d0db2009-04-01 02:36:43 +00002133
Daniel Dunbar41071de2008-08-15 23:26:23 +00002134 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002135 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002136 break;
2137
2138 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002139 // Categories have properties but don't support synthesize so we
2140 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002141 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2142 break;
2143
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002144 case Decl::ObjCImplementation: {
2145 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002146 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2147 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002148 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002149 EmitObjCIvarInitializations(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002150 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002151 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002152 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002153 case Decl::ObjCMethod: {
2154 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2155 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002156 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002157 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2158 break;
2159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002161 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002162 break;
2163
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002164 case Decl::LinkageSpec:
2165 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002166 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002167
2168 case Decl::FileScopeAsm: {
2169 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramer8d042582009-12-11 13:33:18 +00002170 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Daniel Dunbar41071de2008-08-15 23:26:23 +00002172 const std::string &S = getModule().getModuleInlineAsm();
2173 if (S.empty())
2174 getModule().setModuleInlineAsm(AsmString);
2175 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002176 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002177 break;
2178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
2180 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002181 // Make sure we handled everything we should, every other kind is a
2182 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2183 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002184 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2185 }
2186}
John McCall744016d2010-07-06 23:57:41 +00002187
2188/// Turns the given pointer into a constant.
2189static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2190 const void *Ptr) {
2191 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2192 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2193 return llvm::ConstantInt::get(i64, PtrInt);
2194}
2195
2196static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2197 llvm::NamedMDNode *&GlobalMetadata,
2198 GlobalDecl D,
2199 llvm::GlobalValue *Addr) {
2200 if (!GlobalMetadata)
2201 GlobalMetadata =
2202 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2203
2204 // TODO: should we report variant information for ctors/dtors?
2205 llvm::Value *Ops[] = {
2206 Addr,
2207 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2208 };
Jay Foad6f141652011-04-21 19:59:12 +00002209 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002210}
2211
2212/// Emits metadata nodes associating all the global values in the
2213/// current module with the Decls they came from. This is useful for
2214/// projects using IR gen as a subroutine.
2215///
2216/// Since there's currently no way to associate an MDNode directly
2217/// with an llvm::GlobalValue, we create a global named metadata
2218/// with the name 'clang.global.decl.ptrs'.
2219void CodeGenModule::EmitDeclMetadata() {
2220 llvm::NamedMDNode *GlobalMetadata = 0;
2221
2222 // StaticLocalDeclMap
2223 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2224 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2225 I != E; ++I) {
2226 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2227 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2228 }
2229}
2230
2231/// Emits metadata nodes for all the local variables in the current
2232/// function.
2233void CodeGenFunction::EmitDeclMetadata() {
2234 if (LocalDeclMap.empty()) return;
2235
2236 llvm::LLVMContext &Context = getLLVMContext();
2237
2238 // Find the unique metadata ID for this name.
2239 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2240
2241 llvm::NamedMDNode *GlobalMetadata = 0;
2242
2243 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2244 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2245 const Decl *D = I->first;
2246 llvm::Value *Addr = I->second;
2247
2248 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2249 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002250 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002251 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2252 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2253 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2254 }
2255 }
2256}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002257
Nick Lewycky3dc05412011-05-05 00:08:20 +00002258void CodeGenModule::EmitCoverageFile() {
2259 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002260 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2261 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2262 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002263 llvm::MDString *CoverageFile =
2264 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002265 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2266 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002267 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002268 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2269 GCov->addOperand(N);
2270 }
2271 }
2272 }
2273}
2274
Daniel Dunbar673431a2010-07-16 00:00:15 +00002275///@name Custom Runtime Function Interfaces
2276///@{
2277//
2278// FIXME: These can be eliminated once we can have clients just get the required
2279// AST nodes from the builtin tables.
2280
2281llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2282 if (BlockObjectDispose)
2283 return BlockObjectDispose;
2284
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002285 // If we saw an explicit decl, use that.
2286 if (BlockObjectDisposeDecl) {
2287 return BlockObjectDispose = GetAddrOfFunction(
2288 BlockObjectDisposeDecl,
2289 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2290 }
2291
2292 // Otherwise construct the function by hand.
John McCall0774cb82011-05-15 01:53:33 +00002293 const llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2294 const llvm::FunctionType *fty
2295 = llvm::FunctionType::get(VoidTy, args, false);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002296 return BlockObjectDispose =
John McCall0774cb82011-05-15 01:53:33 +00002297 CreateRuntimeFunction(fty, "_Block_object_dispose");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002298}
2299
2300llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2301 if (BlockObjectAssign)
2302 return BlockObjectAssign;
2303
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002304 // If we saw an explicit decl, use that.
2305 if (BlockObjectAssignDecl) {
2306 return BlockObjectAssign = GetAddrOfFunction(
2307 BlockObjectAssignDecl,
2308 getTypes().GetFunctionType(BlockObjectAssignDecl));
2309 }
2310
2311 // Otherwise construct the function by hand.
John McCall0774cb82011-05-15 01:53:33 +00002312 const llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2313 const llvm::FunctionType *fty
2314 = llvm::FunctionType::get(VoidTy, args, false);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002315 return BlockObjectAssign =
John McCall0774cb82011-05-15 01:53:33 +00002316 CreateRuntimeFunction(fty, "_Block_object_assign");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002317}
2318
2319llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2320 if (NSConcreteGlobalBlock)
2321 return NSConcreteGlobalBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002322
2323 // If we saw an explicit decl, use that.
2324 if (NSConcreteGlobalBlockDecl) {
2325 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2326 NSConcreteGlobalBlockDecl,
2327 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2328 }
2329
2330 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002331 return NSConcreteGlobalBlock =
2332 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002333}
2334
2335llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2336 if (NSConcreteStackBlock)
2337 return NSConcreteStackBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002338
2339 // If we saw an explicit decl, use that.
2340 if (NSConcreteStackBlockDecl) {
2341 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2342 NSConcreteStackBlockDecl,
2343 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2344 }
2345
2346 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002347 return NSConcreteStackBlock =
2348 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002349}
2350
2351///@}