blob: ed3a117ef7739652c821e827017f143b9e34d112 [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"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000040#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000041#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000042#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043using namespace clang;
44using namespace CodeGen;
45
John McCallf16aa102010-08-22 21:01:12 +000046static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47 switch (CGM.getContext().Target.getCXXABI()) {
48 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
51 }
52
53 llvm_unreachable("invalid C++ ABI kind");
54 return *CreateItaniumCXXABI(CGM);
55}
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057
Chandler Carruth2811ccf2009-11-12 17:24:48 +000058CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000059 llvm::Module &M, const llvm::TargetData &TD,
60 Diagnostic &diags)
Chris Lattnerbd360642009-03-26 05:00:52 +000061 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000062 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 McCallf16aa102010-08-22 21:01:12 +000067 VTables(*this), Runtime(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),
Daniel Dunbar673431a2010-07-16 00:00:15 +000073 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000074
Chris Lattner3c8f1532009-03-21 07:12:05 +000075 if (!Features.ObjC1)
76 Runtime = 0;
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
81 else
82 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000083
Dan Gohman3d5aff52010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000088
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000089 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson20f12a22009-12-06 18:00:51 +000090 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000091}
92
93CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000094 delete Runtime;
John McCallf16aa102010-08-22 21:01:12 +000095 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +000096 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +000097 delete DebugInfo;
98}
99
David Chisnall0d13f6f2010-01-23 02:40:42 +0000100void CodeGenModule::createObjCRuntime() {
101 if (!Features.NeXTRuntime)
102 Runtime = CreateGNUObjCRuntime(*this);
103 else if (Features.ObjCNonFragileABI)
104 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
105 else
106 Runtime = CreateMacObjCRuntime(*this);
107}
108
Ted Kremenek815c78f2008-08-05 18:50:11 +0000109void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000110 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000111 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000112 EmitCXXGlobalDtorFunc();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000113 if (Runtime)
114 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
115 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000116 EmitCtorList(GlobalCtors, "llvm.global_ctors");
117 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +0000118 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000119 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000120
John McCallb2593832010-09-16 06:16:50 +0000121 SimplifyPersonality();
122
John McCall744016d2010-07-06 23:57:41 +0000123 if (getCodeGenOpts().EmitDeclMetadata)
124 EmitDeclMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000125}
126
Dan Gohman3d5aff52010-10-14 23:06:10 +0000127llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
128 if (!TBAA)
129 return 0;
130 return TBAA->getTBAAInfo(QTy);
131}
132
133void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
134 llvm::MDNode *TBAAInfo) {
135 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
136}
137
John McCall6374c332010-03-06 00:35:14 +0000138bool CodeGenModule::isTargetDarwin() const {
139 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
140}
141
Daniel Dunbar488e9932008-08-16 00:56:44 +0000142/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000143/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000144void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
145 bool OmitOnError) {
146 if (OmitOnError && getDiags().hasErrorOccurred())
147 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000148 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000149 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000150 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000151 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
152 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000153}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000154
Daniel Dunbar488e9932008-08-16 00:56:44 +0000155/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000156/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000157void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
158 bool OmitOnError) {
159 if (OmitOnError && getDiags().hasErrorOccurred())
160 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000161 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000162 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000163 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000164 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000165}
166
John McCall110e8e52010-10-29 22:22:43 +0000167static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
168 switch (V) {
169 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
170 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
171 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
172 }
173 llvm_unreachable("unknown visibility!");
174 return llvm::GlobalValue::DefaultVisibility;
175}
176
177
Mike Stump1eb44332009-09-09 15:08:12 +0000178void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
John McCallaf146032010-10-30 11:50:40 +0000179 const NamedDecl *D,
180 bool IsForDefinition) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000181 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000182 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000183 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000184 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000185 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000186
John McCallaf146032010-10-30 11:50:40 +0000187 // Set visibility for definitions.
188 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
189 if (LV.visibilityExplicit() ||
190 (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
191 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000192}
193
John McCallcbfe5022010-08-04 08:34:44 +0000194/// Set the symbol visibility of type information (vtable and RTTI)
195/// associated with the given type.
196void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
197 const CXXRecordDecl *RD,
John McCallaf146032010-10-30 11:50:40 +0000198 bool IsForRTTI,
199 bool IsForDefinition) const {
200 setGlobalVisibility(GV, RD, IsForDefinition);
John McCallcbfe5022010-08-04 08:34:44 +0000201
John McCall279b5eb2010-08-12 23:36:15 +0000202 if (!CodeGenOpts.HiddenWeakVTables)
203 return;
204
John McCallcbfe5022010-08-04 08:34:44 +0000205 // We want to drop the visibility to hidden for weak type symbols.
206 // This isn't possible if there might be unresolved references
207 // elsewhere that rely on this symbol being visible.
208
John McCall7a536902010-08-05 20:39:18 +0000209 // This should be kept roughly in sync with setThunkVisibility
210 // in CGVTables.cpp.
211
John McCallcbfe5022010-08-04 08:34:44 +0000212 // Preconditions.
213 if (GV->getLinkage() != llvm::GlobalVariable::WeakODRLinkage ||
214 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
215 return;
216
217 // Don't override an explicit visibility attribute.
218 if (RD->hasAttr<VisibilityAttr>())
219 return;
220
221 switch (RD->getTemplateSpecializationKind()) {
222 // We have to disable the optimization if this is an EI definition
223 // because there might be EI declarations in other shared objects.
224 case TSK_ExplicitInstantiationDefinition:
225 case TSK_ExplicitInstantiationDeclaration:
226 return;
227
John McCall7a536902010-08-05 20:39:18 +0000228 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000229 case TSK_Undeclared:
230 break;
231
John McCall7a536902010-08-05 20:39:18 +0000232 // In theory, implicit instantiations can ignore the possibility of
233 // an explicit instantiation declaration because there necessarily
234 // must be an EI definition somewhere with default visibility. In
235 // practice, it's possible to have an explicit instantiation for
236 // an arbitrary template class, and linkers aren't necessarily able
237 // to deal with mixed-visibility symbols.
238 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000239 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000240 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000241 return;
John McCallcbfe5022010-08-04 08:34:44 +0000242 break;
243 }
244
245 // If there's a key function, there may be translation units
246 // that don't have the key function's definition. But ignore
247 // this if we're emitting RTTI under -fno-rtti.
248 if (!IsForRTTI || Features.RTTI)
249 if (Context.getKeyFunction(RD))
250 return;
251
252 // Otherwise, drop the visibility to hidden.
253 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000254 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000255}
256
Anders Carlsson793a9902010-06-22 16:05:32 +0000257llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
258 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
259
260 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
261 if (!Str.empty())
262 return Str;
263
John McCall4c40d982010-08-31 07:33:07 +0000264 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000265 IdentifierInfo *II = ND->getIdentifier();
266 assert(II && "Attempt to mangle unnamed decl.");
267
268 Str = II->getName();
269 return Str;
270 }
271
272 llvm::SmallString<256> Buffer;
273 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
John McCall4c40d982010-08-31 07:33:07 +0000274 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000275 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
John McCall4c40d982010-08-31 07:33:07 +0000276 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000277 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Peter Collingbourne14110472011-01-13 18:57:25 +0000278 getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000279 else
John McCall4c40d982010-08-31 07:33:07 +0000280 getCXXABI().getMangleContext().mangleName(ND, Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000281
282 // Allocate space for the mangled name.
283 size_t Length = Buffer.size();
284 char *Name = MangledNamesAllocator.Allocate<char>(Length);
285 std::copy(Buffer.begin(), Buffer.end(), Name);
286
287 Str = llvm::StringRef(Name, Length);
288
289 return Str;
290}
291
Peter Collingbourne14110472011-01-13 18:57:25 +0000292void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
293 const BlockDecl *BD) {
294 MangleContext &MangleCtx = getCXXABI().getMangleContext();
295 const Decl *D = GD.getDecl();
296 if (D == 0)
297 MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
298 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
299 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
300 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
301 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
302 else
303 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000304}
305
John McCallf746aa62010-03-19 23:29:14 +0000306llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
307 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000308}
309
Chris Lattner6d397602008-03-14 17:18:18 +0000310/// AddGlobalCtor - Add a function to the list that will be called before
311/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000312void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000313 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000314 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000315}
316
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000317/// AddGlobalDtor - Add a function to the list that will be called
318/// when the module is unloaded.
319void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000320 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000321 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
322}
323
324void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
325 // Ctor function type is void()*.
326 llvm::FunctionType* CtorFTy =
Mike Stump1eb44332009-09-09 15:08:12 +0000327 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000328 std::vector<const llvm::Type*>(),
329 false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000330 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000331
332 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump1eb44332009-09-09 15:08:12 +0000333 llvm::StructType* CtorStructTy =
334 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000335 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000336
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000337 // Construct the constructor and destructor arrays.
338 std::vector<llvm::Constant*> Ctors;
339 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
340 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000341 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000342 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000343 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000344 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000345 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000346
347 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000348 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000349 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000350 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000351 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000352 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000353 }
Chris Lattner6d397602008-03-14 17:18:18 +0000354}
355
Nate Begeman532485c2008-04-18 23:43:57 +0000356void CodeGenModule::EmitAnnotations() {
357 if (Annotations.empty())
358 return;
359
360 // Create a new global variable for the ConstantStruct in the Module.
361 llvm::Constant *Array =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000362 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000363 Annotations.size()),
364 Annotations);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 llvm::GlobalValue *gv =
366 new llvm::GlobalVariable(TheModule, Array->getType(), false,
367 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000368 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000369 gv->setSection("llvm.metadata");
370}
371
John McCalld46f9852010-02-19 01:32:20 +0000372llvm::GlobalValue::LinkageTypes
373CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000374 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000375
Chris Lattnerf81530652010-06-30 16:58:07 +0000376 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000377 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000378
379 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000380 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000381
382 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000383 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000384
385 // In C99 mode, 'inline' functions are guaranteed to have a strong
386 // definition somewhere else, so we can use available_externally linkage.
387 if (Linkage == GVA_C99Inline)
John McCalld46f9852010-02-19 01:32:20 +0000388 return llvm::Function::AvailableExternallyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000389
390 // In C++, the compiler has to emit a definition in every translation unit
391 // that references the function. We should use linkonce_odr because
392 // a) if all references in this translation unit are optimized away, we
393 // don't need to codegen it. b) if the function persists, it needs to be
394 // merged with other definitions. c) C++ has the ODR, so we know the
395 // definition is dependable.
396 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld46f9852010-02-19 01:32:20 +0000397 return llvm::Function::LinkOnceODRLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000398
399 // An explicit instantiation of a template has weak linkage, since
400 // explicit instantiations can occur in multiple translation units
401 // and must all be equivalent. However, we are not allowed to
402 // throw away these explicit instantiations.
403 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregor8f51a4f2010-03-13 18:23:07 +0000404 return llvm::Function::WeakODRLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000405
406 // Otherwise, we have strong external linkage.
407 assert(Linkage == GVA_StrongExternal);
408 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000409}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000410
John McCalld46f9852010-02-19 01:32:20 +0000411
412/// SetFunctionDefinitionAttributes - Set attributes for a global.
413///
414/// FIXME: This is currently only done for aliases and functions, but not for
415/// variables (these details are set in EmitGlobalVarDefinition for variables).
416void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
417 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000418 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000419}
420
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000421void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000422 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000423 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000424 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000425 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000426 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000427 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000428 AttributeList.size()));
429 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000430}
431
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000432void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
433 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000434 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump1eb44332009-09-09 15:08:12 +0000435 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000436
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000437 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000438 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000440 if (D->hasAttr<NakedAttr>())
441 F->addFnAttr(llvm::Attribute::Naked);
442
Mike Stump1feade82009-08-26 22:31:08 +0000443 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000444 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000445
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000446 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
447 F->setUnnamedAddr(true);
448
Anders Carlssonfd015352009-11-16 16:56:03 +0000449 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
450 F->addFnAttr(llvm::Attribute::StackProtect);
451 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
452 F->addFnAttr(llvm::Attribute::StackProtectReq);
453
Sean Huntcf807c42010-08-18 23:23:40 +0000454 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
455 if (alignment)
456 F->setAlignment(alignment);
457
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000458 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000459 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
460 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000461}
462
Mike Stump1eb44332009-09-09 15:08:12 +0000463void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000464 llvm::GlobalValue *GV) {
John McCall1fb0caa2010-10-22 21:05:15 +0000465 if (isa<NamedDecl>(D))
John McCallaf146032010-10-30 11:50:40 +0000466 setGlobalVisibility(GV, cast<NamedDecl>(D), /*ForDef*/ true);
John McCall1fb0caa2010-10-22 21:05:15 +0000467 else
468 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000469
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000470 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000471 AddUsedGlobal(GV);
472
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000473 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000474 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000475
476 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000477}
478
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000479void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
480 llvm::Function *F,
481 const CGFunctionInfo &FI) {
482 SetLLVMFunctionAttributes(D, FI, F);
483 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000484
485 F->setLinkage(llvm::Function::InternalLinkage);
486
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000487 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000488}
489
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000490void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000491 llvm::Function *F,
492 bool IsIncompleteFunction) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000493 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
494
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000495 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000496 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000498 // Only a few attributes are set on declarations; these may later be
499 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000501 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000502 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000503 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000504 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000505 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000506 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000507 F->setLinkage(llvm::Function::ExternalWeakLinkage);
508 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000509 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000510
511 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
512 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
513 F->setVisibility(GetLLVMVisibility(LV.visibility()));
514 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000515 }
516
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000517 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000518 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000519}
520
Daniel Dunbar02698712009-02-13 20:29:50 +0000521void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000522 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000523 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000524 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000525}
526
527void CodeGenModule::EmitLLVMUsed() {
528 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000529 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000530 return;
531
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000532 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Chris Lattner35f38a22009-03-31 22:37:52 +0000534 // Convert LLVMUsed to what ConstantArray needs.
535 std::vector<llvm::Constant*> UsedArray;
536 UsedArray.resize(LLVMUsed.size());
537 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000538 UsedArray[i] =
539 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000540 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000543 if (UsedArray.empty())
544 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000545 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000546
547 llvm::GlobalVariable *GV =
548 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000549 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000550 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000551 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000552
553 GV->setSection("llvm.metadata");
554}
555
556void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000557 // Emit code for any potentially referenced deferred decls. Since a
558 // previously unused static decl may become used during the generation of code
559 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000560
Anders Carlsson046c2942010-04-17 20:15:18 +0000561 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
562 if (!DeferredVTables.empty()) {
563 const CXXRecordDecl *RD = DeferredVTables.back();
564 DeferredVTables.pop_back();
565 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000566 continue;
567 }
568
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000569 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000570 DeferredDeclsToEmit.pop_back();
571
John McCallc76702c2010-05-27 01:45:30 +0000572 // Check to see if we've already emitted this. This is necessary
573 // for a couple of reasons: first, decls can end up in the
574 // deferred-decls queue multiple times, and second, decls can end
575 // up with definitions in unusual ways (e.g. by an extern inline
576 // function acquiring a strong function redefinition). Just
577 // ignore these cases.
578 //
579 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000580 llvm::StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000581 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000582 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner67b00522009-03-21 09:44:56 +0000584 if (!CGRef->isDeclaration())
585 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000586
John McCallc76702c2010-05-27 01:45:30 +0000587 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
588 // purposes an alias counts as a definition.
589 if (isa<llvm::GlobalAlias>(CGRef))
590 continue;
591
Chris Lattner67b00522009-03-21 09:44:56 +0000592 // Otherwise, emit the definition and move on to the next one.
593 EmitGlobalDefinition(D);
594 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000595}
596
Mike Stump1eb44332009-09-09 15:08:12 +0000597/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000598/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump1eb44332009-09-09 15:08:12 +0000599/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
600/// GlobalValue being annotated. The second field is the constant string
601/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000602/// string containing the name of the translation unit. The fourth field is
603/// the line number in the file of the annotated value declaration.
604///
605/// FIXME: this does not unique the annotation string constants, as llvm-gcc
606/// appears to.
607///
Mike Stump1eb44332009-09-09 15:08:12 +0000608llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000609 const AnnotateAttr *AA,
610 unsigned LineNo) {
611 llvm::Module *M = &getModule();
612
613 // get [N x i8] constants for the annotation string, and the filename string
614 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000615 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000616 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000617 AA->getAnnotation(), true);
618 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
619 M->getModuleIdentifier(),
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000620 true);
621
622 // Get the two global values corresponding to the ConstantArrays we just
623 // created to hold the bytes of the strings.
Mike Stump1eb44332009-09-09 15:08:12 +0000624 llvm::GlobalValue *annoGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000625 new llvm::GlobalVariable(*M, anno->getType(), false,
626 llvm::GlobalValue::PrivateLinkage, anno,
627 GV->getName());
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000628 // translation unit name string, emitted into the llvm.metadata section.
629 llvm::GlobalValue *unitGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000630 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump1eb44332009-09-09 15:08:12 +0000631 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner95b851e2009-07-16 05:03:48 +0000632 ".str");
Rafael Espindolad3d4e1e2011-01-17 22:22:52 +0000633 unitGV->setUnnamedAddr(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000634
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000635 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000636 llvm::Constant *Fields[4] = {
Owen Anderson3c4972d2009-07-29 18:54:39 +0000637 llvm::ConstantExpr::getBitCast(GV, SBP),
638 llvm::ConstantExpr::getBitCast(annoGV, SBP),
639 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson0032b272009-08-13 21:57:51 +0000640 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000641 };
Owen Anderson47a434f2009-08-05 23:18:46 +0000642 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000643}
644
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000645bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000646 // Never defer when EmitAllDecls is specified.
647 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000648 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000649
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000650 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000651}
652
Rafael Espindola6a836702010-03-04 18:17:24 +0000653llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
654 const AliasAttr *AA = VD->getAttr<AliasAttr>();
655 assert(AA && "No alias?");
656
657 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
658
Rafael Espindola6a836702010-03-04 18:17:24 +0000659 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000660 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000661
662 llvm::Constant *Aliasee;
663 if (isa<llvm::FunctionType>(DeclTy))
John McCallf746aa62010-03-19 23:29:14 +0000664 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola6a836702010-03-04 18:17:24 +0000665 else
John McCallf746aa62010-03-19 23:29:14 +0000666 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000667 llvm::PointerType::getUnqual(DeclTy), 0);
668 if (!Entry) {
669 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
670 F->setLinkage(llvm::Function::ExternalWeakLinkage);
671 WeakRefReferences.insert(F);
672 }
673
674 return Aliasee;
675}
676
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000677void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000678 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Rafael Espindola6a836702010-03-04 18:17:24 +0000680 // Weak references don't produce any output by themselves.
681 if (Global->hasAttr<WeakRefAttr>())
682 return;
683
Chris Lattnerbd532712009-03-22 21:47:11 +0000684 // If this is an alias definition (which otherwise looks like a declaration)
685 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000686 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000687 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000688
Chris Lattner67b00522009-03-21 09:44:56 +0000689 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000690 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000691 if (FD->getIdentifier()) {
692 llvm::StringRef Name = FD->getName();
693 if (Name == "_Block_object_assign") {
694 BlockObjectAssignDecl = FD;
695 } else if (Name == "_Block_object_dispose") {
696 BlockObjectDisposeDecl = FD;
697 }
698 }
699
Daniel Dunbar73241df2009-02-13 21:18:01 +0000700 // Forward declarations are emitted lazily on first use.
701 if (!FD->isThisDeclarationADefinition())
702 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000703 } else {
704 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000705 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
706
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000707 if (VD->getIdentifier()) {
708 llvm::StringRef Name = VD->getName();
709 if (Name == "_NSConcreteGlobalBlock") {
710 NSConcreteGlobalBlockDecl = VD;
711 } else if (Name == "_NSConcreteStackBlock") {
712 NSConcreteStackBlockDecl = VD;
713 }
714 }
715
716
Douglas Gregora9a55c02010-02-06 05:15:45 +0000717 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000718 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000719 }
720
Chris Lattner67b00522009-03-21 09:44:56 +0000721 // Defer code generation when possible if this is a static definition, inline
722 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000723 if (!MayDeferGeneration(Global)) {
724 // Emit the definition if it can't be deferred.
725 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000726 return;
727 }
John McCallbf40cb52010-07-15 23:40:35 +0000728
729 // If we're deferring emission of a C++ variable with an
730 // initializer, remember the order in which it appeared in the file.
731 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
732 cast<VarDecl>(Global)->hasInit()) {
733 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
734 CXXGlobalInits.push_back(0);
735 }
Chris Lattner4357a822010-04-13 17:39:09 +0000736
737 // If the value has already been used, add it directly to the
738 // DeferredDeclsToEmit list.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000739 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000740 if (GetGlobalValue(MangledName))
741 DeferredDeclsToEmit.push_back(GD);
742 else {
743 // Otherwise, remember that we saw a deferred decl with this name. The
744 // first use of the mangled name will cause it to move into
745 // DeferredDeclsToEmit.
746 DeferredDecls[MangledName] = GD;
747 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000748}
749
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000750void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000751 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Dan Gohmancb421fa2010-04-19 16:39:44 +0000753 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000754 Context.getSourceManager(),
755 "Generating code for declaration");
756
Douglas Gregor44eac332010-07-13 06:02:28 +0000757 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
758 // At -O0, don't generate IR for functions with available_externally
759 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000760 if (CodeGenOpts.OptimizationLevel == 0 &&
761 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000762 getFunctionLinkage(Function)
763 == llvm::Function::AvailableExternallyLinkage)
764 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000765
Douglas Gregor44eac332010-07-13 06:02:28 +0000766 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
767 if (Method->isVirtual())
768 getVTables().EmitThunks(GD);
769
770 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
771 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner4357a822010-04-13 17:39:09 +0000772
Douglas Gregor44eac332010-07-13 06:02:28 +0000773 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
774 return EmitCXXDestructor(DD, GD.getDtorType());
775 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000776
Chris Lattnerb5e81562010-04-13 17:57:11 +0000777 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000778 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000779
780 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
781 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000782
783 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000784}
785
Chris Lattner74391b42009-03-22 21:03:39 +0000786/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
787/// module, create and return an llvm Function with the specified type. If there
788/// is something in the module with the specified name, return it potentially
789/// bitcasted to the right type.
790///
791/// If D is non-null, it specifies a decl that correspond to this. This is used
792/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000793llvm::Constant *
794CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
795 const llvm::Type *Ty,
796 GlobalDecl D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000797 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000798 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000799 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000800 if (WeakRefReferences.count(Entry)) {
801 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
802 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000803 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000804
805 WeakRefReferences.erase(Entry);
806 }
807
Chris Lattner0558e792009-03-21 09:25:43 +0000808 if (Entry->getType()->getElementType() == Ty)
809 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattner0558e792009-03-21 09:25:43 +0000811 // Make sure the result is of the correct type.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000812 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000813 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000814 }
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Eli Friedman654ad402009-11-09 05:07:37 +0000816 // This function doesn't have a complete type (for example, the return
817 // type is an incomplete struct). Use a fake type instead, and make
818 // sure not to try to set attributes.
819 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000820
821 const llvm::FunctionType *FTy;
822 if (isa<llvm::FunctionType>(Ty)) {
823 FTy = cast<llvm::FunctionType>(Ty);
824 } else {
825 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
826 std::vector<const llvm::Type*>(), false);
Eli Friedman654ad402009-11-09 05:07:37 +0000827 IsIncompleteFunction = true;
828 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000829
John McCall784f2112010-04-28 00:00:30 +0000830 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000831 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000832 MangledName, &getModule());
833 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000834 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000835 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedman654ad402009-11-09 05:07:37 +0000836
Chris Lattner67b00522009-03-21 09:44:56 +0000837 // This is the first use or definition of a mangled name. If there is a
838 // deferred decl with this name, remember that we need to emit it at the end
839 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000840 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000841 if (DDI != DeferredDecls.end()) {
842 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
843 // list, and remove it from DeferredDecls (since we don't need it anymore).
844 DeferredDeclsToEmit.push_back(DDI->second);
845 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000846
847 // Otherwise, there are cases we have to worry about where we're
848 // using a declaration for which we must emit a definition but where
849 // we might not find a top-level definition:
850 // - member functions defined inline in their classes
851 // - friend functions defined inline in some class
852 // - special member functions with implicit definitions
853 // If we ever change our AST traversal to walk into class methods,
854 // this will be unnecessary.
855 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
856 // Look for a declaration that's lexically in a record.
857 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
858 do {
859 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
860 if (FD->isImplicit()) {
861 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
862 DeferredDeclsToEmit.push_back(D);
863 break;
864 } else if (FD->isThisDeclarationADefinition()) {
865 DeferredDeclsToEmit.push_back(D);
866 break;
867 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000868 }
John McCallbfdcdc82010-12-15 04:00:32 +0000869 FD = FD->getPreviousDeclaration();
870 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000871 }
Mike Stump1eb44332009-09-09 15:08:12 +0000872
John McCall784f2112010-04-28 00:00:30 +0000873 // Make sure the result is of the requested type.
874 if (!IsIncompleteFunction) {
875 assert(F->getType()->getElementType() == Ty);
876 return F;
877 }
878
879 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
880 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000881}
882
Chris Lattner74391b42009-03-22 21:03:39 +0000883/// GetAddrOfFunction - Return the address of the given function. If Ty is
884/// non-null, then this function will use the specified type if it has to
885/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000886llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner74391b42009-03-22 21:03:39 +0000887 const llvm::Type *Ty) {
888 // If there was no specific requested type, just convert it now.
889 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000890 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000891
Anders Carlsson9a20d552010-06-22 16:16:50 +0000892 llvm::StringRef MangledName = getMangledName(GD);
John McCallf746aa62010-03-19 23:29:14 +0000893 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattner74391b42009-03-22 21:03:39 +0000894}
Eli Friedman77ba7082008-05-30 19:50:47 +0000895
Chris Lattner74391b42009-03-22 21:03:39 +0000896/// CreateRuntimeFunction - Create a new runtime function with the specified
897/// type and name.
898llvm::Constant *
899CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCallf746aa62010-03-19 23:29:14 +0000900 llvm::StringRef Name) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000901 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattner74391b42009-03-22 21:03:39 +0000902}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000903
Eli Friedman20e098b2009-12-11 21:23:03 +0000904static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall88786862010-02-08 21:46:50 +0000905 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +0000906 return false;
907 if (Context.getLangOptions().CPlusPlus &&
908 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
909 // FIXME: We should do something fancier here!
910 return false;
911 }
912 return true;
913}
914
Chris Lattner74391b42009-03-22 21:03:39 +0000915/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
916/// create and return an llvm GlobalVariable with the specified type. If there
917/// is something in the module with the specified name, return it potentially
918/// bitcasted to the right type.
919///
920/// If D is non-null, it specifies a decl that correspond to this. This is used
921/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000922llvm::Constant *
923CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
924 const llvm::PointerType *Ty,
925 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000926 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000927 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000928 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000929 if (WeakRefReferences.count(Entry)) {
930 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000931 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000932
933 WeakRefReferences.erase(Entry);
934 }
935
Chris Lattner74391b42009-03-22 21:03:39 +0000936 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000937 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner99b53612009-03-21 08:03:33 +0000939 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +0000940 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner67b00522009-03-21 09:44:56 +0000943 // This is the first use or definition of a mangled name. If there is a
944 // deferred decl with this name, remember that we need to emit it at the end
945 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000946 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000947 if (DDI != DeferredDecls.end()) {
948 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
949 // list, and remove it from DeferredDecls (since we don't need it anymore).
950 DeferredDeclsToEmit.push_back(DDI->second);
951 DeferredDecls.erase(DDI);
952 }
Mike Stump1eb44332009-09-09 15:08:12 +0000953
954 llvm::GlobalVariable *GV =
955 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000956 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000957 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +0000958 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +0000959
960 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000961 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000962 // FIXME: This code is overly simple and should be merged with other global
963 // handling.
Eli Friedman20e098b2009-12-11 21:23:03 +0000964 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner99b53612009-03-21 08:03:33 +0000965
John McCall110e8e52010-10-29 22:22:43 +0000966 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +0000967 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
968 if (LV.linkage() != ExternalLinkage) {
John McCall110e8e52010-10-29 22:22:43 +0000969 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
970 } else {
971 if (D->hasAttr<DLLImportAttr>())
972 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
973 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
974 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +0000975
John McCallaf146032010-10-30 11:50:40 +0000976 // Set visibility on a declaration only if it's explicit.
977 if (LV.visibilityExplicit())
978 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +0000979 }
Eli Friedman56ebe502009-04-19 21:05:03 +0000980
981 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +0000982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
John McCallf746aa62010-03-19 23:29:14 +0000984 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000985}
986
Chris Lattner74391b42009-03-22 21:03:39 +0000987
988/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
989/// given global variable. If Ty is non-null and if the global doesn't exist,
990/// then it will be greated with the specified type instead of whatever the
991/// normal requested type would be.
992llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
993 const llvm::Type *Ty) {
994 assert(D->hasGlobalStorage() && "Not a global variable");
995 QualType ASTTy = D->getType();
996 if (Ty == 0)
997 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
999 const llvm::PointerType *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001000 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCallf746aa62010-03-19 23:29:14 +00001001
Anders Carlsson9a20d552010-06-22 16:16:50 +00001002 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001003 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001004}
1005
1006/// CreateRuntimeVariable - Create a new runtime global variable with the
1007/// specified type and name.
1008llvm::Constant *
1009CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCallf746aa62010-03-19 23:29:14 +00001010 llvm::StringRef Name) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001011 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
Chris Lattner74391b42009-03-22 21:03:39 +00001012}
1013
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001014void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1015 assert(!D->getInit() && "Cannot emit definite definitions here!");
1016
Douglas Gregor7520bd12009-04-21 19:28:58 +00001017 if (MayDeferGeneration(D)) {
1018 // If we have not seen a reference to this variable yet, place it
1019 // into the deferred declarations table to be emitted if needed
1020 // later.
Anders Carlsson9a20d552010-06-22 16:16:50 +00001021 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001022 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001023 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001024 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001025 }
1026 }
1027
1028 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001029 EmitGlobalVarDefinition(D);
1030}
1031
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001032void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1033 if (DefinitionRequired)
1034 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1035}
1036
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001037llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001038CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregordffb8012010-01-06 22:00:56 +00001039 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1040 return llvm::GlobalVariable::InternalLinkage;
1041
1042 if (const CXXMethodDecl *KeyFunction
1043 = RD->getASTContext().getKeyFunction(RD)) {
1044 // If this class has a key function, use that to determine the linkage of
1045 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001046 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001047 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001048 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001049
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001050 switch (KeyFunction->getTemplateSpecializationKind()) {
1051 case TSK_Undeclared:
1052 case TSK_ExplicitSpecialization:
1053 if (KeyFunction->isInlined())
1054 return llvm::GlobalVariable::WeakODRLinkage;
1055
1056 return llvm::GlobalVariable::ExternalLinkage;
1057
1058 case TSK_ImplicitInstantiation:
1059 case TSK_ExplicitInstantiationDefinition:
1060 return llvm::GlobalVariable::WeakODRLinkage;
1061
1062 case TSK_ExplicitInstantiationDeclaration:
1063 // FIXME: Use available_externally linkage. However, this currently
1064 // breaks LLVM's build due to undefined symbols.
1065 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1066 return llvm::GlobalVariable::WeakODRLinkage;
1067 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001068 }
1069
1070 switch (RD->getTemplateSpecializationKind()) {
1071 case TSK_Undeclared:
1072 case TSK_ExplicitSpecialization:
1073 case TSK_ImplicitInstantiation:
1074 case TSK_ExplicitInstantiationDefinition:
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001075 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregordffb8012010-01-06 22:00:56 +00001076
1077 case TSK_ExplicitInstantiationDeclaration:
1078 // FIXME: Use available_externally linkage. However, this currently
1079 // breaks LLVM's build due to undefined symbols.
1080 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1081 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001082 }
1083
1084 // Silence GCC warning.
1085 return llvm::GlobalVariable::WeakODRLinkage;
1086}
1087
Ken Dyck687cc4a2010-01-26 13:48:07 +00001088CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1089 return CharUnits::fromQuantity(
1090 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1091}
1092
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001093void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001094 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001095 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001096 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Sebastian Redl31310a22010-02-01 20:16:42 +00001098 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001099
1100 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001101 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001102 // implicitly initialized with { 0 }.
1103 //
1104 // Note that tentative definitions are only emitted at the end of
1105 // a translation unit, so they should never have incomplete
1106 // type. In addition, EmitTentativeDefinition makes sure that we
1107 // never attempt to emit a tentative definition if a real one
1108 // exists. A use may still exists, however, so we still may need
1109 // to do a RAUW.
1110 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001111 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001112 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001113 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001114 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001115 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001116 if (D->getType()->isReferenceType())
1117 T = D->getType();
1118
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001119 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001120 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001121 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001122 } else {
1123 ErrorUnsupported(D, "static initializer");
1124 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1125 }
John McCallbf40cb52010-07-15 23:40:35 +00001126 } else {
1127 // We don't need an initializer, so remove the entry for the delayed
1128 // initializer position (just in case this entry was delayed).
1129 if (getLangOptions().CPlusPlus)
1130 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001131 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001132 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001133
Chris Lattner2d584062009-03-21 08:13:05 +00001134 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001135 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner570585c2009-03-21 09:16:30 +00001137 // Strip off a bitcast if we got one back.
1138 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001139 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1140 // all zero index gep.
1141 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001142 Entry = CE->getOperand(0);
1143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Chris Lattner570585c2009-03-21 09:16:30 +00001145 // Entry is now either a Function or GlobalVariable.
1146 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chris Lattner570585c2009-03-21 09:16:30 +00001148 // We have a definition after a declaration with the wrong type.
1149 // We must make a new GlobalVariable* and update everything that used OldGV
1150 // (a declaration or tentative definition) with the new GlobalVariable*
1151 // (which will be a definition).
1152 //
1153 // This happens if there is a prototype for a global (e.g.
1154 // "extern int x[];") and then a definition of a different type (e.g.
1155 // "int x[10];"). This also happens when an initializer has a different type
1156 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001157 if (GV == 0 ||
1158 GV->getType()->getElementType() != InitType ||
1159 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCallf746aa62010-03-19 23:29:14 +00001161 // Move the old entry aside so that we'll create a new one.
1162 Entry->setName(llvm::StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001163
Chris Lattner570585c2009-03-21 09:16:30 +00001164 // Make a new global with the correct type, this is now guaranteed to work.
1165 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001166
Eli Friedman77ba7082008-05-30 19:50:47 +00001167 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001168 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001169 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001170 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001171
1172 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001173 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001174 }
Devang Patel8e53e722007-10-26 16:31:40 +00001175
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001176 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001177 SourceManager &SM = Context.getSourceManager();
1178 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00001179 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001180 }
1181
Chris Lattner88a69ad2007-07-13 05:13:43 +00001182 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001183
1184 // If it is safe to mark the global 'constant', do so now.
1185 GV->setConstant(false);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001186 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001187 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Ken Dyck8b752f12010-01-27 17:10:57 +00001189 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001190
Chris Lattner88a69ad2007-07-13 05:13:43 +00001191 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001192 llvm::GlobalValue::LinkageTypes Linkage =
1193 GetLLVMLinkageVarDefinition(D, GV);
1194 GV->setLinkage(Linkage);
1195 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001196 // common vars aren't constant even if declared const.
1197 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001198
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001199 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001200
John McCall3030eb82010-11-06 09:44:32 +00001201 // Emit the initializer function if necessary.
1202 if (NonConstInit)
1203 EmitCXXGlobalVarDeclInitFunc(D, GV);
1204
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001205 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +00001206 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001207 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001208 DI->EmitGlobalVariable(GV, D);
1209 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001210}
Reid Spencer5f016e22007-07-11 17:01:13 +00001211
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001212llvm::GlobalValue::LinkageTypes
1213CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1214 llvm::GlobalVariable *GV) {
1215 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1216 if (Linkage == GVA_Internal)
1217 return llvm::Function::InternalLinkage;
1218 else if (D->hasAttr<DLLImportAttr>())
1219 return llvm::Function::DLLImportLinkage;
1220 else if (D->hasAttr<DLLExportAttr>())
1221 return llvm::Function::DLLExportLinkage;
1222 else if (D->hasAttr<WeakAttr>()) {
1223 if (GV->isConstant())
1224 return llvm::GlobalVariable::WeakODRLinkage;
1225 else
1226 return llvm::GlobalVariable::WeakAnyLinkage;
1227 } else if (Linkage == GVA_TemplateInstantiation ||
1228 Linkage == GVA_ExplicitTemplateInstantiation)
1229 // FIXME: It seems like we can provide more specific linkage here
1230 // (LinkOnceODR, WeakODR).
1231 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001232 else if (!getLangOptions().CPlusPlus &&
1233 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1234 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001235 !D->hasExternalStorage() && !D->getInit() &&
1236 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1237 // Thread local vars aren't considered common linkage.
1238 return llvm::GlobalVariable::CommonLinkage;
1239 }
1240 return llvm::GlobalVariable::ExternalLinkage;
1241}
1242
Chris Lattnerbdb01322009-05-05 06:16:31 +00001243/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1244/// implement a function with no prototype, e.g. "int foo() {}". If there are
1245/// existing call uses of the old function in the module, this adjusts them to
1246/// call the new function directly.
1247///
1248/// This is not just a cleanup: the always_inline pass requires direct calls to
1249/// functions to be able to inline them. If there is a bitcast in the way, it
1250/// won't inline them. Instcombine normally deletes these calls, but it isn't
1251/// run at -O0.
1252static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1253 llvm::Function *NewFn) {
1254 // If we're redefining a global as a function, don't transform it.
1255 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1256 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattnerbdb01322009-05-05 06:16:31 +00001258 const llvm::Type *NewRetTy = NewFn->getReturnType();
1259 llvm::SmallVector<llvm::Value*, 4> ArgList;
1260
1261 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001262 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001263 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001264 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1265 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001266 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001267 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001268 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattnerbdb01322009-05-05 06:16:31 +00001270 // If the return types don't match exactly, and if the call isn't dead, then
1271 // we can't transform this call.
1272 if (CI->getType() != NewRetTy && !CI->use_empty())
1273 continue;
1274
1275 // If the function was passed too few arguments, don't transform. If extra
1276 // arguments were passed, we silently drop them. If any of the types
1277 // mismatch, we don't transform.
1278 unsigned ArgNo = 0;
1279 bool DontTransform = false;
1280 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1281 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001282 if (CS.arg_size() == ArgNo ||
1283 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001284 DontTransform = true;
1285 break;
1286 }
1287 }
1288 if (DontTransform)
1289 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattnerbdb01322009-05-05 06:16:31 +00001291 // Okay, we can transform this. Create the new call instruction and copy
1292 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001293 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001294 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1295 ArgList.end(), "", CI);
1296 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001297 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001298 NewCall->takeName(CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001299 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001300 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001301
1302 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001303 if (!CI->use_empty())
1304 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001305
Chris Lattnerc6034632010-04-01 06:31:43 +00001306 // Copy debug location attached to CI.
1307 if (!CI->getDebugLoc().isUnknown())
1308 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001309 CI->eraseFromParent();
1310 }
1311}
1312
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001313
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001314void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001315 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallc0bf4622010-02-23 00:48:20 +00001316 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001317 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001318 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Chris Lattner0558e792009-03-21 09:25:43 +00001320 // Strip off a bitcast if we got one back.
1321 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1322 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1323 Entry = CE->getOperand(0);
1324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
1326
Chris Lattner0558e792009-03-21 09:25:43 +00001327 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001328 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Daniel Dunbar42745812009-03-09 23:53:08 +00001330 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001331 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001332 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001333
Chris Lattner62b33ea2009-03-21 08:38:50 +00001334 // F is the Function* for the one with the wrong type, we must make a new
1335 // Function* and update everything that used F (a declaration) with the new
1336 // Function* (which will be a definition).
1337 //
1338 // This happens if there is a prototype for a function
1339 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001340 // (e.g. "int f(int x)"). Move the old function aside so that it
1341 // doesn't interfere with GetAddrOfFunction.
1342 OldFn->setName(llvm::StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001343 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattnerbdb01322009-05-05 06:16:31 +00001345 // If this is an implementation of a function without a prototype, try to
1346 // replace any existing uses of the function (which may be calls) with uses
1347 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001348 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001349 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001350 OldFn->removeDeadConstantUsers();
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Chris Lattner62b33ea2009-03-21 08:38:50 +00001353 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001354 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001355 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001356 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001357 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner62b33ea2009-03-21 08:38:50 +00001360 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001361 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner0558e792009-03-21 09:25:43 +00001363 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
John McCall112c9672010-11-02 21:04:24 +00001366 // We need to set linkage and visibility on the function before
1367 // generating code for it because various parts of IR generation
1368 // want to propagate this information down (e.g. to local static
1369 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001370 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001371 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001372
John McCall112c9672010-11-02 21:04:24 +00001373 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1374 setGlobalVisibility(Fn, D, /*ForDef*/ true);
1375
Daniel Dunbar219df662008-09-08 23:44:31 +00001376 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001377
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001378 SetFunctionDefinitionAttributes(D, Fn);
1379 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001381 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001382 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001383 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001384 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001385}
1386
John McCallf746aa62010-03-19 23:29:14 +00001387void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1388 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001389 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001390 assert(AA && "Not an alias?");
1391
Anders Carlsson9a20d552010-06-22 16:16:50 +00001392 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
John McCallf746aa62010-03-19 23:29:14 +00001394 // If there is a definition in the module, then it wins over the alias.
1395 // This is dubious, but allow it to be safe. Just ignore the alias.
1396 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1397 if (Entry && !Entry->isDeclaration())
1398 return;
1399
1400 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001401
1402 // Create a reference to the named value. This ensures that it is emitted
1403 // if a deferred decl.
1404 llvm::Constant *Aliasee;
1405 if (isa<llvm::FunctionType>(DeclTy))
John McCallf746aa62010-03-19 23:29:14 +00001406 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattnerbd532712009-03-22 21:47:11 +00001407 else
John McCallf746aa62010-03-19 23:29:14 +00001408 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001409 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001410
1411 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001412 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001413 new llvm::GlobalAlias(Aliasee->getType(),
1414 llvm::Function::ExternalLinkage,
1415 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattnerbd532712009-03-22 21:47:11 +00001417 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001418 assert(Entry->isDeclaration());
1419
Chris Lattnerbd532712009-03-22 21:47:11 +00001420 // If there is a declaration in the module, then we had an extern followed
1421 // by the alias, as in:
1422 // extern int test6();
1423 // ...
1424 // int test6() __attribute__((alias("test7")));
1425 //
1426 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001427 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Owen Anderson3c4972d2009-07-29 18:54:39 +00001429 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001430 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001431 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001432 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001433 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001436 // Set attributes which are particular to an alias; this is a
1437 // specialization of the attributes which may be set on a global
1438 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001439 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001440 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1441 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001442 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001443 GA->setLinkage(llvm::Function::DLLExportLinkage);
1444 } else {
1445 GA->setLinkage(llvm::Function::DLLExportLinkage);
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001448 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001449 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001450 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1451 }
1452
1453 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001454}
1455
Chris Lattnerb808c952009-03-22 21:56:56 +00001456/// getBuiltinLibFunction - Given a builtin id for a function like
1457/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbar34771b52009-09-14 04:33:21 +00001458llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1459 unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001460 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001461 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +00001462 "isn't a lib fn");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregor3e41d602009-02-13 23:20:09 +00001464 // Get the name, skip over the __builtin_ prefix (if necessary).
1465 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1466 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1467 Name += 10;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Mike Stump1eb44332009-09-09 15:08:12 +00001469 const llvm::FunctionType *Ty =
Eli Friedman386ca782009-12-09 03:05:59 +00001470 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001471
Daniel Dunbar34771b52009-09-14 04:33:21 +00001472 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001473}
1474
Chris Lattner7acda7c2007-12-18 00:25:38 +00001475llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1476 unsigned NumTys) {
1477 return llvm::Intrinsic::getDeclaration(&getModule(),
1478 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1479}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001480
Daniel Dunbar1d552912009-07-23 22:52:48 +00001481static llvm::StringMapEntry<llvm::Constant*> &
1482GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1483 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001484 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001485 bool &IsUTF16,
1486 unsigned &StringLength) {
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001487 llvm::StringRef String = Literal->getString();
1488 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001489
Daniel Dunbarf015b032009-09-22 10:03:52 +00001490 // Check for simple case.
1491 if (!Literal->containsNonAsciiOrNull()) {
1492 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001493 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001494 }
1495
Daniel Dunbar1d552912009-07-23 22:52:48 +00001496 // Otherwise, convert the UTF8 literals into a byte string.
1497 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001498 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001499 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001501 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1502 &ToPtr, ToPtr + NumBytes,
1503 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001505 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001506 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001507
1508 // Render the UTF-16 string into a byte array and convert to the target byte
1509 // order.
1510 //
1511 // FIXME: This isn't something we should need to do here.
1512 llvm::SmallString<128> AsBytes;
1513 AsBytes.reserve(StringLength * 2);
1514 for (unsigned i = 0; i != StringLength; ++i) {
1515 unsigned short Val = ToBuf[i];
1516 if (TargetIsLSB) {
1517 AsBytes.push_back(Val & 0xFF);
1518 AsBytes.push_back(Val >> 8);
1519 } else {
1520 AsBytes.push_back(Val >> 8);
1521 AsBytes.push_back(Val & 0xFF);
1522 }
1523 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001524 // Append one extra null character, the second is automatically added by our
1525 // caller.
1526 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001527
Daniel Dunbar1d552912009-07-23 22:52:48 +00001528 IsUTF16 = true;
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001529 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001530}
1531
1532llvm::Constant *
1533CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1534 unsigned StringLength = 0;
1535 bool isUTF16 = false;
1536 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001537 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001538 getTargetData().isLittleEndian(),
1539 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Daniel Dunbar1d552912009-07-23 22:52:48 +00001541 if (llvm::Constant *C = Entry.getValue())
1542 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Owen Anderson0032b272009-08-13 21:57:51 +00001544 llvm::Constant *Zero =
1545 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001546 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001548 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001549 if (!CFConstantStringClassRef) {
1550 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001551 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001552 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001553 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001554 // Decay array -> ptr
1555 CFConstantStringClassRef =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001556 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Anders Carlssone3daa762008-11-15 18:54:24 +00001559 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001560
Mike Stump1eb44332009-09-09 15:08:12 +00001561 const llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001562 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1563
Anders Carlsson5add6832009-08-16 05:55:31 +00001564 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001565
Anders Carlssonc9e20912007-08-21 00:21:21 +00001566 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001567 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Anders Carlssonc9e20912007-08-21 00:21:21 +00001569 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001570 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001571 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001572 llvm::ConstantInt::get(Ty, 0x07C8);
1573
Anders Carlssonc9e20912007-08-21 00:21:21 +00001574 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001575 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001576
Chris Lattner95b851e2009-07-16 05:03:48 +00001577 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001578 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001579 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001580 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001581 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001582 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1583 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001584 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001585 } else {
1586 Linkage = llvm::GlobalValue::PrivateLinkage;
1587 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001588 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001589
Mike Stump1eb44332009-09-09 15:08:12 +00001590 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001591 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1592 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001593 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001594 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001595 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1596 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001597 }
Anders Carlsson5add6832009-08-16 05:55:31 +00001598 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1599
Anders Carlssonc9e20912007-08-21 00:21:21 +00001600 // String length.
1601 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001602 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Anders Carlssonc9e20912007-08-21 00:21:21 +00001604 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001605 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001606 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1607 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001608 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001609 if (const char *Sect = getContext().Target.getCFStringSection())
1610 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001611 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Anders Carlsson0c678292007-11-01 00:41:52 +00001613 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001614}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001615
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001616llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001617CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001618 unsigned StringLength = 0;
1619 bool isUTF16 = false;
1620 llvm::StringMapEntry<llvm::Constant*> &Entry =
1621 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1622 getTargetData().isLittleEndian(),
1623 isUTF16, StringLength);
1624
1625 if (llvm::Constant *C = Entry.getValue())
1626 return C;
1627
1628 llvm::Constant *Zero =
1629 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1630 llvm::Constant *Zeros[] = { Zero, Zero };
1631
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001632 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001633 if (!ConstantStringClassRef) {
1634 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001635 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1636 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001637 llvm::Constant *GV;
1638 if (StringClass.empty())
1639 GV = CreateRuntimeVariable(Ty,
1640 Features.ObjCNonFragileABI ?
1641 "OBJC_CLASS_$_NSConstantString" :
1642 "_NSConstantStringClassReference");
1643 else {
1644 std::string str;
1645 if (Features.ObjCNonFragileABI)
1646 str = "OBJC_CLASS_$_" + StringClass;
1647 else
1648 str = "_" + StringClass + "ClassReference";
1649 GV = CreateRuntimeVariable(Ty, str);
1650 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001651 // Decay array -> ptr
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001652 ConstantStringClassRef =
1653 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001654 }
1655
1656 QualType NSTy = getContext().getNSConstantStringType();
1657
1658 const llvm::StructType *STy =
1659 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1660
1661 std::vector<llvm::Constant*> Fields(3);
1662
1663 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001664 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001665
1666 // String pointer.
1667 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1668
1669 llvm::GlobalValue::LinkageTypes Linkage;
1670 bool isConstant;
1671 if (isUTF16) {
1672 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1673 Linkage = llvm::GlobalValue::InternalLinkage;
1674 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1675 // does make plain ascii ones writable.
1676 isConstant = true;
1677 } else {
1678 Linkage = llvm::GlobalValue::PrivateLinkage;
1679 isConstant = !Features.WritableStrings;
1680 }
1681
1682 llvm::GlobalVariable *GV =
1683 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1684 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001685 GV->setUnnamedAddr(true);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001686 if (isUTF16) {
1687 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1688 GV->setAlignment(Align.getQuantity());
1689 }
1690 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1691
1692 // String length.
1693 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1694 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1695
1696 // The struct.
1697 C = llvm::ConstantStruct::get(STy, Fields);
1698 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1699 llvm::GlobalVariable::PrivateLinkage, C,
1700 "_unnamed_nsstring_");
1701 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001702 if (const char *Sect =
1703 Features.ObjCNonFragileABI
1704 ? getContext().Target.getNSStringNonFragileABISection()
1705 : getContext().Target.getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001706 GV->setSection(Sect);
1707 Entry.setValue(GV);
1708
1709 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001710}
1711
Daniel Dunbar61432932008-08-13 23:20:05 +00001712/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001713/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001714std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001715 const ConstantArrayType *CAT =
1716 getContext().getAsConstantArrayType(E->getType());
1717 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001719 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001720 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001722 if (E->isWide())
1723 RealLen *= getContext().Target.getWCharWidth()/8;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001725 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001726 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Daniel Dunbar1e049762008-08-10 20:25:57 +00001728 return Str;
1729}
1730
Daniel Dunbar61432932008-08-13 23:20:05 +00001731/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1732/// constant array for the given string literal.
1733llvm::Constant *
1734CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1735 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001736 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1737 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1738 if (S->isWide()) {
1739 llvm::Type *DestTy =
1740 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1741 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1742 }
1743 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00001744}
1745
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001746/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1747/// array for the given ObjCEncodeExpr node.
1748llvm::Constant *
1749CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1750 std::string Str;
1751 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001752
1753 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001754}
1755
1756
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001757/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001758static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001759 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001760 CodeGenModule &CGM,
1761 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001762 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00001763 llvm::Constant *C =
1764 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001766 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00001767 llvm::GlobalVariable *GV =
1768 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1769 llvm::GlobalValue::PrivateLinkage,
1770 C, GlobalName);
1771 GV->setUnnamedAddr(true);
1772 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001773}
1774
Daniel Dunbar61432932008-08-13 23:20:05 +00001775/// GetAddrOfConstantString - Returns a pointer to a character array
1776/// containing the literal. This contents are exactly that of the
1777/// given string, i.e. it will not be null terminated automatically;
1778/// see GetAddrOfConstantCString. Note that whether the result is
1779/// actually a pointer to an LLVM constant depends on
1780/// Feature.WriteableStrings.
1781///
1782/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001783llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1784 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001785 bool IsConstant = !Features.WritableStrings;
1786
1787 // Get the default prefix if a name wasn't specified.
1788 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001789 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001790
1791 // Don't share any string literals if strings aren't constant.
1792 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001793 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
1795 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner95b851e2009-07-16 05:03:48 +00001796 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001797
1798 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001799 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001800
1801 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001802 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001803 Entry.setValue(C);
1804 return C;
1805}
Daniel Dunbar61432932008-08-13 23:20:05 +00001806
1807/// GetAddrOfConstantCString - Returns a pointer to a character
1808/// array containing the literal and a terminating '\-'
1809/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001810llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1811 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001812 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001813}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001814
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001815/// EmitObjCPropertyImplementations - Emit information for synthesized
1816/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00001817void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001818 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001819 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001820 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001821 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001823 // Dynamic is just for type-checking.
1824 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1825 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1826
1827 // Determine which methods need to be implemented, some may have
1828 // been overridden. Note that ::isSynthesized is not the method
1829 // we want, that just indicates if the decl came from a
1830 // property. What we want to know is if the method is defined in
1831 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001832 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001833 CodeGenFunction(*this).GenerateObjCGetter(
1834 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001835 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001836 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001837 CodeGenFunction(*this).GenerateObjCSetter(
1838 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001839 }
1840 }
1841}
1842
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001843/// EmitObjCIvarInitializations - Emit information for ivar initialization
1844/// for an implementation.
1845void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1846 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1847 return;
1848 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1849 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1850 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1851 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1852 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1853 D->getLocation(),
1854 D->getLocation(), cxxSelector,
1855 getContext().VoidTy, 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001856 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001857 ObjCMethodDecl::Required);
1858 D->addInstanceMethod(DTORMethod);
1859 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1860
1861 II = &getContext().Idents.get(".cxx_construct");
1862 cxxSelector = getContext().Selectors.getSelector(0, &II);
1863 // The constructor returns 'self'.
1864 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1865 D->getLocation(),
1866 D->getLocation(), cxxSelector,
1867 getContext().getObjCIdType(), 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001868 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001869 ObjCMethodDecl::Required);
1870 D->addInstanceMethod(CTORMethod);
1871 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1872
1873
1874}
1875
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001876/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001877void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001878 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00001879 I != E; ++I)
1880 EmitTopLevelDecl(*I);
1881}
1882
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001883// EmitLinkageSpec - Emit all declarations in a linkage spec.
1884void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00001885 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1886 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001887 ErrorUnsupported(LSD, "linkage spec");
1888 return;
1889 }
1890
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001891 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001892 I != E; ++I)
1893 EmitTopLevelDecl(*I);
1894}
1895
Daniel Dunbar41071de2008-08-15 23:26:23 +00001896/// EmitTopLevelDecl - Emit code for a single top level declaration.
1897void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1898 // If an error has occurred, stop code generation, but continue
1899 // parsing and semantic analysis (to ensure all warnings and errors
1900 // are emitted).
1901 if (Diags.hasErrorOccurred())
1902 return;
1903
Douglas Gregor16e8be22009-06-29 17:30:29 +00001904 // Ignore dependent declarations.
1905 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1906 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Daniel Dunbar41071de2008-08-15 23:26:23 +00001908 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00001909 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001910 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001911 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00001912 // Skip function templates
1913 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1914 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001916 EmitGlobal(cast<FunctionDecl>(D));
1917 break;
1918
Daniel Dunbar41071de2008-08-15 23:26:23 +00001919 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001920 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001921 break;
1922
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001923 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001924 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001925 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001926 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001927 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00001928 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001929 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00001930 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00001931 case Decl::ClassTemplate:
1932 case Decl::FunctionTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00001933 case Decl::NamespaceAlias:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001934 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001935 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00001936 // Skip function templates
1937 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1938 return;
1939
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001940 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1941 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00001942 case Decl::CXXDestructor:
1943 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1944 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00001945
1946 case Decl::StaticAssert:
1947 // Nothing to do.
1948 break;
1949
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001950 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001952 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001953 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001954 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00001955 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00001956 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00001957
1958 case Decl::ObjCCategory: {
1959 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
1960 if (CD->IsClassExtension() && CD->hasSynthBitfield())
1961 Context.ResetObjCLayout(CD->getClassInterface());
1962 break;
1963 }
1964
Chris Lattner285d0db2009-04-01 02:36:43 +00001965
Daniel Dunbar41071de2008-08-15 23:26:23 +00001966 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001967 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001968 break;
1969
1970 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001971 // Categories have properties but don't support synthesize so we
1972 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001973 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1974 break;
1975
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001976 case Decl::ObjCImplementation: {
1977 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00001978 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
1979 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001980 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001981 EmitObjCIvarInitializations(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001982 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001983 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001984 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001985 case Decl::ObjCMethod: {
1986 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1987 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001988 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00001989 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1990 break;
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001993 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001994 break;
1995
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001996 case Decl::LinkageSpec:
1997 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001998 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001999
2000 case Decl::FileScopeAsm: {
2001 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramer8d042582009-12-11 13:33:18 +00002002 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Daniel Dunbar41071de2008-08-15 23:26:23 +00002004 const std::string &S = getModule().getModuleInlineAsm();
2005 if (S.empty())
2006 getModule().setModuleInlineAsm(AsmString);
2007 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002008 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002009 break;
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
2012 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002013 // Make sure we handled everything we should, every other kind is a
2014 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2015 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002016 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2017 }
2018}
John McCall744016d2010-07-06 23:57:41 +00002019
2020/// Turns the given pointer into a constant.
2021static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2022 const void *Ptr) {
2023 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2024 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2025 return llvm::ConstantInt::get(i64, PtrInt);
2026}
2027
2028static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2029 llvm::NamedMDNode *&GlobalMetadata,
2030 GlobalDecl D,
2031 llvm::GlobalValue *Addr) {
2032 if (!GlobalMetadata)
2033 GlobalMetadata =
2034 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2035
2036 // TODO: should we report variant information for ctors/dtors?
2037 llvm::Value *Ops[] = {
2038 Addr,
2039 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2040 };
2041 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2042}
2043
2044/// Emits metadata nodes associating all the global values in the
2045/// current module with the Decls they came from. This is useful for
2046/// projects using IR gen as a subroutine.
2047///
2048/// Since there's currently no way to associate an MDNode directly
2049/// with an llvm::GlobalValue, we create a global named metadata
2050/// with the name 'clang.global.decl.ptrs'.
2051void CodeGenModule::EmitDeclMetadata() {
2052 llvm::NamedMDNode *GlobalMetadata = 0;
2053
2054 // StaticLocalDeclMap
2055 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2056 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2057 I != E; ++I) {
2058 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2059 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2060 }
2061}
2062
2063/// Emits metadata nodes for all the local variables in the current
2064/// function.
2065void CodeGenFunction::EmitDeclMetadata() {
2066 if (LocalDeclMap.empty()) return;
2067
2068 llvm::LLVMContext &Context = getLLVMContext();
2069
2070 // Find the unique metadata ID for this name.
2071 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2072
2073 llvm::NamedMDNode *GlobalMetadata = 0;
2074
2075 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2076 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2077 const Decl *D = I->first;
2078 llvm::Value *Addr = I->second;
2079
2080 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2081 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2082 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2083 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2084 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2085 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2086 }
2087 }
2088}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002089
2090///@name Custom Runtime Function Interfaces
2091///@{
2092//
2093// FIXME: These can be eliminated once we can have clients just get the required
2094// AST nodes from the builtin tables.
2095
2096llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2097 if (BlockObjectDispose)
2098 return BlockObjectDispose;
2099
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002100 // If we saw an explicit decl, use that.
2101 if (BlockObjectDisposeDecl) {
2102 return BlockObjectDispose = GetAddrOfFunction(
2103 BlockObjectDisposeDecl,
2104 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2105 }
2106
2107 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002108 const llvm::FunctionType *FTy;
2109 std::vector<const llvm::Type*> ArgTys;
2110 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2111 ArgTys.push_back(PtrToInt8Ty);
2112 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2113 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2114 return BlockObjectDispose =
2115 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2116}
2117
2118llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2119 if (BlockObjectAssign)
2120 return BlockObjectAssign;
2121
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002122 // If we saw an explicit decl, use that.
2123 if (BlockObjectAssignDecl) {
2124 return BlockObjectAssign = GetAddrOfFunction(
2125 BlockObjectAssignDecl,
2126 getTypes().GetFunctionType(BlockObjectAssignDecl));
2127 }
2128
2129 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002130 const llvm::FunctionType *FTy;
2131 std::vector<const llvm::Type*> ArgTys;
2132 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2133 ArgTys.push_back(PtrToInt8Ty);
2134 ArgTys.push_back(PtrToInt8Ty);
2135 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2136 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2137 return BlockObjectAssign =
2138 CreateRuntimeFunction(FTy, "_Block_object_assign");
2139}
2140
2141llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2142 if (NSConcreteGlobalBlock)
2143 return NSConcreteGlobalBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002144
2145 // If we saw an explicit decl, use that.
2146 if (NSConcreteGlobalBlockDecl) {
2147 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2148 NSConcreteGlobalBlockDecl,
2149 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2150 }
2151
2152 // Otherwise construct the variable by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002153 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2154 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2155}
2156
2157llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2158 if (NSConcreteStackBlock)
2159 return NSConcreteStackBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002160
2161 // If we saw an explicit decl, use that.
2162 if (NSConcreteStackBlockDecl) {
2163 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2164 NSConcreteStackBlockDecl,
2165 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2166 }
2167
2168 // Otherwise construct the variable by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002169 return NSConcreteStackBlock = CreateRuntimeVariable(
2170 PtrToInt8Ty, "_NSConcreteStackBlock");
2171}
2172
2173///@}