blob: 9bb12900fa84bee9ff50c96f7aa6165954dda88e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Mike Stumpd6d0ebe2009-03-04 18:47:42 +000037 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
Mike Stump1f010b52009-03-04 18:17:45 +000038 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000040
Chris Lattner08b05eb2009-03-21 07:12:05 +000041 if (!Features.ObjC1)
42 Runtime = 0;
43 else if (!Features.NeXTRuntime)
44 Runtime = CreateGNUObjCRuntime(*this);
45 else if (Features.ObjCNonFragileABI)
46 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
47 else
48 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stumpef2c82f2009-02-13 18:36:05 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Chris Lattner13137542009-03-22 21:21:57 +000060 EmitDeferred();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000061 if (Runtime)
62 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
63 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000064 EmitCtorList(GlobalCtors, "llvm.global_ctors");
65 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000066 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000067 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000068}
69
Daniel Dunbar9503b782008-08-16 00:56:44 +000070/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000071/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000072void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
73 bool OmitOnError) {
74 if (OmitOnError && getDiags().hasErrorOccurred())
75 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000076 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000077 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +000078 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000079 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
80 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +000081}
Chris Lattner0e4755d2007-12-02 06:27:33 +000082
Daniel Dunbar9503b782008-08-16 00:56:44 +000083/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000084/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000085void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
86 bool OmitOnError) {
87 if (OmitOnError && getDiags().hasErrorOccurred())
88 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000089 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000090 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +000091 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000092 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +000093}
94
Daniel Dunbar27250d32008-08-15 23:26:23 +000095/// setGlobalVisibility - Set the visibility for the given LLVM
96/// GlobalValue according to the given clang AST visibility value.
97static void setGlobalVisibility(llvm::GlobalValue *GV,
98 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +000099 switch (Vis) {
100 default: assert(0 && "Unknown visibility!");
101 case VisibilityAttr::DefaultVisibility:
102 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
103 break;
104 case VisibilityAttr::HiddenVisibility:
105 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
106 break;
107 case VisibilityAttr::ProtectedVisibility:
108 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
109 break;
110 }
111}
112
Douglas Gregor3556bc72009-02-13 00:10:09 +0000113/// \brief Retrieves the mangled name for the given declaration.
114///
115/// If the given declaration requires a mangled name, returns an
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000116/// const char* containing the mangled name. Otherwise, returns
117/// the unmangled name.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000118///
119/// FIXME: Returning an IdentifierInfo* here is a total hack. We
120/// really need some kind of string abstraction that either stores a
121/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbar7b7f4f42009-02-18 22:52:09 +0000122/// changes to the GlobalDeclMap, too. (I disagree, I think what we
123/// actually need is for Sema to provide some notion of which Decls
124/// refer to the same semantic decl. We shouldn't need to mangle the
125/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor3556bc72009-02-13 00:10:09 +0000126///
127/// FIXME: Performance here is going to be terribly until we start
128/// caching mangled names. However, we should fix the problem above
129/// first.
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000130const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000131 // In C, functions with no attributes never need to be mangled. Fastpath them.
132 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
133 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000134 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000135 }
136
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000137 llvm::SmallString<256> Name;
138 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000139 if (!mangleName(ND, Context, Out)) {
140 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000141 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000142 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000143
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000144 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000145 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000146}
147
Chris Lattner753d2592008-03-14 17:18:18 +0000148/// AddGlobalCtor - Add a function to the list that will be called before
149/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000150void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000151 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000152 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000153}
154
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000155/// AddGlobalDtor - Add a function to the list that will be called
156/// when the module is unloaded.
157void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000158 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000159 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
160}
161
162void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
163 // Ctor function type is void()*.
164 llvm::FunctionType* CtorFTy =
165 llvm::FunctionType::get(llvm::Type::VoidTy,
166 std::vector<const llvm::Type*>(),
167 false);
168 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
169
170 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000171 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000172 llvm::StructType::get(llvm::Type::Int32Ty,
173 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000174
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000175 // Construct the constructor and destructor arrays.
176 std::vector<llvm::Constant*> Ctors;
177 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
178 std::vector<llvm::Constant*> S;
179 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
180 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
181 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000182 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000183
184 if (!Ctors.empty()) {
185 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
186 new llvm::GlobalVariable(AT, false,
187 llvm::GlobalValue::AppendingLinkage,
188 llvm::ConstantArray::get(AT, Ctors),
189 GlobalName,
190 &TheModule);
191 }
Chris Lattner753d2592008-03-14 17:18:18 +0000192}
193
Nate Begeman52da5c72008-04-18 23:43:57 +0000194void CodeGenModule::EmitAnnotations() {
195 if (Annotations.empty())
196 return;
197
198 // Create a new global variable for the ConstantStruct in the Module.
199 llvm::Constant *Array =
200 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
201 Annotations.size()),
202 Annotations);
203 llvm::GlobalValue *gv =
204 new llvm::GlobalVariable(Array->getType(), false,
205 llvm::GlobalValue::AppendingLinkage, Array,
206 "llvm.global.annotations", &TheModule);
207 gv->setSection("llvm.metadata");
208}
209
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000210void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
211 bool IsInternal,
212 bool IsInline,
213 llvm::GlobalValue *GV,
214 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000215 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000216 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000217 if (!ForDefinition) {
218 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000219 if (D->getAttr<DLLImportAttr>()) {
220 // The dllimport attribute is overridden by a subsequent declaration as
221 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000222 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000223 // dllimport attribute can be applied only to function decls, not to
224 // definitions.
225 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
226 if (!FD->getBody())
227 GV->setLinkage(llvm::Function::DLLImportLinkage);
228 } else
229 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000230 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000231 } else if (D->getAttr<WeakAttr>() ||
232 D->getAttr<WeakImportAttr>()) {
233 // "extern_weak" is overloaded in LLVM; we probably should have
234 // separate linkage types for this.
Duncan Sands9aa5c262009-03-11 08:40:02 +0000235 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000236 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000237 } else {
238 if (IsInternal) {
239 GV->setLinkage(llvm::Function::InternalLinkage);
240 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000241 if (D->getAttr<DLLExportAttr>()) {
242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
243 // The dllexport attribute is ignored for undefined symbols.
244 if (FD->getBody())
245 GV->setLinkage(llvm::Function::DLLExportLinkage);
246 } else
247 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000248 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
249 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000250 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000251 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000252 }
Nuno Lopes78534382008-06-08 15:45:52 +0000253
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000254 // FIXME: Figure out the relative priority of the attribute,
255 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000256 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000257 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000258 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000259
Daniel Dunbar97509722009-02-12 17:28:23 +0000260 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
261 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000262
263 // Only add to llvm.used when we see a definition, otherwise we
264 // might add multiple times or risk the value being replaced by a
265 // subsequent RAUW.
266 if (ForDefinition) {
267 if (D->getAttr<UsedAttr>())
268 AddUsedGlobal(GV);
269 }
Nuno Lopes78534382008-06-08 15:45:52 +0000270}
271
Devang Patela85a9ef2008-09-25 21:02:23 +0000272void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000273 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000274 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000275 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000276 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000277
Devang Patela85a9ef2008-09-25 21:02:23 +0000278 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
279 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000280
281 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000282 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000283 F->setCallingConv(llvm::CallingConv::X86_FastCall);
284
285 if (D->getAttr<StdCallAttr>())
286 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000287}
288
289/// SetFunctionAttributesForDefinition - Set function attributes
290/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000291void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
292 llvm::Function *F) {
293 if (isa<ObjCMethodDecl>(D)) {
294 SetGlobalValueAttributes(D, true, false, F, true);
295 } else {
296 const FunctionDecl *FD = cast<FunctionDecl>(D);
297 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
298 FD->isInline(), F, true);
299 }
300
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000301 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000302 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000303
304 if (D->getAttr<AlwaysInlineAttr>())
305 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000306
307 if (D->getAttr<NoinlineAttr>())
308 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000309}
310
311void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
312 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000313 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000314
Daniel Dunbar566a6502008-09-08 23:44:31 +0000315 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000316}
317
318void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
319 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000320 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000321
Daniel Dunbar566a6502008-09-08 23:44:31 +0000322 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
323 FD->isInline(), F, false);
324}
325
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000326void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
327 assert(!GV->isDeclaration() &&
328 "Only globals with definition can force usage.");
329 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
330 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
331}
332
333void CodeGenModule::EmitLLVMUsed() {
334 // Don't create llvm.used if there is no need.
335 if (LLVMUsed.empty())
336 return;
337
338 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
339 LLVMUsed.size());
340 llvm::GlobalVariable *GV =
341 new llvm::GlobalVariable(ATy, false,
342 llvm::GlobalValue::AppendingLinkage,
343 llvm::ConstantArray::get(ATy, LLVMUsed),
344 "llvm.used", &getModule());
345
346 GV->setSection("llvm.metadata");
347}
348
349void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000350 // Emit code for any potentially referenced deferred decls. Since a
351 // previously unused static decl may become used during the generation of code
352 // for a static function, iterate until no changes are made.
353 while (!DeferredDeclsToEmit.empty()) {
354 const ValueDecl *D = DeferredDeclsToEmit.back();
355 DeferredDeclsToEmit.pop_back();
356
357 // The mangled name for the decl must have been emitted in GlobalDeclMap.
358 // Look it up to see if it was defined with a stronger definition (e.g. an
359 // extern inline function with a strong function redefinition). If so,
360 // just ignore the deferred decl.
361 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
362 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000363
Chris Lattner38837f92009-03-21 09:44:56 +0000364 if (!CGRef->isDeclaration())
365 continue;
366
367 // Otherwise, emit the definition and move on to the next one.
368 EmitGlobalDefinition(D);
369 }
Chris Lattner4b009652007-07-25 00:24:17 +0000370}
371
Nate Begeman8a704172008-04-19 04:17:09 +0000372/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
373/// annotation information for a given GlobalValue. The annotation struct is
374/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000375/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000376/// created from the AnnotateAttr's annotation. The third field is a constant
377/// string containing the name of the translation unit. The fourth field is
378/// the line number in the file of the annotated value declaration.
379///
380/// FIXME: this does not unique the annotation string constants, as llvm-gcc
381/// appears to.
382///
383llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
384 const AnnotateAttr *AA,
385 unsigned LineNo) {
386 llvm::Module *M = &getModule();
387
388 // get [N x i8] constants for the annotation string, and the filename string
389 // which are the 2nd and 3rd elements of the global annotation structure.
390 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
391 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
392 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
393 true);
394
395 // Get the two global values corresponding to the ConstantArrays we just
396 // created to hold the bytes of the strings.
397 llvm::GlobalValue *annoGV =
398 new llvm::GlobalVariable(anno->getType(), false,
399 llvm::GlobalValue::InternalLinkage, anno,
400 GV->getName() + ".str", M);
401 // translation unit name string, emitted into the llvm.metadata section.
402 llvm::GlobalValue *unitGV =
403 new llvm::GlobalVariable(unit->getType(), false,
404 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
405
406 // Create the ConstantStruct that is the global annotion.
407 llvm::Constant *Fields[4] = {
408 llvm::ConstantExpr::getBitCast(GV, SBP),
409 llvm::ConstantExpr::getBitCast(annoGV, SBP),
410 llvm::ConstantExpr::getBitCast(unitGV, SBP),
411 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
412 };
413 return llvm::ConstantStruct::get(Fields, 4, false);
414}
415
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000416bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000417 // Never defer when EmitAllDecls is specified or the decl has
418 // attribute used.
419 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000420 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000421
422 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000423 // Constructors and destructors should never be deferred.
424 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
425 return false;
426
Chris Lattner7e5888f2009-03-21 08:03:33 +0000427 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000428 if (FD->getStorageClass() != FunctionDecl::Static)
429 return false;
430 } else {
431 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000432 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000433
434 if (VD->getStorageClass() != VarDecl::Static)
435 return false;
436 }
437
438 return true;
439}
440
441void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000442 // If this is an alias definition (which otherwise looks like a declaration)
443 // emit it now.
444 if (Global->getAttr<AliasAttr>())
445 return EmitAliasDefinition(Global);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000446
Chris Lattner38837f92009-03-21 09:44:56 +0000447 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000448 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000449 // Forward declarations are emitted lazily on first use.
450 if (!FD->isThisDeclarationADefinition())
451 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000452 } else {
453 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000454 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
455
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000456 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000457 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000458 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000459 }
460
Chris Lattner38837f92009-03-21 09:44:56 +0000461 // Defer code generation when possible if this is a static definition, inline
462 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000463 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000464 // If the value has already been used, add it directly to the
465 // DeferredDeclsToEmit list.
466 const char *MangledName = getMangledName(Global);
467 if (GlobalDeclMap.count(MangledName))
468 DeferredDeclsToEmit.push_back(Global);
469 else {
470 // Otherwise, remember that we saw a deferred decl with this name. The
471 // first use of the mangled name will cause it to move into
472 // DeferredDeclsToEmit.
473 DeferredDecls[MangledName] = Global;
474 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000475 return;
476 }
477
478 // Otherwise emit the definition.
479 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000480}
481
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000482void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
483 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
484 EmitGlobalFunctionDefinition(FD);
485 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
486 EmitGlobalVarDefinition(VD);
487 } else {
488 assert(0 && "Invalid argument to EmitGlobalDefinition()");
489 }
490}
491
Chris Lattneraea1aee2009-03-22 21:03:39 +0000492/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
493/// module, create and return an llvm Function with the specified type. If there
494/// is something in the module with the specified name, return it potentially
495/// bitcasted to the right type.
496///
497/// If D is non-null, it specifies a decl that correspond to this. This is used
498/// to set the attributes on the function when it is first created.
499llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
500 const llvm::Type *Ty,
501 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000502 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000503 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
504 if (Entry) {
505 if (Entry->getType()->getElementType() == Ty)
506 return Entry;
507
508 // Make sure the result is of the correct type.
509 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
510 return llvm::ConstantExpr::getBitCast(Entry, PTy);
511 }
512
Chris Lattner38837f92009-03-21 09:44:56 +0000513 // This is the first use or definition of a mangled name. If there is a
514 // deferred decl with this name, remember that we need to emit it at the end
515 // of the file.
516 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000517 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000518 if (DDI != DeferredDecls.end()) {
519 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
520 // list, and remove it from DeferredDecls (since we don't need it anymore).
521 DeferredDeclsToEmit.push_back(DDI->second);
522 DeferredDecls.erase(DDI);
523 }
524
Chris Lattner5dd030f2009-03-21 09:25:43 +0000525 // This function doesn't have a complete type (for example, the return
526 // type is an incomplete struct). Use a fake type instead, and make
527 // sure not to try to set attributes.
528 bool ShouldSetAttributes = true;
529 if (!isa<llvm::FunctionType>(Ty)) {
530 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
531 std::vector<const llvm::Type*>(), false);
532 ShouldSetAttributes = false;
533 }
534 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
535 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000536 "", &getModule());
537 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000538 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000539 SetFunctionAttributes(D, F);
540 Entry = F;
541 return F;
542}
543
Chris Lattneraea1aee2009-03-22 21:03:39 +0000544/// GetAddrOfFunction - Return the address of the given function. If Ty is
545/// non-null, then this function will use the specified type if it has to
546/// create it (this occurs when we see a definition of the function).
547llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
548 const llvm::Type *Ty) {
549 // If there was no specific requested type, just convert it now.
550 if (!Ty)
551 Ty = getTypes().ConvertType(D->getType());
552 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
553}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000554
Chris Lattneraea1aee2009-03-22 21:03:39 +0000555/// CreateRuntimeFunction - Create a new runtime function with the specified
556/// type and name.
557llvm::Constant *
558CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
559 const char *Name) {
560 // Convert Name to be a uniqued string from the IdentifierInfo table.
561 Name = getContext().Idents.get(Name).getName();
562 return GetOrCreateLLVMFunction(Name, FTy, 0);
563}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000564
Chris Lattneraea1aee2009-03-22 21:03:39 +0000565/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
566/// create and return an llvm GlobalVariable with the specified type. If there
567/// is something in the module with the specified name, return it potentially
568/// bitcasted to the right type.
569///
570/// If D is non-null, it specifies a decl that correspond to this. This is used
571/// to set the attributes on the global when it is first created.
572llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
573 const llvm::PointerType*Ty,
574 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000575 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000576 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000577 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000578 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000579 return Entry;
580
Chris Lattner7e5888f2009-03-21 08:03:33 +0000581 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000582 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000583 }
Chris Lattner38837f92009-03-21 09:44:56 +0000584
585 // This is the first use or definition of a mangled name. If there is a
586 // deferred decl with this name, remember that we need to emit it at the end
587 // of the file.
588 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
589 DeferredDecls.find(MangledName);
590 if (DDI != DeferredDecls.end()) {
591 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
592 // list, and remove it from DeferredDecls (since we don't need it anymore).
593 DeferredDeclsToEmit.push_back(DDI->second);
594 DeferredDecls.erase(DDI);
595 }
596
Chris Lattner7e5888f2009-03-21 08:03:33 +0000597 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000598 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000599 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000600 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000601 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000602 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000603
604 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000605 if (D) {
606 // FIXME: This code is overly simple and should be merged with
607 // other global handling.
608 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000609
Chris Lattneraea1aee2009-03-22 21:03:39 +0000610 // FIXME: Merge with other attribute handling code.
611 if (D->getStorageClass() == VarDecl::PrivateExtern)
612 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000613
Chris Lattneraea1aee2009-03-22 21:03:39 +0000614 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
615 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
616 }
617
Chris Lattner7e5888f2009-03-21 08:03:33 +0000618 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000619}
620
Chris Lattneraea1aee2009-03-22 21:03:39 +0000621
622/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
623/// given global variable. If Ty is non-null and if the global doesn't exist,
624/// then it will be greated with the specified type instead of whatever the
625/// normal requested type would be.
626llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
627 const llvm::Type *Ty) {
628 assert(D->hasGlobalStorage() && "Not a global variable");
629 QualType ASTTy = D->getType();
630 if (Ty == 0)
631 Ty = getTypes().ConvertTypeForMem(ASTTy);
632
633 const llvm::PointerType *PTy =
634 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
635 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
636}
637
638/// CreateRuntimeVariable - Create a new runtime global variable with the
639/// specified type and name.
640llvm::Constant *
641CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
642 const char *Name) {
643 // Convert Name to be a uniqued string from the IdentifierInfo table.
644 Name = getContext().Idents.get(Name).getName();
645 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
646}
647
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000648void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000649 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000650 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000651
Chris Lattner4b009652007-07-25 00:24:17 +0000652 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000653 // This is a tentative definition; tentative definitions are
654 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000655 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000656 if (ASTTy->isIncompleteArrayType()) {
657 // An incomplete array is normally [ TYPE x 0 ], but we need
658 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000659 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000660 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000661 }
662 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000663 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000664 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000665 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000666 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000667 QualType T = D->getInit()->getType();
668 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
669 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000670 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000671
Chris Lattner23afd5b2009-03-21 08:13:05 +0000672 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000673 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000674
Chris Lattnera6984932009-03-21 09:16:30 +0000675 // Strip off a bitcast if we got one back.
676 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
677 assert(CE->getOpcode() == llvm::Instruction::BitCast);
678 Entry = CE->getOperand(0);
679 }
680
681 // Entry is now either a Function or GlobalVariable.
682 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
683
684 // If we already have this global and it has an initializer, then
685 // we are in the rare situation where we emitted the defining
686 // declaration of the global and are now being asked to emit a
687 // definition which would be common. This occurs, for example, in
688 // the following situation because statics can be emitted out of
689 // order:
690 //
691 // static int x;
692 // static int *y = &x;
693 // static int x = 10;
694 // int **z = &y;
695 //
696 // Bail here so we don't blow away the definition. Note that if we
697 // can't distinguish here if we emitted a definition with a null
698 // initializer, but this case is safe.
699 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000700 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
701 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000702 }
703
704 // We have a definition after a declaration with the wrong type.
705 // We must make a new GlobalVariable* and update everything that used OldGV
706 // (a declaration or tentative definition) with the new GlobalVariable*
707 // (which will be a definition).
708 //
709 // This happens if there is a prototype for a global (e.g.
710 // "extern int x[];") and then a definition of a different type (e.g.
711 // "int x[10];"). This also happens when an initializer has a different type
712 // from the type of the global (this happens with unions).
713 //
714 // FIXME: This also ends up happening if there's a definition followed by
715 // a tentative definition! (Although Sema rejects that construct
716 // at the moment.)
717 if (GV == 0 ||
718 GV->getType()->getElementType() != InitType ||
719 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
720
721 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
722 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000723
Chris Lattnera6984932009-03-21 09:16:30 +0000724 // Make a new global with the correct type, this is now guaranteed to work.
725 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000726 GV->takeName(cast<llvm::GlobalValue>(Entry));
727
Eli Friedman43a0ce82008-05-30 19:50:47 +0000728 // Replace all uses of the old global with the new global
729 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000730 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
731 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000732
733 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000734 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattnera6984932009-03-21 09:16:30 +0000735 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000737
Nate Begeman8a704172008-04-19 04:17:09 +0000738 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
739 SourceManager &SM = Context.getSourceManager();
740 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000741 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000742 }
743
Chris Lattner4b009652007-07-25 00:24:17 +0000744 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000745 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000746 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000747
Chris Lattner402b3372008-03-03 03:28:21 +0000748 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000749 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000750 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000751
Chris Lattner4b009652007-07-25 00:24:17 +0000752 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000753 if (D->getStorageClass() == VarDecl::Static)
754 GV->setLinkage(llvm::Function::InternalLinkage);
755 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000756 GV->setLinkage(llvm::Function::DLLImportLinkage);
757 else if (D->getAttr<DLLExportAttr>())
758 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000759 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000760 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000761 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000762 // FIXME: This isn't right. This should handle common linkage and other
763 // stuff.
764 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000765 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000766 case VarDecl::Auto:
767 case VarDecl::Register:
768 assert(0 && "Can't have auto or register globals");
769 case VarDecl::None:
770 if (!D->getInit())
Duncan Sands78c33cc2009-03-11 20:15:27 +0000771 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000772 else
773 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000774 break;
775 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000776 // FIXME: common
777 break;
778
Chris Lattner402b3372008-03-03 03:28:21 +0000779 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000780 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
781 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000782 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000783 }
Chris Lattner4b009652007-07-25 00:24:17 +0000784 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000785
Daniel Dunbar97509722009-02-12 17:28:23 +0000786 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
787 GV->setSection(SA->getName());
788
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000789 if (D->getAttr<UsedAttr>())
790 AddUsedGlobal(GV);
791
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000792 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000793 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000794 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000795 DI->EmitGlobalVariable(GV, D);
796 }
Chris Lattner4b009652007-07-25 00:24:17 +0000797}
798
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000799
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000800void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000801 const llvm::FunctionType *Ty =
802 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
803
804 // As a special case, make sure that definitions of K&R function
805 // "type foo()" aren't declared as varargs (which forces the backend
806 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000807 if (D->getType()->isFunctionNoProtoType()) {
808 assert(Ty->isVarArg() && "Didn't lower type as expected");
809 // Due to stret, the lowered function could have arguments. Just create the
810 // same type as was lowered by ConvertType but strip off the varargs bit.
811 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
812 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
813 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000814
Chris Lattnerd26784e2009-03-21 08:53:37 +0000815 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000816 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000817
Chris Lattner5dd030f2009-03-21 09:25:43 +0000818 // Strip off a bitcast if we got one back.
819 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
820 assert(CE->getOpcode() == llvm::Instruction::BitCast);
821 Entry = CE->getOperand(0);
822 }
823
824
825 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000826 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000827 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
828 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000829
Chris Lattnere28718c2009-03-21 08:38:50 +0000830 // F is the Function* for the one with the wrong type, we must make a new
831 // Function* and update everything that used F (a declaration) with the new
832 // Function* (which will be a definition).
833 //
834 // This happens if there is a prototype for a function
835 // (e.g. "int f()") and then a definition of a different type
836 // (e.g. "int f(int x)"). Start by making a new function of the
837 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000838 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000839 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
840 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000841
842 // Replace uses of F with the Function we will endow with a body.
843 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000844 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
845 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000846
847 // Ok, delete the old function now, which is dead.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000848 // FIXME: If it was attribute(used) the pointer will dangle from the
849 // LLVMUsed array!
Chris Lattner5dd030f2009-03-21 09:25:43 +0000850 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000851
Chris Lattner5dd030f2009-03-21 09:25:43 +0000852 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000853 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000854
855 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000856
Daniel Dunbar566a6502008-09-08 23:44:31 +0000857 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000858
Daniel Dunbar566a6502008-09-08 23:44:31 +0000859 SetFunctionAttributesForDefinition(D, Fn);
860
Chris Lattnerd26784e2009-03-21 08:53:37 +0000861 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000862 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000863 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000864 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000865}
866
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000867void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
868 const AliasAttr *AA = D->getAttr<AliasAttr>();
869 assert(AA && "Not an alias?");
870
871 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
872
873 // Unique the name through the identifier table.
874 const char *AliaseeName = AA->getAliasee().c_str();
875 AliaseeName = getContext().Idents.get(AliaseeName).getName();
876
877 // Create a reference to the named value. This ensures that it is emitted
878 // if a deferred decl.
879 llvm::Constant *Aliasee;
880 if (isa<llvm::FunctionType>(DeclTy))
881 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
882 else
883 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
884 llvm::PointerType::getUnqual(DeclTy), 0);
885
886 // Create the new alias itself, but don't set a name yet.
887 llvm::GlobalValue *GA =
888 new llvm::GlobalAlias(Aliasee->getType(),
889 llvm::Function::ExternalLinkage,
890 "", Aliasee, &getModule());
891
892 // See if there is already something with the alias' name in the module.
893 const char *MangledName = getMangledName(D);
894 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
895
896 if (Entry && !Entry->isDeclaration()) {
897 // If there is a definition in the module, then it wins over the alias.
898 // This is dubious, but allow it to be safe. Just ignore the alias.
899 GA->eraseFromParent();
900 return;
901 }
902
903 if (Entry) {
904 // If there is a declaration in the module, then we had an extern followed
905 // by the alias, as in:
906 // extern int test6();
907 // ...
908 // int test6() __attribute__((alias("test7")));
909 //
910 // Remove it and replace uses of it with the alias.
911
912 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
913 Entry->getType()));
914 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
915 Entry->eraseFromParent();
916 }
917
918 // Now we know that there is no conflict, set the name.
919 Entry = GA;
920 GA->setName(MangledName);
921
922 // Alias should never be internal or inline.
923 SetGlobalValueAttributes(D, false, false, GA, true);
924}
925
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000926void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
927 // Make sure that this type is translated.
928 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000929}
930
931
Chris Lattnerab862cc2007-08-31 04:31:45 +0000932/// getBuiltinLibFunction
Mike Stump96b7a152009-02-27 22:42:30 +0000933llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000934 if (BuiltinID > BuiltinFunctions.size())
935 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000936
Chris Lattner9f2d6892007-12-13 00:38:03 +0000937 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
938 // a slot for it.
939 assert(BuiltinID && "Invalid Builtin ID");
Mike Stump96b7a152009-02-27 22:42:30 +0000940 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000941 if (FunctionSlot)
942 return FunctionSlot;
943
Douglas Gregor411889e2009-02-13 23:20:09 +0000944 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
945 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
946 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000947
Douglas Gregor411889e2009-02-13 23:20:09 +0000948 // Get the name, skip over the __builtin_ prefix (if necessary).
949 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
950 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
951 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000952
953 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000954 Builtin::Context::GetBuiltinTypeError Error;
955 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
956 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
957
Chris Lattnerab862cc2007-08-31 04:31:45 +0000958 const llvm::FunctionType *Ty =
959 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
960
961 // FIXME: This has a serious problem with code like this:
962 // void abs() {}
963 // ... __builtin_abs(x);
964 // The two versions of abs will collide. The fix is for the builtin to win,
965 // and for the existing one to be turned into a constantexpr cast of the
966 // builtin. In the case where the existing one is a static function, it
967 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000968 if (llvm::Function *Existing = getModule().getFunction(Name)) {
969 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
970 return FunctionSlot = Existing;
971 assert(Existing == 0 && "FIXME: Name collision");
972 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000973
Chris Lattner72cdb962009-03-01 18:47:06 +0000974 llvm::GlobalValue *&ExistingFn =
975 GlobalDeclMap[getContext().Idents.get(Name).getName()];
Chris Lattner71fc5812009-03-21 06:58:21 +0000976 assert(!ExistingFn && "Asking for the same builtin multiple times?");
Mike Stump96b7a152009-02-27 22:42:30 +0000977
Chris Lattnerab862cc2007-08-31 04:31:45 +0000978 // FIXME: param attributes for sext/zext etc.
Chris Lattner72cdb962009-03-01 18:47:06 +0000979 return FunctionSlot = ExistingFn =
Nate Begemanad320b62008-04-20 06:29:50 +0000980 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
981 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000982}
983
Chris Lattner4b23f942007-12-18 00:25:38 +0000984llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
985 unsigned NumTys) {
986 return llvm::Intrinsic::getDeclaration(&getModule(),
987 (llvm::Intrinsic::ID)IID, Tys, NumTys);
988}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000989
Chris Lattner4b009652007-07-25 00:24:17 +0000990llvm::Function *CodeGenModule::getMemCpyFn() {
991 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000992 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
993 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000994}
Anders Carlsson36a04872007-08-21 00:21:21 +0000995
Eli Friedman8f08a252008-05-26 12:59:39 +0000996llvm::Function *CodeGenModule::getMemMoveFn() {
997 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000998 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
999 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +00001000}
1001
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +00001002llvm::Function *CodeGenModule::getMemSetFn() {
1003 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +00001004 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1005 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +00001006}
Chris Lattner4b23f942007-12-18 00:25:38 +00001007
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001008static void appendFieldAndPadding(CodeGenModule &CGM,
1009 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +00001010 FieldDecl *FieldD, FieldDecl *NextFieldD,
1011 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +00001012 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001013 // Append the field.
1014 Fields.push_back(Field);
1015
Douglas Gregor8acb7272008-12-11 16:49:14 +00001016 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001017
1018 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001019 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001020 NextStructFieldNo = STy->getNumElements();
1021 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001022 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001023 }
1024
1025 // Append padding
1026 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1027 llvm::Constant *C =
1028 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1029
1030 Fields.push_back(C);
1031 }
1032}
1033
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001034// We still need to work out the details of handling UTF-16.
1035// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001036llvm::Constant *CodeGenModule::
1037GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001038 llvm::StringMapEntry<llvm::Constant *> &Entry =
1039 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1040
1041 if (Entry.getValue())
1042 return Entry.getValue();
1043
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001044 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1045 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001046
1047 if (!CFConstantStringClassRef) {
1048 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1049 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001050
1051 // FIXME: This is fairly broken if
1052 // __CFConstantStringClassReference is already defined, in that it
1053 // will get renamed and the user will most likely see an opaque
1054 // error message. This is a general issue with relying on
1055 // particular names.
1056 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001057 new llvm::GlobalVariable(Ty, false,
1058 llvm::GlobalVariable::ExternalLinkage, 0,
1059 "__CFConstantStringClassReference",
1060 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001061
1062 // Decay array -> ptr
1063 CFConstantStringClassRef =
1064 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001065 }
1066
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001067 QualType CFTy = getContext().getCFConstantStringType();
1068 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001069
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001070 const llvm::StructType *STy =
1071 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1072
1073 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001074 RecordDecl::field_iterator Field = CFRD->field_begin();
1075
Anders Carlsson36a04872007-08-21 00:21:21 +00001076 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001077 FieldDecl *CurField = *Field++;
1078 FieldDecl *NextField = *Field++;
1079 appendFieldAndPadding(*this, Fields, CurField, NextField,
1080 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001081
1082 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001083 CurField = NextField;
1084 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001085 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001086 appendFieldAndPadding(*this, Fields, CurField, NextField,
1087 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001088
1089 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001090 CurField = NextField;
1091 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001092 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001093 C = new llvm::GlobalVariable(C->getType(), true,
1094 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001095 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001096 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001097 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1098 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001099
1100 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001101 CurField = NextField;
1102 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001103 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001104 appendFieldAndPadding(*this, Fields, CurField, NextField,
1105 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001106
1107 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001108 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001109 llvm::GlobalVariable *GV =
1110 new llvm::GlobalVariable(C->getType(), true,
1111 llvm::GlobalVariable::InternalLinkage,
1112 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001113
Anders Carlsson9be009e2007-11-01 00:41:52 +00001114 GV->setSection("__DATA,__cfstring");
1115 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001116
Anders Carlsson9be009e2007-11-01 00:41:52 +00001117 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001118}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001119
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001120/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001121/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001122std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001123 const char *StrData = E->getStrData();
1124 unsigned Len = E->getByteLength();
1125
1126 const ConstantArrayType *CAT =
1127 getContext().getAsConstantArrayType(E->getType());
1128 assert(CAT && "String isn't pointer or array!");
1129
Chris Lattner14032222009-02-26 23:01:51 +00001130 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001131 std::string Str(StrData, StrData+Len);
1132 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001133
1134 if (E->isWide())
1135 RealLen *= getContext().Target.getWCharWidth()/8;
1136
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001137 Str.resize(RealLen, '\0');
1138
1139 return Str;
1140}
1141
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001142/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1143/// constant array for the given string literal.
1144llvm::Constant *
1145CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1146 // FIXME: This can be more efficient.
1147 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1148}
1149
Chris Lattnerc5d32632009-02-24 22:18:39 +00001150/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1151/// array for the given ObjCEncodeExpr node.
1152llvm::Constant *
1153CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1154 std::string Str;
1155 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001156
1157 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001158}
1159
1160
Chris Lattnera6dcce32008-02-11 00:02:17 +00001161/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001162static llvm::Constant *GenerateStringLiteral(const std::string &str,
1163 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001164 CodeGenModule &CGM,
1165 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001166 // Create Constant for this string literal. Don't add a '\0'.
1167 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001168
1169 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001170 return new llvm::GlobalVariable(C->getType(), constant,
1171 llvm::GlobalValue::InternalLinkage,
1172 C, GlobalName ? GlobalName : ".str",
1173 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001174}
1175
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001176/// GetAddrOfConstantString - Returns a pointer to a character array
1177/// containing the literal. This contents are exactly that of the
1178/// given string, i.e. it will not be null terminated automatically;
1179/// see GetAddrOfConstantCString. Note that whether the result is
1180/// actually a pointer to an LLVM constant depends on
1181/// Feature.WriteableStrings.
1182///
1183/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001184llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1185 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001186 // Don't share any string literals if writable-strings is turned on.
1187 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001188 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001189
1190 llvm::StringMapEntry<llvm::Constant *> &Entry =
1191 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1192
1193 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001194 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001195
1196 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001197 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001198 Entry.setValue(C);
1199 return C;
1200}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001201
1202/// GetAddrOfConstantCString - Returns a pointer to a character
1203/// array containing the literal and a terminating '\-'
1204/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001205llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1206 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001207 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001208}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001209
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001210/// EmitObjCPropertyImplementations - Emit information for synthesized
1211/// properties for an implementation.
1212void CodeGenModule::EmitObjCPropertyImplementations(const
1213 ObjCImplementationDecl *D) {
1214 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1215 e = D->propimpl_end(); i != e; ++i) {
1216 ObjCPropertyImplDecl *PID = *i;
1217
1218 // Dynamic is just for type-checking.
1219 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1220 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1221
1222 // Determine which methods need to be implemented, some may have
1223 // been overridden. Note that ::isSynthesized is not the method
1224 // we want, that just indicates if the decl came from a
1225 // property. What we want to know is if the method is defined in
1226 // this implementation.
1227 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001228 CodeGenFunction(*this).GenerateObjCGetter(
1229 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001230 if (!PD->isReadOnly() &&
1231 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001232 CodeGenFunction(*this).GenerateObjCSetter(
1233 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001234 }
1235 }
1236}
1237
Daniel Dunbar27250d32008-08-15 23:26:23 +00001238/// EmitTopLevelDecl - Emit code for a single top level declaration.
1239void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1240 // If an error has occurred, stop code generation, but continue
1241 // parsing and semantic analysis (to ensure all warnings and errors
1242 // are emitted).
1243 if (Diags.hasErrorOccurred())
1244 return;
1245
1246 switch (D->getKind()) {
1247 case Decl::Function:
1248 case Decl::Var:
1249 EmitGlobal(cast<ValueDecl>(D));
1250 break;
1251
1252 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001253 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001254 break;
1255
1256 // Objective-C Decls
1257
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001258 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001259 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001260 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001261 case Decl::ObjCCategory:
1262 case Decl::ObjCInterface:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001263 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001264
Daniel Dunbar27250d32008-08-15 23:26:23 +00001265 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001266 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001267 break;
1268
1269 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001270 // Categories have properties but don't support synthesize so we
1271 // can ignore them here.
1272
Daniel Dunbar27250d32008-08-15 23:26:23 +00001273 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1274 break;
1275
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001276 case Decl::ObjCImplementation: {
1277 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1278 EmitObjCPropertyImplementations(OMD);
1279 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001280 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001281 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001282 case Decl::ObjCMethod: {
1283 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1284 // If this is not a prototype, emit the body.
1285 if (OMD->getBody())
1286 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1287 break;
1288 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001289 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001290 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001291 break;
1292
1293 case Decl::LinkageSpec: {
1294 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1295 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001296 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001297 // FIXME: implement C++ linkage, C linkage works mostly by C
1298 // language reuse already.
1299 break;
1300 }
1301
1302 case Decl::FileScopeAsm: {
1303 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1304 std::string AsmString(AD->getAsmString()->getStrData(),
1305 AD->getAsmString()->getByteLength());
1306
1307 const std::string &S = getModule().getModuleInlineAsm();
1308 if (S.empty())
1309 getModule().setModuleInlineAsm(AsmString);
1310 else
1311 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1312 break;
1313 }
1314
1315 default:
1316 // Make sure we handled everything we should, every other kind is
1317 // a non-top-level decl. FIXME: Would be nice to have an
1318 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1319 // that easily.
1320 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1321 }
1322}