blob: 057182d0392b5be6bf289e2e1b90d1701de13436 [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"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000020#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000021#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000023#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000025#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000026#include "clang/AST/DeclTemplate.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000027#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000029#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000032#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000033#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000034#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "llvm/Intrinsics.h"
Chris Lattnerd5b89022009-12-28 21:44:41 +000036#include "llvm/LLVMContext.h"
John McCall6374c332010-03-06 00:35:14 +000037#include "llvm/ADT/Triple.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000038#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000039#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000040#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42using namespace CodeGen;
43
44
Chandler Carruth2811ccf2009-11-12 17:24:48 +000045CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000046 llvm::Module &M, const llvm::TargetData &TD,
47 Diagnostic &diags)
Chris Lattnerbd360642009-03-26 05:00:52 +000048 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000049 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000050 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000051 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
Charles Davis3a811f12010-05-25 19:52:27 +000052 VTables(*this), Runtime(0), ABI(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000053 CFConstantStringClassRef(0), NSConstantStringClassRef(0),
54 VMContext(M.getContext()),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000055 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000056 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000057 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000058 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000059
Chris Lattner3c8f1532009-03-21 07:12:05 +000060 if (!Features.ObjC1)
61 Runtime = 0;
62 else if (!Features.NeXTRuntime)
63 Runtime = CreateGNUObjCRuntime(*this);
64 else if (Features.ObjCNonFragileABI)
65 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
66 else
67 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000068
Charles Davis3a811f12010-05-25 19:52:27 +000069 if (!Features.CPlusPlus)
70 ABI = 0;
71 else createCXXABI();
72
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000073 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson20f12a22009-12-06 18:00:51 +000074 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000075}
76
77CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000078 delete Runtime;
Charles Davis3a811f12010-05-25 19:52:27 +000079 delete ABI;
Ted Kremenek815c78f2008-08-05 18:50:11 +000080 delete DebugInfo;
81}
82
David Chisnall0d13f6f2010-01-23 02:40:42 +000083void CodeGenModule::createObjCRuntime() {
84 if (!Features.NeXTRuntime)
85 Runtime = CreateGNUObjCRuntime(*this);
86 else if (Features.ObjCNonFragileABI)
87 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
88 else
89 Runtime = CreateMacObjCRuntime(*this);
90}
91
Charles Davis3a811f12010-05-25 19:52:27 +000092void CodeGenModule::createCXXABI() {
Charles Davis98b7c5c2010-06-11 01:06:47 +000093 if (Context.Target.getCXXABI() == "microsoft")
94 ABI = CreateMicrosoftCXXABI(*this);
95 else
96 ABI = CreateItaniumCXXABI(*this);
Charles Davis3a811f12010-05-25 19:52:27 +000097}
98
Ted Kremenek815c78f2008-08-05 18:50:11 +000099void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000100 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000101 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000102 EmitCXXGlobalDtorFunc();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000103 if (Runtime)
104 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
105 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000106 EmitCtorList(GlobalCtors, "llvm.global_ctors");
107 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +0000108 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000109 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000110
111 if (getCodeGenOpts().EmitDeclMetadata)
112 EmitDeclMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000113}
114
John McCall6374c332010-03-06 00:35:14 +0000115bool CodeGenModule::isTargetDarwin() const {
116 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
117}
118
Daniel Dunbar488e9932008-08-16 00:56:44 +0000119/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000120/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000121void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
122 bool OmitOnError) {
123 if (OmitOnError && getDiags().hasErrorOccurred())
124 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000125 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000126 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000127 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000128 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
129 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000130}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000131
Daniel Dunbar488e9932008-08-16 00:56:44 +0000132/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000133/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000134void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
135 bool OmitOnError) {
136 if (OmitOnError && getDiags().hasErrorOccurred())
137 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000138 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000139 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000140 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000141 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000142}
143
Mike Stump1eb44332009-09-09 15:08:12 +0000144LangOptions::VisibilityMode
Daniel Dunbar04d40782009-04-14 06:00:08 +0000145CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
146 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
147 if (VD->getStorageClass() == VarDecl::PrivateExtern)
148 return LangOptions::Hidden;
149
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000150 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000151 switch (attr->getVisibility()) {
152 default: assert(0 && "Unknown visibility!");
Mike Stump1eb44332009-09-09 15:08:12 +0000153 case VisibilityAttr::DefaultVisibility:
Daniel Dunbar04d40782009-04-14 06:00:08 +0000154 return LangOptions::Default;
155 case VisibilityAttr::HiddenVisibility:
156 return LangOptions::Hidden;
157 case VisibilityAttr::ProtectedVisibility:
158 return LangOptions::Protected;
159 }
160 }
Douglas Gregor7cf84d62010-06-15 17:05:35 +0000161
Douglas Gregoraf896892010-06-21 18:41:26 +0000162 if (getLangOptions().CPlusPlus) {
163 // Entities subject to an explicit instantiation declaration get default
164 // visibility.
165 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
166 if (Function->getTemplateSpecializationKind()
167 == TSK_ExplicitInstantiationDeclaration)
168 return LangOptions::Default;
169 } else if (const ClassTemplateSpecializationDecl *ClassSpec
170 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
171 if (ClassSpec->getSpecializationKind()
172 == TSK_ExplicitInstantiationDeclaration)
173 return LangOptions::Default;
174 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
175 if (Record->getTemplateSpecializationKind()
176 == TSK_ExplicitInstantiationDeclaration)
177 return LangOptions::Default;
178 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
179 if (Var->isStaticDataMember() &&
180 (Var->getTemplateSpecializationKind()
181 == TSK_ExplicitInstantiationDeclaration))
182 return LangOptions::Default;
183 }
184
185 // If -fvisibility-inlines-hidden was provided, then inline C++ member
186 // functions get "hidden" visibility by default.
187 if (getLangOptions().InlineVisibilityHidden)
188 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
189 if (Method->isInlined())
190 return LangOptions::Hidden;
191 }
192
Anders Carlsson39de84d2010-02-07 01:44:36 +0000193 // This decl should have the same visibility as its parent.
194 if (const DeclContext *DC = D->getDeclContext())
195 return getDeclVisibilityMode(cast<Decl>(DC));
196
Daniel Dunbar04d40782009-04-14 06:00:08 +0000197 return getLangOptions().getVisibilityMode();
198}
199
Mike Stump1eb44332009-09-09 15:08:12 +0000200void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Daniel Dunbar04d40782009-04-14 06:00:08 +0000201 const Decl *D) const {
202 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000203 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000204 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000205 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000206 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000207
Daniel Dunbar04d40782009-04-14 06:00:08 +0000208 switch (getDeclVisibilityMode(D)) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000209 default: assert(0 && "Unknown visibility!");
Daniel Dunbar04d40782009-04-14 06:00:08 +0000210 case LangOptions::Default:
211 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
212 case LangOptions::Hidden:
213 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
214 case LangOptions::Protected:
215 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman4f8d1232008-05-22 00:50:06 +0000216 }
217}
218
Anders Carlsson793a9902010-06-22 16:05:32 +0000219llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
220 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
221
222 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
223 if (!Str.empty())
224 return Str;
225
226 if (!getMangleContext().shouldMangleDeclName(ND)) {
227 IdentifierInfo *II = ND->getIdentifier();
228 assert(II && "Attempt to mangle unnamed decl.");
229
230 Str = II->getName();
231 return Str;
232 }
233
234 llvm::SmallString<256> Buffer;
235 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
236 getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
237 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
238 getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
239 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000240 getMangleContext().mangleBlock(GD, BD, Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000241 else
242 getMangleContext().mangleName(ND, Buffer);
243
244 // Allocate space for the mangled name.
245 size_t Length = Buffer.size();
246 char *Name = MangledNamesAllocator.Allocate<char>(Length);
247 std::copy(Buffer.begin(), Buffer.end(), Name);
248
249 Str = llvm::StringRef(Name, Length);
250
251 return Str;
252}
253
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000254void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer,
255 const BlockDecl *BD) {
256 getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer());
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000257}
258
John McCallf746aa62010-03-19 23:29:14 +0000259llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
260 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000261}
262
Chris Lattner6d397602008-03-14 17:18:18 +0000263/// AddGlobalCtor - Add a function to the list that will be called before
264/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000265void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000266 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000267 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000268}
269
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000270/// AddGlobalDtor - Add a function to the list that will be called
271/// when the module is unloaded.
272void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000273 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000274 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
275}
276
277void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
278 // Ctor function type is void()*.
279 llvm::FunctionType* CtorFTy =
Mike Stump1eb44332009-09-09 15:08:12 +0000280 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000281 std::vector<const llvm::Type*>(),
282 false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000283 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000284
285 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump1eb44332009-09-09 15:08:12 +0000286 llvm::StructType* CtorStructTy =
287 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000288 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000289
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000290 // Construct the constructor and destructor arrays.
291 std::vector<llvm::Constant*> Ctors;
292 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
293 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000294 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000295 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000296 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000297 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000298 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000299
300 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000301 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000302 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000303 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000304 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000305 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000306 }
Chris Lattner6d397602008-03-14 17:18:18 +0000307}
308
Nate Begeman532485c2008-04-18 23:43:57 +0000309void CodeGenModule::EmitAnnotations() {
310 if (Annotations.empty())
311 return;
312
313 // Create a new global variable for the ConstantStruct in the Module.
314 llvm::Constant *Array =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000315 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000316 Annotations.size()),
317 Annotations);
Mike Stump1eb44332009-09-09 15:08:12 +0000318 llvm::GlobalValue *gv =
319 new llvm::GlobalVariable(TheModule, Array->getType(), false,
320 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000321 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000322 gv->setSection("llvm.metadata");
323}
324
Chris Lattner86daeee2009-04-14 16:44:36 +0000325static CodeGenModule::GVALinkage
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000326GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
327 const LangOptions &Features) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000328 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000329
330 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000331 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000332 FD->getType()->getLinkage() == UniqueExternalLinkage)
333 L = UniqueExternalLinkage;
334
335 switch (L) {
336 case NoLinkage:
337 case InternalLinkage:
338 case UniqueExternalLinkage:
339 return CodeGenModule::GVA_Internal;
Anders Carlsson548e60e2009-12-10 22:25:34 +0000340
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000341 case ExternalLinkage:
342 switch (FD->getTemplateSpecializationKind()) {
343 case TSK_Undeclared:
344 case TSK_ExplicitSpecialization:
345 External = CodeGenModule::GVA_StrongExternal;
346 break;
347
348 case TSK_ExplicitInstantiationDefinition:
Douglas Gregor8f51a4f2010-03-13 18:23:07 +0000349 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000350
351 case TSK_ExplicitInstantiationDeclaration:
352 case TSK_ImplicitInstantiation:
Anders Carlsson548e60e2009-12-10 22:25:34 +0000353 External = CodeGenModule::GVA_TemplateInstantiation;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000354 break;
355 }
Anders Carlsson548e60e2009-12-10 22:25:34 +0000356 }
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregor7ced9c82009-10-27 21:11:48 +0000358 if (!FD->isInlined())
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000359 return External;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000360
Douglas Gregor1fc09a92009-09-13 07:46:26 +0000361 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
362 // GNU or C99 inline semantics. Determine whether this symbol should be
363 // externally visible.
364 if (FD->isInlineDefinitionExternallyVisible())
365 return External;
366
367 // C99 inline semantics, where the symbol is not externally visible.
368 return CodeGenModule::GVA_C99Inline;
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000369 }
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000370
Douglas Gregor7d9c3c92009-10-27 23:26:40 +0000371 // C++0x [temp.explicit]p9:
372 // [ Note: The intent is that an inline function that is the subject of
373 // an explicit instantiation declaration will still be implicitly
374 // instantiated when used so that the body can be considered for
375 // inlining, but that no out-of-line copy of the inline function would be
376 // generated in the translation unit. -- end note ]
Rafael Espindolaf075b222010-03-23 19:55:22 +0000377 if (FD->getTemplateSpecializationKind()
378 == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor7d9c3c92009-10-27 23:26:40 +0000379 return CodeGenModule::GVA_C99Inline;
Rafael Espindolab8cab182010-04-19 00:44:22 +0000380
Douglas Gregor1fc09a92009-09-13 07:46:26 +0000381 return CodeGenModule::GVA_CXXInline;
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000382}
383
John McCalld46f9852010-02-19 01:32:20 +0000384llvm::GlobalValue::LinkageTypes
385CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000386 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000387
Chris Lattnerf81530652010-06-30 16:58:07 +0000388 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000389 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000390
391 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000392 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000393
394 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000395 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000396
397 // In C99 mode, 'inline' functions are guaranteed to have a strong
398 // definition somewhere else, so we can use available_externally linkage.
399 if (Linkage == GVA_C99Inline)
John McCalld46f9852010-02-19 01:32:20 +0000400 return llvm::Function::AvailableExternallyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000401
402 // In C++, the compiler has to emit a definition in every translation unit
403 // that references the function. We should use linkonce_odr because
404 // a) if all references in this translation unit are optimized away, we
405 // don't need to codegen it. b) if the function persists, it needs to be
406 // merged with other definitions. c) C++ has the ODR, so we know the
407 // definition is dependable.
408 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld46f9852010-02-19 01:32:20 +0000409 return llvm::Function::LinkOnceODRLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000410
411 // An explicit instantiation of a template has weak linkage, since
412 // explicit instantiations can occur in multiple translation units
413 // and must all be equivalent. However, we are not allowed to
414 // throw away these explicit instantiations.
415 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregor8f51a4f2010-03-13 18:23:07 +0000416 return llvm::Function::WeakODRLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000417
418 // Otherwise, we have strong external linkage.
419 assert(Linkage == GVA_StrongExternal);
420 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000421}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000422
John McCalld46f9852010-02-19 01:32:20 +0000423
424/// SetFunctionDefinitionAttributes - Set attributes for a global.
425///
426/// FIXME: This is currently only done for aliases and functions, but not for
427/// variables (these details are set in EmitGlobalVarDefinition for variables).
428void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
429 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000430 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000431}
432
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000433void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000434 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000435 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000436 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000437 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000438 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000439 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000440 AttributeList.size()));
441 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000442}
443
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000444void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
445 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000446 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump1eb44332009-09-09 15:08:12 +0000447 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000448
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000449 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000450 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Mike Stump1feade82009-08-26 22:31:08 +0000452 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000453 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000454
Anders Carlssonfd015352009-11-16 16:56:03 +0000455 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
456 F->addFnAttr(llvm::Attribute::StackProtect);
457 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
458 F->addFnAttr(llvm::Attribute::StackProtectReq);
459
Sean Huntbbd37c62009-11-21 08:43:09 +0000460 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
461 unsigned width = Context.Target.getCharWidth();
462 F->setAlignment(AA->getAlignment() / width);
463 while ((AA = AA->getNext<AlignedAttr>()))
464 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
465 }
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000466 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000467 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
468 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000469}
470
Mike Stump1eb44332009-09-09 15:08:12 +0000471void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000472 llvm::GlobalValue *GV) {
473 setGlobalVisibility(GV, D);
474
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000475 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000476 AddUsedGlobal(GV);
477
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000478 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000479 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000480
481 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000482}
483
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000484void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
485 llvm::Function *F,
486 const CGFunctionInfo &FI) {
487 SetLLVMFunctionAttributes(D, FI, F);
488 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000489
490 F->setLinkage(llvm::Function::InternalLinkage);
491
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000492 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000493}
494
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000495void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000496 llvm::Function *F,
497 bool IsIncompleteFunction) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000498 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
499
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000500 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000501 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000503 // Only a few attributes are set on declarations; these may later be
504 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000506 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000507 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000508 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000509 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000510 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000511 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000512 F->setLinkage(llvm::Function::ExternalWeakLinkage);
513 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000514 F->setLinkage(llvm::Function::ExternalLinkage);
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");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000633
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000634 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000635 llvm::Constant *Fields[4] = {
Owen Anderson3c4972d2009-07-29 18:54:39 +0000636 llvm::ConstantExpr::getBitCast(GV, SBP),
637 llvm::ConstantExpr::getBitCast(annoGV, SBP),
638 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson0032b272009-08-13 21:57:51 +0000639 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000640 };
Owen Anderson47a434f2009-08-05 23:18:46 +0000641 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000642}
643
Eli Friedman61c6c912010-06-19 06:24:06 +0000644static CodeGenModule::GVALinkage
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000645GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
Eli Friedman61c6c912010-06-19 06:24:06 +0000646 // If this is a static data member, compute the kind of template
647 // specialization. Otherwise, this variable is not part of a
648 // template.
649 TemplateSpecializationKind TSK = TSK_Undeclared;
650 if (VD->isStaticDataMember())
651 TSK = VD->getTemplateSpecializationKind();
652
653 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000654 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
Eli Friedman61c6c912010-06-19 06:24:06 +0000655 VD->getType()->getLinkage() == UniqueExternalLinkage)
656 L = UniqueExternalLinkage;
657
658 switch (L) {
659 case NoLinkage:
660 case InternalLinkage:
661 case UniqueExternalLinkage:
662 return CodeGenModule::GVA_Internal;
663
664 case ExternalLinkage:
665 switch (TSK) {
666 case TSK_Undeclared:
667 case TSK_ExplicitSpecialization:
668 return CodeGenModule::GVA_StrongExternal;
669
670 case TSK_ExplicitInstantiationDeclaration:
671 llvm_unreachable("Variable should not be instantiated");
672 // Fall through to treat this like any other instantiation.
673
674 case TSK_ExplicitInstantiationDefinition:
675 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
676
677 case TSK_ImplicitInstantiation:
678 return CodeGenModule::GVA_TemplateInstantiation;
679 }
680 }
681
682 return CodeGenModule::GVA_StrongExternal;
683}
684
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000685bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
686 // Never defer when EmitAllDecls is specified or the decl has
687 // attribute used.
688 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000689 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000690
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000691 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
692 // Constructors and destructors should never be deferred.
693 if (FD->hasAttr<ConstructorAttr>() ||
694 FD->hasAttr<DestructorAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000695 return false;
696
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000697 // The key function for a class must never be deferred.
698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
Eli Friedman61eab882009-12-08 03:56:49 +0000699 const CXXRecordDecl *RD = MD->getParent();
700 if (MD->isOutOfLine() && RD->isDynamicClass()) {
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000701 const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
702 if (KeyFunction &&
703 KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
704 return false;
Eli Friedman61eab882009-12-08 03:56:49 +0000705 }
706 }
707
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000708 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000710 // static, static inline, always_inline, and extern inline functions can
Chris Lattner86daeee2009-04-14 16:44:36 +0000711 // always be deferred. Normal inline functions can be deferred in C99/C++.
Douglas Gregor8f51a4f2010-03-13 18:23:07 +0000712 // Implicit template instantiations can also be deferred in C++.
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000713 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
714 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
715 return true;
716 return false;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000719 const VarDecl *VD = cast<VarDecl>(Global);
720 assert(VD->isFileVarDecl() && "Invalid decl");
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000721
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000722 // We never want to defer structs that have non-trivial constructors or
723 // destructors.
724
Anders Carlsson74d644a2009-10-08 17:28:59 +0000725 // FIXME: Handle references.
726 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
727 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
728 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000729 return false;
Anders Carlsson74d644a2009-10-08 17:28:59 +0000730 }
731 }
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000732
733 GVALinkage L = GetLinkageForVariable(getContext(), VD);
734 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
735 if (!(VD->getInit() && VD->getInit()->HasSideEffects(Context)))
736 return true;
Fariborz Jahanian393c2472009-11-05 18:03:03 +0000737 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000738
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000739 return false;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000740}
741
Rafael Espindola6a836702010-03-04 18:17:24 +0000742llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
743 const AliasAttr *AA = VD->getAttr<AliasAttr>();
744 assert(AA && "No alias?");
745
746 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
747
Rafael Espindola6a836702010-03-04 18:17:24 +0000748 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000749 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000750
751 llvm::Constant *Aliasee;
752 if (isa<llvm::FunctionType>(DeclTy))
John McCallf746aa62010-03-19 23:29:14 +0000753 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola6a836702010-03-04 18:17:24 +0000754 else
John McCallf746aa62010-03-19 23:29:14 +0000755 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000756 llvm::PointerType::getUnqual(DeclTy), 0);
757 if (!Entry) {
758 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
759 F->setLinkage(llvm::Function::ExternalWeakLinkage);
760 WeakRefReferences.insert(F);
761 }
762
763 return Aliasee;
764}
765
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000766void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000767 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Rafael Espindola6a836702010-03-04 18:17:24 +0000769 // Weak references don't produce any output by themselves.
770 if (Global->hasAttr<WeakRefAttr>())
771 return;
772
Chris Lattnerbd532712009-03-22 21:47:11 +0000773 // If this is an alias definition (which otherwise looks like a declaration)
774 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000775 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000776 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000777
Chris Lattner67b00522009-03-21 09:44:56 +0000778 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000779 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000780 if (FD->getIdentifier()) {
781 llvm::StringRef Name = FD->getName();
782 if (Name == "_Block_object_assign") {
783 BlockObjectAssignDecl = FD;
784 } else if (Name == "_Block_object_dispose") {
785 BlockObjectDisposeDecl = FD;
786 }
787 }
788
Daniel Dunbar73241df2009-02-13 21:18:01 +0000789 // Forward declarations are emitted lazily on first use.
790 if (!FD->isThisDeclarationADefinition())
791 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000792 } else {
793 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000794 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
795
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000796 if (VD->getIdentifier()) {
797 llvm::StringRef Name = VD->getName();
798 if (Name == "_NSConcreteGlobalBlock") {
799 NSConcreteGlobalBlockDecl = VD;
800 } else if (Name == "_NSConcreteStackBlock") {
801 NSConcreteStackBlockDecl = VD;
802 }
803 }
804
805
Douglas Gregora9a55c02010-02-06 05:15:45 +0000806 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000807 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000808 }
809
Chris Lattner67b00522009-03-21 09:44:56 +0000810 // Defer code generation when possible if this is a static definition, inline
811 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000812 if (!MayDeferGeneration(Global)) {
813 // Emit the definition if it can't be deferred.
814 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000815 return;
816 }
John McCallbf40cb52010-07-15 23:40:35 +0000817
818 // If we're deferring emission of a C++ variable with an
819 // initializer, remember the order in which it appeared in the file.
820 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
821 cast<VarDecl>(Global)->hasInit()) {
822 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
823 CXXGlobalInits.push_back(0);
824 }
Chris Lattner4357a822010-04-13 17:39:09 +0000825
826 // If the value has already been used, add it directly to the
827 // DeferredDeclsToEmit list.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000828 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000829 if (GetGlobalValue(MangledName))
830 DeferredDeclsToEmit.push_back(GD);
831 else {
832 // Otherwise, remember that we saw a deferred decl with this name. The
833 // first use of the mangled name will cause it to move into
834 // DeferredDeclsToEmit.
835 DeferredDecls[MangledName] = GD;
836 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000837}
838
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000839void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000840 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Dan Gohmancb421fa2010-04-19 16:39:44 +0000842 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000843 Context.getSourceManager(),
844 "Generating code for declaration");
845
Douglas Gregor44eac332010-07-13 06:02:28 +0000846 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
847 // At -O0, don't generate IR for functions with available_externally
848 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000849 if (CodeGenOpts.OptimizationLevel == 0 &&
850 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000851 getFunctionLinkage(Function)
852 == llvm::Function::AvailableExternallyLinkage)
853 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000854
Douglas Gregor44eac332010-07-13 06:02:28 +0000855 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
856 if (Method->isVirtual())
857 getVTables().EmitThunks(GD);
858
859 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
860 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner4357a822010-04-13 17:39:09 +0000861
Douglas Gregor44eac332010-07-13 06:02:28 +0000862 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
863 return EmitCXXDestructor(DD, GD.getDtorType());
864 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000865
Chris Lattnerb5e81562010-04-13 17:57:11 +0000866 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000867 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000868
869 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
870 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000871
872 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000873}
874
Chris Lattner74391b42009-03-22 21:03:39 +0000875/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
876/// module, create and return an llvm Function with the specified type. If there
877/// is something in the module with the specified name, return it potentially
878/// bitcasted to the right type.
879///
880/// If D is non-null, it specifies a decl that correspond to this. This is used
881/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000882llvm::Constant *
883CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
884 const llvm::Type *Ty,
885 GlobalDecl D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000886 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000887 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000888 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000889 if (WeakRefReferences.count(Entry)) {
890 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
891 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000892 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000893
894 WeakRefReferences.erase(Entry);
895 }
896
Chris Lattner0558e792009-03-21 09:25:43 +0000897 if (Entry->getType()->getElementType() == Ty)
898 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner0558e792009-03-21 09:25:43 +0000900 // Make sure the result is of the correct type.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000901 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000902 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000903 }
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Eli Friedman654ad402009-11-09 05:07:37 +0000905 // This function doesn't have a complete type (for example, the return
906 // type is an incomplete struct). Use a fake type instead, and make
907 // sure not to try to set attributes.
908 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000909
910 const llvm::FunctionType *FTy;
911 if (isa<llvm::FunctionType>(Ty)) {
912 FTy = cast<llvm::FunctionType>(Ty);
913 } else {
914 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
915 std::vector<const llvm::Type*>(), false);
Eli Friedman654ad402009-11-09 05:07:37 +0000916 IsIncompleteFunction = true;
917 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000918
John McCall784f2112010-04-28 00:00:30 +0000919 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000920 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000921 MangledName, &getModule());
922 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000923 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000924 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedman654ad402009-11-09 05:07:37 +0000925
Chris Lattner67b00522009-03-21 09:44:56 +0000926 // This is the first use or definition of a mangled name. If there is a
927 // deferred decl with this name, remember that we need to emit it at the end
928 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000929 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000930 if (DDI != DeferredDecls.end()) {
931 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
932 // list, and remove it from DeferredDecls (since we don't need it anymore).
933 DeferredDeclsToEmit.push_back(DDI->second);
934 DeferredDecls.erase(DDI);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000935 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattner0c337ed2009-05-12 21:02:27 +0000936 // If this the first reference to a C++ inline function in a class, queue up
937 // the deferred function body for emission. These are not seen as
938 // top-level declarations.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000939 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
940 DeferredDeclsToEmit.push_back(D);
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000941 // A called constructor which has no definition or declaration need be
942 // synthesized.
943 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000944 if (CD->isImplicit()) {
Benjamin Kramerd3a344c2010-03-06 09:07:19 +0000945 assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
Eli Friedman15233e52009-11-26 07:40:08 +0000946 DeferredDeclsToEmit.push_back(D);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000947 }
Eli Friedman15233e52009-11-26 07:40:08 +0000948 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000949 if (DD->isImplicit()) {
Benjamin Kramerd3a344c2010-03-06 09:07:19 +0000950 assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
Eli Friedman15233e52009-11-26 07:40:08 +0000951 DeferredDeclsToEmit.push_back(D);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000952 }
Eli Friedman15233e52009-11-26 07:40:08 +0000953 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000954 if (MD->isCopyAssignment() && MD->isImplicit()) {
Benjamin Kramerd3a344c2010-03-06 09:07:19 +0000955 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000956 DeferredDeclsToEmit.push_back(D);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000957 }
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000958 }
Chris Lattner67b00522009-03-21 09:44:56 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCall784f2112010-04-28 00:00:30 +0000961 // Make sure the result is of the requested type.
962 if (!IsIncompleteFunction) {
963 assert(F->getType()->getElementType() == Ty);
964 return F;
965 }
966
967 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
968 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000969}
970
Chris Lattner74391b42009-03-22 21:03:39 +0000971/// GetAddrOfFunction - Return the address of the given function. If Ty is
972/// non-null, then this function will use the specified type if it has to
973/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000974llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner74391b42009-03-22 21:03:39 +0000975 const llvm::Type *Ty) {
976 // If there was no specific requested type, just convert it now.
977 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000978 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000979
Anders Carlsson9a20d552010-06-22 16:16:50 +0000980 llvm::StringRef MangledName = getMangledName(GD);
John McCallf746aa62010-03-19 23:29:14 +0000981 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattner74391b42009-03-22 21:03:39 +0000982}
Eli Friedman77ba7082008-05-30 19:50:47 +0000983
Chris Lattner74391b42009-03-22 21:03:39 +0000984/// CreateRuntimeFunction - Create a new runtime function with the specified
985/// type and name.
986llvm::Constant *
987CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCallf746aa62010-03-19 23:29:14 +0000988 llvm::StringRef Name) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000989 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattner74391b42009-03-22 21:03:39 +0000990}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000991
Eli Friedman20e098b2009-12-11 21:23:03 +0000992static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall88786862010-02-08 21:46:50 +0000993 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +0000994 return false;
995 if (Context.getLangOptions().CPlusPlus &&
996 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
997 // FIXME: We should do something fancier here!
998 return false;
999 }
1000 return true;
1001}
1002
Chris Lattner74391b42009-03-22 21:03:39 +00001003/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1004/// create and return an llvm GlobalVariable with the specified type. If there
1005/// is something in the module with the specified name, return it potentially
1006/// bitcasted to the right type.
1007///
1008/// If D is non-null, it specifies a decl that correspond to this. This is used
1009/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001010llvm::Constant *
1011CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
1012 const llvm::PointerType *Ty,
1013 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001014 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001015 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001016 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001017 if (WeakRefReferences.count(Entry)) {
1018 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001019 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001020
1021 WeakRefReferences.erase(Entry);
1022 }
1023
Chris Lattner74391b42009-03-22 21:03:39 +00001024 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001025 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner99b53612009-03-21 08:03:33 +00001027 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001028 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner67b00522009-03-21 09:44:56 +00001031 // This is the first use or definition of a mangled name. If there is a
1032 // deferred decl with this name, remember that we need to emit it at the end
1033 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001034 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001035 if (DDI != DeferredDecls.end()) {
1036 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1037 // list, and remove it from DeferredDecls (since we don't need it anymore).
1038 DeferredDeclsToEmit.push_back(DDI->second);
1039 DeferredDecls.erase(DDI);
1040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
1042 llvm::GlobalVariable *GV =
1043 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001044 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001045 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +00001046 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +00001047
1048 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001049 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001050 // FIXME: This code is overly simple and should be merged with other global
1051 // handling.
Eli Friedman20e098b2009-12-11 21:23:03 +00001052 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner99b53612009-03-21 08:03:33 +00001053
Chris Lattner74391b42009-03-22 21:03:39 +00001054 // FIXME: Merge with other attribute handling code.
1055 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbar04d40782009-04-14 06:00:08 +00001056 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +00001057
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (D->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001059 D->hasAttr<WeakImportAttr>())
Chris Lattner74391b42009-03-22 21:03:39 +00001060 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman56ebe502009-04-19 21:05:03 +00001061
1062 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001063 }
Mike Stump1eb44332009-09-09 15:08:12 +00001064
John McCallf746aa62010-03-19 23:29:14 +00001065 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001066}
1067
Chris Lattner74391b42009-03-22 21:03:39 +00001068
1069/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1070/// given global variable. If Ty is non-null and if the global doesn't exist,
1071/// then it will be greated with the specified type instead of whatever the
1072/// normal requested type would be.
1073llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1074 const llvm::Type *Ty) {
1075 assert(D->hasGlobalStorage() && "Not a global variable");
1076 QualType ASTTy = D->getType();
1077 if (Ty == 0)
1078 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001079
1080 const llvm::PointerType *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001081 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCallf746aa62010-03-19 23:29:14 +00001082
Anders Carlsson9a20d552010-06-22 16:16:50 +00001083 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001084 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001085}
1086
1087/// CreateRuntimeVariable - Create a new runtime global variable with the
1088/// specified type and name.
1089llvm::Constant *
1090CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCallf746aa62010-03-19 23:29:14 +00001091 llvm::StringRef Name) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001092 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
Chris Lattner74391b42009-03-22 21:03:39 +00001093}
1094
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001095void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1096 assert(!D->getInit() && "Cannot emit definite definitions here!");
1097
Douglas Gregor7520bd12009-04-21 19:28:58 +00001098 if (MayDeferGeneration(D)) {
1099 // If we have not seen a reference to this variable yet, place it
1100 // into the deferred declarations table to be emitted if needed
1101 // later.
Anders Carlsson9a20d552010-06-22 16:16:50 +00001102 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001103 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001104 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001105 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001106 }
1107 }
1108
1109 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001110 EmitGlobalVarDefinition(D);
1111}
1112
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001113void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1114 if (DefinitionRequired)
1115 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1116}
1117
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001118llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001119CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregordffb8012010-01-06 22:00:56 +00001120 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1121 return llvm::GlobalVariable::InternalLinkage;
1122
1123 if (const CXXMethodDecl *KeyFunction
1124 = RD->getASTContext().getKeyFunction(RD)) {
1125 // If this class has a key function, use that to determine the linkage of
1126 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001127 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001128 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001129 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001130
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001131 switch (KeyFunction->getTemplateSpecializationKind()) {
1132 case TSK_Undeclared:
1133 case TSK_ExplicitSpecialization:
1134 if (KeyFunction->isInlined())
1135 return llvm::GlobalVariable::WeakODRLinkage;
1136
1137 return llvm::GlobalVariable::ExternalLinkage;
1138
1139 case TSK_ImplicitInstantiation:
1140 case TSK_ExplicitInstantiationDefinition:
1141 return llvm::GlobalVariable::WeakODRLinkage;
1142
1143 case TSK_ExplicitInstantiationDeclaration:
1144 // FIXME: Use available_externally linkage. However, this currently
1145 // breaks LLVM's build due to undefined symbols.
1146 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1147 return llvm::GlobalVariable::WeakODRLinkage;
1148 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001149 }
1150
1151 switch (RD->getTemplateSpecializationKind()) {
1152 case TSK_Undeclared:
1153 case TSK_ExplicitSpecialization:
1154 case TSK_ImplicitInstantiation:
1155 case TSK_ExplicitInstantiationDefinition:
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001156 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregordffb8012010-01-06 22:00:56 +00001157
1158 case TSK_ExplicitInstantiationDeclaration:
1159 // FIXME: Use available_externally linkage. However, this currently
1160 // breaks LLVM's build due to undefined symbols.
1161 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1162 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001163 }
1164
1165 // Silence GCC warning.
1166 return llvm::GlobalVariable::WeakODRLinkage;
1167}
1168
Ken Dyck687cc4a2010-01-26 13:48:07 +00001169CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1170 return CharUnits::fromQuantity(
1171 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1172}
1173
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001174void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001175 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001176 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001177 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Sebastian Redl31310a22010-02-01 20:16:42 +00001179 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001180
1181 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001182 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001183 // implicitly initialized with { 0 }.
1184 //
1185 // Note that tentative definitions are only emitted at the end of
1186 // a translation unit, so they should never have incomplete
1187 // type. In addition, EmitTentativeDefinition makes sure that we
1188 // never attempt to emit a tentative definition if a real one
1189 // exists. A use may still exists, however, so we still may need
1190 // to do a RAUW.
1191 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001192 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001193 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001194 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001195 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001196 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001197 if (D->getType()->isReferenceType())
1198 T = D->getType();
1199
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001200 if (getLangOptions().CPlusPlus) {
Eli Friedman6c6bda32010-01-08 00:50:11 +00001201 EmitCXXGlobalVarDeclInitFunc(D);
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001202 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001203 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001204 } else {
1205 ErrorUnsupported(D, "static initializer");
1206 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1207 }
John McCallbf40cb52010-07-15 23:40:35 +00001208 } else {
1209 // We don't need an initializer, so remove the entry for the delayed
1210 // initializer position (just in case this entry was delayed).
1211 if (getLangOptions().CPlusPlus)
1212 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001213 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001214 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001215
Chris Lattner2d584062009-03-21 08:13:05 +00001216 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001217 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Chris Lattner570585c2009-03-21 09:16:30 +00001219 // Strip off a bitcast if we got one back.
1220 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001221 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1222 // all zero index gep.
1223 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001224 Entry = CE->getOperand(0);
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Chris Lattner570585c2009-03-21 09:16:30 +00001227 // Entry is now either a Function or GlobalVariable.
1228 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Chris Lattner570585c2009-03-21 09:16:30 +00001230 // We have a definition after a declaration with the wrong type.
1231 // We must make a new GlobalVariable* and update everything that used OldGV
1232 // (a declaration or tentative definition) with the new GlobalVariable*
1233 // (which will be a definition).
1234 //
1235 // This happens if there is a prototype for a global (e.g.
1236 // "extern int x[];") and then a definition of a different type (e.g.
1237 // "int x[10];"). This also happens when an initializer has a different type
1238 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001239 if (GV == 0 ||
1240 GV->getType()->getElementType() != InitType ||
1241 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCallf746aa62010-03-19 23:29:14 +00001243 // Move the old entry aside so that we'll create a new one.
1244 Entry->setName(llvm::StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001245
Chris Lattner570585c2009-03-21 09:16:30 +00001246 // Make a new global with the correct type, this is now guaranteed to work.
1247 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001248
Eli Friedman77ba7082008-05-30 19:50:47 +00001249 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001250 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001251 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001252 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001253
1254 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001255 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001256 }
Devang Patel8e53e722007-10-26 16:31:40 +00001257
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001258 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001259 SourceManager &SM = Context.getSourceManager();
1260 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00001261 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001262 }
1263
Chris Lattner88a69ad2007-07-13 05:13:43 +00001264 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001265
1266 // If it is safe to mark the global 'constant', do so now.
1267 GV->setConstant(false);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001268 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001269 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Ken Dyck8b752f12010-01-27 17:10:57 +00001271 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Eli Friedman08d78022008-05-29 11:10:27 +00001272
Chris Lattner88a69ad2007-07-13 05:13:43 +00001273 // Set the llvm linkage type as appropriate.
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +00001274 GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
Douglas Gregora0f00a72009-10-14 21:36:34 +00001275 if (Linkage == GVA_Internal)
Chris Lattner8fabd782008-05-04 01:44:26 +00001276 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001277 else if (D->hasAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +00001278 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001279 else if (D->hasAttr<DLLExportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +00001280 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001281 else if (D->hasAttr<WeakAttr>()) {
1282 if (GV->isConstant())
1283 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1284 else
1285 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Douglas Gregor8f51a4f2010-03-13 18:23:07 +00001286 } else if (Linkage == GVA_TemplateInstantiation ||
1287 Linkage == GVA_ExplicitTemplateInstantiation)
1288 // FIXME: It seems like we can provide more specific linkage here
1289 // (LinkOnceODR, WeakODR).
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001290 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar1bc5c032009-11-30 08:40:34 +00001291 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
Chris Lattner309457d2009-08-05 04:56:58 +00001292 !D->hasExternalStorage() && !D->getInit() &&
Chris Lattnere78b86f2009-08-05 05:20:29 +00001293 !D->getAttr<SectionAttr>()) {
Daniel Dunbar04d40782009-04-14 06:00:08 +00001294 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001295 // common vars aren't constant even if declared const.
1296 GV->setConstant(false);
1297 } else
Daniel Dunbar04d40782009-04-14 06:00:08 +00001298 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001299
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001300 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001301
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001302 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +00001303 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001304 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001305 DI->EmitGlobalVariable(GV, D);
1306 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001307}
Reid Spencer5f016e22007-07-11 17:01:13 +00001308
Chris Lattnerbdb01322009-05-05 06:16:31 +00001309/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1310/// implement a function with no prototype, e.g. "int foo() {}". If there are
1311/// existing call uses of the old function in the module, this adjusts them to
1312/// call the new function directly.
1313///
1314/// This is not just a cleanup: the always_inline pass requires direct calls to
1315/// functions to be able to inline them. If there is a bitcast in the way, it
1316/// won't inline them. Instcombine normally deletes these calls, but it isn't
1317/// run at -O0.
1318static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1319 llvm::Function *NewFn) {
1320 // If we're redefining a global as a function, don't transform it.
1321 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1322 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Chris Lattnerbdb01322009-05-05 06:16:31 +00001324 const llvm::Type *NewRetTy = NewFn->getReturnType();
1325 llvm::SmallVector<llvm::Value*, 4> ArgList;
1326
1327 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001328 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001329 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001330 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1331 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif35db3b92010-04-10 03:45:50 +00001332 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001333 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Chris Lattnerbdb01322009-05-05 06:16:31 +00001335 // If the return types don't match exactly, and if the call isn't dead, then
1336 // we can't transform this call.
1337 if (CI->getType() != NewRetTy && !CI->use_empty())
1338 continue;
1339
1340 // If the function was passed too few arguments, don't transform. If extra
1341 // arguments were passed, we silently drop them. If any of the types
1342 // mismatch, we don't transform.
1343 unsigned ArgNo = 0;
1344 bool DontTransform = false;
1345 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1346 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001347 if (CS.arg_size() == ArgNo ||
1348 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001349 DontTransform = true;
1350 break;
1351 }
1352 }
1353 if (DontTransform)
1354 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Chris Lattnerbdb01322009-05-05 06:16:31 +00001356 // Okay, we can transform this. Create the new call instruction and copy
1357 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001358 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001359 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1360 ArgList.end(), "", CI);
1361 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001362 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001363 NewCall->takeName(CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001364 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001365 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001366
1367 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001368 if (!CI->use_empty())
1369 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001370
Chris Lattnerc6034632010-04-01 06:31:43 +00001371 // Copy debug location attached to CI.
1372 if (!CI->getDebugLoc().isUnknown())
1373 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001374 CI->eraseFromParent();
1375 }
1376}
1377
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001378
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001379void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001380 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallc0bf4622010-02-23 00:48:20 +00001381 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Fariborz Jahanian4819ac42010-03-04 01:02:03 +00001382 getMangleContext().mangleInitDiscriminator();
Chris Lattner9fa959d2009-05-12 20:58:15 +00001383 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001384 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Chris Lattner0558e792009-03-21 09:25:43 +00001386 // Strip off a bitcast if we got one back.
1387 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1388 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1389 Entry = CE->getOperand(0);
1390 }
Mike Stump1eb44332009-09-09 15:08:12 +00001391
1392
Chris Lattner0558e792009-03-21 09:25:43 +00001393 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001394 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Daniel Dunbar42745812009-03-09 23:53:08 +00001396 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001397 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001398 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001399
Chris Lattner62b33ea2009-03-21 08:38:50 +00001400 // F is the Function* for the one with the wrong type, we must make a new
1401 // Function* and update everything that used F (a declaration) with the new
1402 // Function* (which will be a definition).
1403 //
1404 // This happens if there is a prototype for a function
1405 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001406 // (e.g. "int f(int x)"). Move the old function aside so that it
1407 // doesn't interfere with GetAddrOfFunction.
1408 OldFn->setName(llvm::StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001409 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Chris Lattnerbdb01322009-05-05 06:16:31 +00001411 // If this is an implementation of a function without a prototype, try to
1412 // replace any existing uses of the function (which may be calls) with uses
1413 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001414 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001415 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001416 OldFn->removeDeadConstantUsers();
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Chris Lattner62b33ea2009-03-21 08:38:50 +00001419 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001420 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001421 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001422 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001423 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Chris Lattner62b33ea2009-03-21 08:38:50 +00001426 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001427 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Chris Lattner0558e792009-03-21 09:25:43 +00001429 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Chris Lattner0558e792009-03-21 09:25:43 +00001432 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001433 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001434
Daniel Dunbar219df662008-09-08 23:44:31 +00001435 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001436
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001437 SetFunctionDefinitionAttributes(D, Fn);
1438 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001440 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001441 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001442 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001443 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001444}
1445
John McCallf746aa62010-03-19 23:29:14 +00001446void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1447 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001448 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001449 assert(AA && "Not an alias?");
1450
Anders Carlsson9a20d552010-06-22 16:16:50 +00001451 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
John McCallf746aa62010-03-19 23:29:14 +00001453 // If there is a definition in the module, then it wins over the alias.
1454 // This is dubious, but allow it to be safe. Just ignore the alias.
1455 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1456 if (Entry && !Entry->isDeclaration())
1457 return;
1458
1459 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001460
1461 // Create a reference to the named value. This ensures that it is emitted
1462 // if a deferred decl.
1463 llvm::Constant *Aliasee;
1464 if (isa<llvm::FunctionType>(DeclTy))
John McCallf746aa62010-03-19 23:29:14 +00001465 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattnerbd532712009-03-22 21:47:11 +00001466 else
John McCallf746aa62010-03-19 23:29:14 +00001467 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001468 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001469
1470 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001471 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001472 new llvm::GlobalAlias(Aliasee->getType(),
1473 llvm::Function::ExternalLinkage,
1474 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattnerbd532712009-03-22 21:47:11 +00001476 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001477 assert(Entry->isDeclaration());
1478
Chris Lattnerbd532712009-03-22 21:47:11 +00001479 // If there is a declaration in the module, then we had an extern followed
1480 // by the alias, as in:
1481 // extern int test6();
1482 // ...
1483 // int test6() __attribute__((alias("test7")));
1484 //
1485 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001486 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Owen Anderson3c4972d2009-07-29 18:54:39 +00001488 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001489 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001490 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001491 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001492 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001495 // Set attributes which are particular to an alias; this is a
1496 // specialization of the attributes which may be set on a global
1497 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001498 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1500 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001501 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001502 GA->setLinkage(llvm::Function::DLLExportLinkage);
1503 } else {
1504 GA->setLinkage(llvm::Function::DLLExportLinkage);
1505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001507 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001508 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001509 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1510 }
1511
1512 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001513}
1514
Chris Lattnerb808c952009-03-22 21:56:56 +00001515/// getBuiltinLibFunction - Given a builtin id for a function like
1516/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbar34771b52009-09-14 04:33:21 +00001517llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1518 unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001519 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001520 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +00001521 "isn't a lib fn");
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Douglas Gregor3e41d602009-02-13 23:20:09 +00001523 // Get the name, skip over the __builtin_ prefix (if necessary).
1524 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1525 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1526 Name += 10;
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Mike Stump1eb44332009-09-09 15:08:12 +00001528 const llvm::FunctionType *Ty =
Eli Friedman386ca782009-12-09 03:05:59 +00001529 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001530
Daniel Dunbar34771b52009-09-14 04:33:21 +00001531 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001532}
1533
Chris Lattner7acda7c2007-12-18 00:25:38 +00001534llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1535 unsigned NumTys) {
1536 return llvm::Intrinsic::getDeclaration(&getModule(),
1537 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1538}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001539
Mon P Wang3ecd7852010-04-04 03:10:52 +00001540
1541llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1542 const llvm::Type *SrcType,
1543 const llvm::Type *SizeType) {
1544 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1545 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
Reid Spencer5f016e22007-07-11 17:01:13 +00001546}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001547
Mon P Wang3ecd7852010-04-04 03:10:52 +00001548llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1549 const llvm::Type *SrcType,
1550 const llvm::Type *SizeType) {
1551 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1552 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
Eli Friedman0c995092008-05-26 12:59:39 +00001553}
1554
Mon P Wang3ecd7852010-04-04 03:10:52 +00001555llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1556 const llvm::Type *SizeType) {
1557 const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1558 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001559}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001560
Daniel Dunbar1d552912009-07-23 22:52:48 +00001561static llvm::StringMapEntry<llvm::Constant*> &
1562GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1563 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001564 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001565 bool &IsUTF16,
1566 unsigned &StringLength) {
Daniel Dunbardf4eee92009-09-22 03:27:52 +00001567 unsigned NumBytes = Literal->getByteLength();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001568
Daniel Dunbarf015b032009-09-22 10:03:52 +00001569 // Check for simple case.
1570 if (!Literal->containsNonAsciiOrNull()) {
1571 StringLength = NumBytes;
1572 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1573 StringLength));
1574 }
1575
Daniel Dunbar1d552912009-07-23 22:52:48 +00001576 // Otherwise, convert the UTF8 literals into a byte string.
1577 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1578 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1579 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001580
1581 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001582 &ToPtr, ToPtr + NumBytes,
1583 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Daniel Dunbar1d552912009-07-23 22:52:48 +00001585 // Check for conversion failure.
1586 if (Result != conversionOK) {
1587 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1588 // this duplicate code.
1589 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
Daniel Dunbarf015b032009-09-22 10:03:52 +00001590 StringLength = NumBytes;
1591 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1592 StringLength));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001593 }
1594
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001595 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001596 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001597
1598 // Render the UTF-16 string into a byte array and convert to the target byte
1599 // order.
1600 //
1601 // FIXME: This isn't something we should need to do here.
1602 llvm::SmallString<128> AsBytes;
1603 AsBytes.reserve(StringLength * 2);
1604 for (unsigned i = 0; i != StringLength; ++i) {
1605 unsigned short Val = ToBuf[i];
1606 if (TargetIsLSB) {
1607 AsBytes.push_back(Val & 0xFF);
1608 AsBytes.push_back(Val >> 8);
1609 } else {
1610 AsBytes.push_back(Val >> 8);
1611 AsBytes.push_back(Val & 0xFF);
1612 }
1613 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001614 // Append one extra null character, the second is automatically added by our
1615 // caller.
1616 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001617
Daniel Dunbar1d552912009-07-23 22:52:48 +00001618 IsUTF16 = true;
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001619 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001620}
1621
1622llvm::Constant *
1623CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1624 unsigned StringLength = 0;
1625 bool isUTF16 = false;
1626 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001627 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001628 getTargetData().isLittleEndian(),
1629 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Daniel Dunbar1d552912009-07-23 22:52:48 +00001631 if (llvm::Constant *C = Entry.getValue())
1632 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Owen Anderson0032b272009-08-13 21:57:51 +00001634 llvm::Constant *Zero =
1635 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001636 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001638 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001639 if (!CFConstantStringClassRef) {
1640 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001641 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001642 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001643 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001644 // Decay array -> ptr
1645 CFConstantStringClassRef =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001646 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Anders Carlssone3daa762008-11-15 18:54:24 +00001649 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001650
Mike Stump1eb44332009-09-09 15:08:12 +00001651 const llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001652 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1653
Anders Carlsson5add6832009-08-16 05:55:31 +00001654 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001655
Anders Carlssonc9e20912007-08-21 00:21:21 +00001656 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001657 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlssonc9e20912007-08-21 00:21:21 +00001659 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001660 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001661 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001662 llvm::ConstantInt::get(Ty, 0x07C8);
1663
Anders Carlssonc9e20912007-08-21 00:21:21 +00001664 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001665 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001666
Chris Lattner95b851e2009-07-16 05:03:48 +00001667 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001668 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001669 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001670 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001671 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001672 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1673 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001674 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001675 } else {
1676 Linkage = llvm::GlobalValue::PrivateLinkage;
1677 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001678 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001679
Mike Stump1eb44332009-09-09 15:08:12 +00001680 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001681 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1682 ".str");
Daniel Dunbara9668e02009-04-03 00:57:44 +00001683 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001684 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1685 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001686 }
Anders Carlsson5add6832009-08-16 05:55:31 +00001687 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1688
Anders Carlssonc9e20912007-08-21 00:21:21 +00001689 // String length.
1690 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001691 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Anders Carlssonc9e20912007-08-21 00:21:21 +00001693 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001694 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001695 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1696 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001697 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001698 if (const char *Sect = getContext().Target.getCFStringSection())
1699 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001700 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Anders Carlsson0c678292007-11-01 00:41:52 +00001702 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001703}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001704
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001705llvm::Constant *
1706CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001707 unsigned StringLength = 0;
1708 bool isUTF16 = false;
1709 llvm::StringMapEntry<llvm::Constant*> &Entry =
1710 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1711 getTargetData().isLittleEndian(),
1712 isUTF16, StringLength);
1713
1714 if (llvm::Constant *C = Entry.getValue())
1715 return C;
1716
1717 llvm::Constant *Zero =
1718 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1719 llvm::Constant *Zeros[] = { Zero, Zero };
1720
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001721 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001722 if (!NSConstantStringClassRef) {
1723 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1724 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001725 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1726 Features.ObjCNonFragileABI ?
1727 "OBJC_CLASS_$_NSConstantString" :
1728 "_NSConstantStringClassReference");
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001729 // Decay array -> ptr
1730 NSConstantStringClassRef =
1731 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1732 }
1733
1734 QualType NSTy = getContext().getNSConstantStringType();
1735
1736 const llvm::StructType *STy =
1737 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1738
1739 std::vector<llvm::Constant*> Fields(3);
1740
1741 // Class pointer.
1742 Fields[0] = NSConstantStringClassRef;
1743
1744 // String pointer.
1745 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1746
1747 llvm::GlobalValue::LinkageTypes Linkage;
1748 bool isConstant;
1749 if (isUTF16) {
1750 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1751 Linkage = llvm::GlobalValue::InternalLinkage;
1752 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1753 // does make plain ascii ones writable.
1754 isConstant = true;
1755 } else {
1756 Linkage = llvm::GlobalValue::PrivateLinkage;
1757 isConstant = !Features.WritableStrings;
1758 }
1759
1760 llvm::GlobalVariable *GV =
1761 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1762 ".str");
1763 if (isUTF16) {
1764 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1765 GV->setAlignment(Align.getQuantity());
1766 }
1767 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1768
1769 // String length.
1770 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1771 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1772
1773 // The struct.
1774 C = llvm::ConstantStruct::get(STy, Fields);
1775 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1776 llvm::GlobalVariable::PrivateLinkage, C,
1777 "_unnamed_nsstring_");
1778 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001779 if (const char *Sect =
1780 Features.ObjCNonFragileABI
1781 ? getContext().Target.getNSStringNonFragileABISection()
1782 : getContext().Target.getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001783 GV->setSection(Sect);
1784 Entry.setValue(GV);
1785
1786 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001787}
1788
Daniel Dunbar61432932008-08-13 23:20:05 +00001789/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001790/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001791std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001792 const char *StrData = E->getStrData();
1793 unsigned Len = E->getByteLength();
1794
1795 const ConstantArrayType *CAT =
1796 getContext().getAsConstantArrayType(E->getType());
1797 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001799 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001800 std::string Str(StrData, StrData+Len);
1801 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001803 if (E->isWide())
1804 RealLen *= getContext().Target.getWCharWidth()/8;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Daniel Dunbar1e049762008-08-10 20:25:57 +00001806 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Daniel Dunbar1e049762008-08-10 20:25:57 +00001808 return Str;
1809}
1810
Daniel Dunbar61432932008-08-13 23:20:05 +00001811/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1812/// constant array for the given string literal.
1813llvm::Constant *
1814CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1815 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001816 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1817 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1818 if (S->isWide()) {
1819 llvm::Type *DestTy =
1820 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1821 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1822 }
1823 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00001824}
1825
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001826/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1827/// array for the given ObjCEncodeExpr node.
1828llvm::Constant *
1829CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1830 std::string Str;
1831 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001832
1833 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001834}
1835
1836
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001837/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001838static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001839 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001840 CodeGenModule &CGM,
1841 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001842 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00001843 llvm::Constant *C =
1844 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001846 // Create a global variable for this string
Mike Stump1eb44332009-09-09 15:08:12 +00001847 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
Chris Lattner95b851e2009-07-16 05:03:48 +00001848 llvm::GlobalValue::PrivateLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00001849 C, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001850}
1851
Daniel Dunbar61432932008-08-13 23:20:05 +00001852/// GetAddrOfConstantString - Returns a pointer to a character array
1853/// containing the literal. This contents are exactly that of the
1854/// given string, i.e. it will not be null terminated automatically;
1855/// see GetAddrOfConstantCString. Note that whether the result is
1856/// actually a pointer to an LLVM constant depends on
1857/// Feature.WriteableStrings.
1858///
1859/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001860llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1861 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001862 bool IsConstant = !Features.WritableStrings;
1863
1864 // Get the default prefix if a name wasn't specified.
1865 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001866 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001867
1868 // Don't share any string literals if strings aren't constant.
1869 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001870 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
1872 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner95b851e2009-07-16 05:03:48 +00001873 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001874
1875 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001876 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001877
1878 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001879 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001880 Entry.setValue(C);
1881 return C;
1882}
Daniel Dunbar61432932008-08-13 23:20:05 +00001883
1884/// GetAddrOfConstantCString - Returns a pointer to a character
1885/// array containing the literal and a terminating '\-'
1886/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001887llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1888 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001889 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001890}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001891
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001892/// EmitObjCPropertyImplementations - Emit information for synthesized
1893/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00001894void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001895 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001896 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001897 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001898 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001900 // Dynamic is just for type-checking.
1901 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1902 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1903
1904 // Determine which methods need to be implemented, some may have
1905 // been overridden. Note that ::isSynthesized is not the method
1906 // we want, that just indicates if the decl came from a
1907 // property. What we want to know is if the method is defined in
1908 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001909 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001910 CodeGenFunction(*this).GenerateObjCGetter(
1911 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001912 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001913 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001914 CodeGenFunction(*this).GenerateObjCSetter(
1915 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001916 }
1917 }
1918}
1919
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001920/// EmitObjCIvarInitializations - Emit information for ivar initialization
1921/// for an implementation.
1922void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1923 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1924 return;
1925 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1926 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1927 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1928 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1929 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1930 D->getLocation(),
1931 D->getLocation(), cxxSelector,
1932 getContext().VoidTy, 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001933 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001934 ObjCMethodDecl::Required);
1935 D->addInstanceMethod(DTORMethod);
1936 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1937
1938 II = &getContext().Idents.get(".cxx_construct");
1939 cxxSelector = getContext().Selectors.getSelector(0, &II);
1940 // The constructor returns 'self'.
1941 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1942 D->getLocation(),
1943 D->getLocation(), cxxSelector,
1944 getContext().getObjCIdType(), 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001945 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001946 ObjCMethodDecl::Required);
1947 D->addInstanceMethod(CTORMethod);
1948 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1949
1950
1951}
1952
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001953/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001954void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001955 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00001956 I != E; ++I)
1957 EmitTopLevelDecl(*I);
1958}
1959
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001960// EmitLinkageSpec - Emit all declarations in a linkage spec.
1961void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00001962 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1963 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001964 ErrorUnsupported(LSD, "linkage spec");
1965 return;
1966 }
1967
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001968 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001969 I != E; ++I)
1970 EmitTopLevelDecl(*I);
1971}
1972
Daniel Dunbar41071de2008-08-15 23:26:23 +00001973/// EmitTopLevelDecl - Emit code for a single top level declaration.
1974void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1975 // If an error has occurred, stop code generation, but continue
1976 // parsing and semantic analysis (to ensure all warnings and errors
1977 // are emitted).
1978 if (Diags.hasErrorOccurred())
1979 return;
1980
Douglas Gregor16e8be22009-06-29 17:30:29 +00001981 // Ignore dependent declarations.
1982 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1983 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Daniel Dunbar41071de2008-08-15 23:26:23 +00001985 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00001986 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001987 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001988 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00001989 // Skip function templates
1990 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1991 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001993 EmitGlobal(cast<FunctionDecl>(D));
1994 break;
1995
Daniel Dunbar41071de2008-08-15 23:26:23 +00001996 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001997 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001998 break;
1999
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002000 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002001 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002002 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002003 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002004 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002005 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002006 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002007 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002008 case Decl::ClassTemplate:
2009 case Decl::FunctionTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002010 case Decl::NamespaceAlias:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002011 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002012 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002013 // Skip function templates
2014 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2015 return;
2016
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002017 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2018 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002019 case Decl::CXXDestructor:
2020 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2021 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002022
2023 case Decl::StaticAssert:
2024 // Nothing to do.
2025 break;
2026
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002027 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002029 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002030 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002031 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002032 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00002033 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002034 break;
2035
Daniel Dunbar41071de2008-08-15 23:26:23 +00002036 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002037 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002038 break;
2039
2040 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002041 // Categories have properties but don't support synthesize so we
2042 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002043 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2044 break;
2045
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002046 case Decl::ObjCImplementation: {
2047 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2048 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002049 EmitObjCIvarInitializations(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002050 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002051 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002052 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002053 case Decl::ObjCMethod: {
2054 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2055 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002056 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002057 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2058 break;
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002061 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002062 break;
2063
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002064 case Decl::LinkageSpec:
2065 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002066 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002067
2068 case Decl::FileScopeAsm: {
2069 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramer8d042582009-12-11 13:33:18 +00002070 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Daniel Dunbar41071de2008-08-15 23:26:23 +00002072 const std::string &S = getModule().getModuleInlineAsm();
2073 if (S.empty())
2074 getModule().setModuleInlineAsm(AsmString);
2075 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002076 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002077 break;
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
2080 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002081 // Make sure we handled everything we should, every other kind is a
2082 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2083 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002084 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2085 }
2086}
John McCall744016d2010-07-06 23:57:41 +00002087
2088/// Turns the given pointer into a constant.
2089static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2090 const void *Ptr) {
2091 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2092 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2093 return llvm::ConstantInt::get(i64, PtrInt);
2094}
2095
2096static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2097 llvm::NamedMDNode *&GlobalMetadata,
2098 GlobalDecl D,
2099 llvm::GlobalValue *Addr) {
2100 if (!GlobalMetadata)
2101 GlobalMetadata =
2102 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2103
2104 // TODO: should we report variant information for ctors/dtors?
2105 llvm::Value *Ops[] = {
2106 Addr,
2107 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2108 };
2109 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2110}
2111
2112/// Emits metadata nodes associating all the global values in the
2113/// current module with the Decls they came from. This is useful for
2114/// projects using IR gen as a subroutine.
2115///
2116/// Since there's currently no way to associate an MDNode directly
2117/// with an llvm::GlobalValue, we create a global named metadata
2118/// with the name 'clang.global.decl.ptrs'.
2119void CodeGenModule::EmitDeclMetadata() {
2120 llvm::NamedMDNode *GlobalMetadata = 0;
2121
2122 // StaticLocalDeclMap
2123 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2124 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2125 I != E; ++I) {
2126 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2127 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2128 }
2129}
2130
2131/// Emits metadata nodes for all the local variables in the current
2132/// function.
2133void CodeGenFunction::EmitDeclMetadata() {
2134 if (LocalDeclMap.empty()) return;
2135
2136 llvm::LLVMContext &Context = getLLVMContext();
2137
2138 // Find the unique metadata ID for this name.
2139 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2140
2141 llvm::NamedMDNode *GlobalMetadata = 0;
2142
2143 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2144 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2145 const Decl *D = I->first;
2146 llvm::Value *Addr = I->second;
2147
2148 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2149 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2150 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2151 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2152 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2153 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2154 }
2155 }
2156}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002157
2158///@name Custom Runtime Function Interfaces
2159///@{
2160//
2161// FIXME: These can be eliminated once we can have clients just get the required
2162// AST nodes from the builtin tables.
2163
2164llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2165 if (BlockObjectDispose)
2166 return BlockObjectDispose;
2167
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002168 // If we saw an explicit decl, use that.
2169 if (BlockObjectDisposeDecl) {
2170 return BlockObjectDispose = GetAddrOfFunction(
2171 BlockObjectDisposeDecl,
2172 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2173 }
2174
2175 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002176 const llvm::FunctionType *FTy;
2177 std::vector<const llvm::Type*> ArgTys;
2178 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2179 ArgTys.push_back(PtrToInt8Ty);
2180 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2181 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2182 return BlockObjectDispose =
2183 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2184}
2185
2186llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2187 if (BlockObjectAssign)
2188 return BlockObjectAssign;
2189
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002190 // If we saw an explicit decl, use that.
2191 if (BlockObjectAssignDecl) {
2192 return BlockObjectAssign = GetAddrOfFunction(
2193 BlockObjectAssignDecl,
2194 getTypes().GetFunctionType(BlockObjectAssignDecl));
2195 }
2196
2197 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002198 const llvm::FunctionType *FTy;
2199 std::vector<const llvm::Type*> ArgTys;
2200 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2201 ArgTys.push_back(PtrToInt8Ty);
2202 ArgTys.push_back(PtrToInt8Ty);
2203 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2204 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2205 return BlockObjectAssign =
2206 CreateRuntimeFunction(FTy, "_Block_object_assign");
2207}
2208
2209llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2210 if (NSConcreteGlobalBlock)
2211 return NSConcreteGlobalBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002212
2213 // If we saw an explicit decl, use that.
2214 if (NSConcreteGlobalBlockDecl) {
2215 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2216 NSConcreteGlobalBlockDecl,
2217 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2218 }
2219
2220 // Otherwise construct the variable by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002221 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2222 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2223}
2224
2225llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2226 if (NSConcreteStackBlock)
2227 return NSConcreteStackBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002228
2229 // If we saw an explicit decl, use that.
2230 if (NSConcreteStackBlockDecl) {
2231 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2232 NSConcreteStackBlockDecl,
2233 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2234 }
2235
2236 // Otherwise construct the variable by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002237 return NSConcreteStackBlock = CreateRuntimeVariable(
2238 PtrToInt8Ty, "_NSConcreteStackBlock");
2239}
2240
2241///@}