blob: 8a880516f66e73c531013a16e2dd6ef87c06f8bd [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"
Chris Lattnerbd360642009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000027#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000028#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000030#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerbd360642009-03-26 05:00:52 +000035CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattnerfb97b032007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerbd360642009-03-26 05:00:52 +000037 Diagnostic &diags)
38 : BlockModule(C, M, TD, Types, *this), Context(C),
39 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000040 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
41 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000042
Chris Lattner3c8f1532009-03-21 07:12:05 +000043 if (!Features.ObjC1)
44 Runtime = 0;
45 else if (!Features.NeXTRuntime)
46 Runtime = CreateGNUObjCRuntime(*this);
47 else if (Features.ObjCNonFragileABI)
48 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
49 else
50 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000051
52 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerbd360642009-03-26 05:00:52 +000053 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000054}
55
56CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000057 delete Runtime;
58 delete DebugInfo;
59}
60
61void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +000062 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000063 if (Runtime)
64 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
65 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000066 EmitCtorList(GlobalCtors, "llvm.global_ctors");
67 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000068 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000069 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000070}
71
Daniel Dunbar488e9932008-08-16 00:56:44 +000072/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000073/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000074void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
75 bool OmitOnError) {
76 if (OmitOnError && getDiags().hasErrorOccurred())
77 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000078 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000079 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000080 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000081 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
82 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000083}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000084
Daniel Dunbar488e9932008-08-16 00:56:44 +000085/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000086/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000087void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
88 bool OmitOnError) {
89 if (OmitOnError && getDiags().hasErrorOccurred())
90 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000091 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000092 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000093 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000094 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000095}
96
Daniel Dunbar41071de2008-08-15 23:26:23 +000097/// setGlobalVisibility - Set the visibility for the given LLVM
98/// GlobalValue according to the given clang AST visibility value.
99static void setGlobalVisibility(llvm::GlobalValue *GV,
100 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000101 switch (Vis) {
102 default: assert(0 && "Unknown visibility!");
103 case VisibilityAttr::DefaultVisibility:
104 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
105 break;
106 case VisibilityAttr::HiddenVisibility:
107 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
108 break;
109 case VisibilityAttr::ProtectedVisibility:
110 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
111 break;
112 }
113}
114
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000115/// \brief Retrieves the mangled name for the given declaration.
116///
117/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000118/// const char* containing the mangled name. Otherwise, returns
119/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000120///
121/// FIXME: Returning an IdentifierInfo* here is a total hack. We
122/// really need some kind of string abstraction that either stores a
123/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbarb5da3e92009-02-18 22:52:09 +0000124/// changes to the GlobalDeclMap, too. (I disagree, I think what we
125/// actually need is for Sema to provide some notion of which Decls
126/// refer to the same semantic decl. We shouldn't need to mangle the
127/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000128///
129/// FIXME: Performance here is going to be terribly until we start
130/// caching mangled names. However, we should fix the problem above
131/// first.
Douglas Gregor6ec36682009-02-18 23:53:56 +0000132const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000133 // In C, functions with no attributes never need to be mangled. Fastpath them.
134 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
135 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000136 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000137 }
138
Douglas Gregor6ec36682009-02-18 23:53:56 +0000139 llvm::SmallString<256> Name;
140 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000141 if (!mangleName(ND, Context, Out)) {
142 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000143 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000144 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000145
Douglas Gregor6ec36682009-02-18 23:53:56 +0000146 Name += '\0';
Chris Lattner3c8f1532009-03-21 07:12:05 +0000147 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000148}
149
Chris Lattner6d397602008-03-14 17:18:18 +0000150/// AddGlobalCtor - Add a function to the list that will be called before
151/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000153 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000154 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000155}
156
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000157/// AddGlobalDtor - Add a function to the list that will be called
158/// when the module is unloaded.
159void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000160 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000161 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
162}
163
164void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
165 // Ctor function type is void()*.
166 llvm::FunctionType* CtorFTy =
167 llvm::FunctionType::get(llvm::Type::VoidTy,
168 std::vector<const llvm::Type*>(),
169 false);
170 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
171
172 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000173 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000174 llvm::StructType::get(llvm::Type::Int32Ty,
175 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000176
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000177 // Construct the constructor and destructor arrays.
178 std::vector<llvm::Constant*> Ctors;
179 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
180 std::vector<llvm::Constant*> S;
181 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
182 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
183 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000184 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185
186 if (!Ctors.empty()) {
187 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
188 new llvm::GlobalVariable(AT, false,
189 llvm::GlobalValue::AppendingLinkage,
190 llvm::ConstantArray::get(AT, Ctors),
191 GlobalName,
192 &TheModule);
193 }
Chris Lattner6d397602008-03-14 17:18:18 +0000194}
195
Nate Begeman532485c2008-04-18 23:43:57 +0000196void CodeGenModule::EmitAnnotations() {
197 if (Annotations.empty())
198 return;
199
200 // Create a new global variable for the ConstantStruct in the Module.
201 llvm::Constant *Array =
202 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
203 Annotations.size()),
204 Annotations);
205 llvm::GlobalValue *gv =
206 new llvm::GlobalVariable(Array->getType(), false,
207 llvm::GlobalValue::AppendingLinkage, Array,
208 "llvm.global.annotations", &TheModule);
209 gv->setSection("llvm.metadata");
210}
211
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000212void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
213 bool IsInternal,
214 bool IsInline,
215 llvm::GlobalValue *GV,
216 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000217 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000218 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000219 if (!ForDefinition) {
220 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000221 if (D->getAttr<DLLImportAttr>()) {
222 // The dllimport attribute is overridden by a subsequent declaration as
223 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000224 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000225 // dllimport attribute can be applied only to function decls, not to
226 // definitions.
227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
228 if (!FD->getBody())
229 GV->setLinkage(llvm::Function::DLLImportLinkage);
230 } else
231 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000232 }
Daniel Dunbar5e273142009-03-06 16:20:49 +0000233 } else if (D->getAttr<WeakAttr>() ||
234 D->getAttr<WeakImportAttr>()) {
235 // "extern_weak" is overloaded in LLVM; we probably should have
236 // separate linkage types for this.
Duncan Sandse3fedbe2009-03-11 08:40:02 +0000237 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000238 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000239 } else {
240 if (IsInternal) {
241 GV->setLinkage(llvm::Function::InternalLinkage);
242 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000243 if (D->getAttr<DLLExportAttr>()) {
244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245 // The dllexport attribute is ignored for undefined symbols.
246 if (FD->getBody())
247 GV->setLinkage(llvm::Function::DLLExportLinkage);
248 } else
249 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000250 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
251 IsInline)
Mike Stump286acbd2009-03-07 16:33:28 +0000252 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000253 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000254 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000255
Daniel Dunbar49988882009-01-13 02:25:00 +0000256 // FIXME: Figure out the relative priority of the attribute,
257 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000258 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000259 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000260 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000261
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000262 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
263 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000264
265 // Only add to llvm.used when we see a definition, otherwise we
266 // might add multiple times or risk the value being replaced by a
267 // subsequent RAUW.
268 if (ForDefinition) {
269 if (D->getAttr<UsedAttr>())
270 AddUsedGlobal(GV);
271 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000272}
273
Devang Patel761d7f72008-09-25 21:02:23 +0000274void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000275 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000276 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000277 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000278 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000279
Devang Patel761d7f72008-09-25 21:02:23 +0000280 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
281 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000282
283 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000284 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000285 F->setCallingConv(llvm::CallingConv::X86_FastCall);
286
287 if (D->getAttr<StdCallAttr>())
288 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000289}
290
291/// SetFunctionAttributesForDefinition - Set function attributes
292/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000293void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
294 llvm::Function *F) {
295 if (isa<ObjCMethodDecl>(D)) {
296 SetGlobalValueAttributes(D, true, false, F, true);
297 } else {
298 const FunctionDecl *FD = cast<FunctionDecl>(D);
299 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
300 FD->isInline(), F, true);
301 }
302
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000303 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000304 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000305
306 if (D->getAttr<AlwaysInlineAttr>())
307 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000308
309 if (D->getAttr<NoinlineAttr>())
310 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000311}
312
313void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
314 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000315 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000316
Daniel Dunbar219df662008-09-08 23:44:31 +0000317 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000318}
319
320void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
321 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000322 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000323
Daniel Dunbar219df662008-09-08 23:44:31 +0000324 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
325 FD->isInline(), F, false);
326}
327
Daniel Dunbar02698712009-02-13 20:29:50 +0000328void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
329 assert(!GV->isDeclaration() &&
330 "Only globals with definition can force usage.");
331 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
332 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
333}
334
335void CodeGenModule::EmitLLVMUsed() {
336 // Don't create llvm.used if there is no need.
337 if (LLVMUsed.empty())
338 return;
339
340 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
341 LLVMUsed.size());
342 llvm::GlobalVariable *GV =
343 new llvm::GlobalVariable(ATy, false,
344 llvm::GlobalValue::AppendingLinkage,
345 llvm::ConstantArray::get(ATy, LLVMUsed),
346 "llvm.used", &getModule());
347
348 GV->setSection("llvm.metadata");
349}
350
351void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000352 // Emit code for any potentially referenced deferred decls. Since a
353 // previously unused static decl may become used during the generation of code
354 // for a static function, iterate until no changes are made.
355 while (!DeferredDeclsToEmit.empty()) {
356 const ValueDecl *D = DeferredDeclsToEmit.back();
357 DeferredDeclsToEmit.pop_back();
358
359 // The mangled name for the decl must have been emitted in GlobalDeclMap.
360 // Look it up to see if it was defined with a stronger definition (e.g. an
361 // extern inline function with a strong function redefinition). If so,
362 // just ignore the deferred decl.
363 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
364 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000365
Chris Lattner67b00522009-03-21 09:44:56 +0000366 if (!CGRef->isDeclaration())
367 continue;
368
369 // Otherwise, emit the definition and move on to the next one.
370 EmitGlobalDefinition(D);
371 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000372}
373
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000374/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
375/// annotation information for a given GlobalValue. The annotation struct is
376/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000377/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000378/// created from the AnnotateAttr's annotation. The third field is a constant
379/// string containing the name of the translation unit. The fourth field is
380/// the line number in the file of the annotated value declaration.
381///
382/// FIXME: this does not unique the annotation string constants, as llvm-gcc
383/// appears to.
384///
385llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
386 const AnnotateAttr *AA,
387 unsigned LineNo) {
388 llvm::Module *M = &getModule();
389
390 // get [N x i8] constants for the annotation string, and the filename string
391 // which are the 2nd and 3rd elements of the global annotation structure.
392 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
393 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
394 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
395 true);
396
397 // Get the two global values corresponding to the ConstantArrays we just
398 // created to hold the bytes of the strings.
399 llvm::GlobalValue *annoGV =
400 new llvm::GlobalVariable(anno->getType(), false,
401 llvm::GlobalValue::InternalLinkage, anno,
402 GV->getName() + ".str", M);
403 // translation unit name string, emitted into the llvm.metadata section.
404 llvm::GlobalValue *unitGV =
405 new llvm::GlobalVariable(unit->getType(), false,
406 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
407
408 // Create the ConstantStruct that is the global annotion.
409 llvm::Constant *Fields[4] = {
410 llvm::ConstantExpr::getBitCast(GV, SBP),
411 llvm::ConstantExpr::getBitCast(annoGV, SBP),
412 llvm::ConstantExpr::getBitCast(unitGV, SBP),
413 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
414 };
415 return llvm::ConstantStruct::get(Fields, 4, false);
416}
417
Daniel Dunbar73241df2009-02-13 21:18:01 +0000418bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000419 // Never defer when EmitAllDecls is specified or the decl has
420 // attribute used.
421 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000422 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000423
424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000425 // Constructors and destructors should never be deferred.
426 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
427 return false;
428
Chris Lattner99b53612009-03-21 08:03:33 +0000429 // FIXME: What about inline, and/or extern inline?
Daniel Dunbar73241df2009-02-13 21:18:01 +0000430 if (FD->getStorageClass() != FunctionDecl::Static)
431 return false;
432 } else {
433 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner99b53612009-03-21 08:03:33 +0000434 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbar73241df2009-02-13 21:18:01 +0000435
436 if (VD->getStorageClass() != VarDecl::Static)
437 return false;
438 }
439
440 return true;
441}
442
443void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattnerbd532712009-03-22 21:47:11 +0000444 // If this is an alias definition (which otherwise looks like a declaration)
445 // emit it now.
446 if (Global->getAttr<AliasAttr>())
447 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000448
Chris Lattner67b00522009-03-21 09:44:56 +0000449 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000450 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000451 // Forward declarations are emitted lazily on first use.
452 if (!FD->isThisDeclarationADefinition())
453 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000454 } else {
455 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000456 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
457
Daniel Dunbar73241df2009-02-13 21:18:01 +0000458 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000459 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000460 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000461 }
462
Chris Lattner67b00522009-03-21 09:44:56 +0000463 // Defer code generation when possible if this is a static definition, inline
464 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000465 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000466 // If the value has already been used, add it directly to the
467 // DeferredDeclsToEmit list.
468 const char *MangledName = getMangledName(Global);
469 if (GlobalDeclMap.count(MangledName))
470 DeferredDeclsToEmit.push_back(Global);
471 else {
472 // Otherwise, remember that we saw a deferred decl with this name. The
473 // first use of the mangled name will cause it to move into
474 // DeferredDeclsToEmit.
475 DeferredDecls[MangledName] = Global;
476 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000477 return;
478 }
479
480 // Otherwise emit the definition.
481 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000482}
483
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000484void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
485 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
486 EmitGlobalFunctionDefinition(FD);
487 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
488 EmitGlobalVarDefinition(VD);
489 } else {
490 assert(0 && "Invalid argument to EmitGlobalDefinition()");
491 }
492}
493
Chris Lattner74391b42009-03-22 21:03:39 +0000494/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
495/// module, create and return an llvm Function with the specified type. If there
496/// is something in the module with the specified name, return it potentially
497/// bitcasted to the right type.
498///
499/// If D is non-null, it specifies a decl that correspond to this. This is used
500/// to set the attributes on the function when it is first created.
501llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
502 const llvm::Type *Ty,
503 const FunctionDecl *D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000504 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000505 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
506 if (Entry) {
507 if (Entry->getType()->getElementType() == Ty)
508 return Entry;
509
510 // Make sure the result is of the correct type.
511 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
512 return llvm::ConstantExpr::getBitCast(Entry, PTy);
513 }
514
Chris Lattner67b00522009-03-21 09:44:56 +0000515 // This is the first use or definition of a mangled name. If there is a
516 // deferred decl with this name, remember that we need to emit it at the end
517 // of the file.
518 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattner74391b42009-03-22 21:03:39 +0000519 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000520 if (DDI != DeferredDecls.end()) {
521 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
522 // list, and remove it from DeferredDecls (since we don't need it anymore).
523 DeferredDeclsToEmit.push_back(DDI->second);
524 DeferredDecls.erase(DDI);
525 }
526
Chris Lattner0558e792009-03-21 09:25:43 +0000527 // This function doesn't have a complete type (for example, the return
528 // type is an incomplete struct). Use a fake type instead, and make
529 // sure not to try to set attributes.
530 bool ShouldSetAttributes = true;
531 if (!isa<llvm::FunctionType>(Ty)) {
532 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
533 std::vector<const llvm::Type*>(), false);
534 ShouldSetAttributes = false;
535 }
536 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
537 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000538 "", &getModule());
539 F->setName(MangledName);
Chris Lattner74391b42009-03-22 21:03:39 +0000540 if (D && ShouldSetAttributes)
Chris Lattner0558e792009-03-21 09:25:43 +0000541 SetFunctionAttributes(D, F);
542 Entry = F;
543 return F;
544}
545
Chris Lattner74391b42009-03-22 21:03:39 +0000546/// GetAddrOfFunction - Return the address of the given function. If Ty is
547/// non-null, then this function will use the specified type if it has to
548/// create it (this occurs when we see a definition of the function).
549llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
550 const llvm::Type *Ty) {
551 // If there was no specific requested type, just convert it now.
552 if (!Ty)
553 Ty = getTypes().ConvertType(D->getType());
554 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
555}
Eli Friedman77ba7082008-05-30 19:50:47 +0000556
Chris Lattner74391b42009-03-22 21:03:39 +0000557/// CreateRuntimeFunction - Create a new runtime function with the specified
558/// type and name.
559llvm::Constant *
560CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
561 const char *Name) {
562 // Convert Name to be a uniqued string from the IdentifierInfo table.
563 Name = getContext().Idents.get(Name).getName();
564 return GetOrCreateLLVMFunction(Name, FTy, 0);
565}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000566
Chris Lattner74391b42009-03-22 21:03:39 +0000567/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
568/// create and return an llvm GlobalVariable with the specified type. If there
569/// is something in the module with the specified name, return it potentially
570/// bitcasted to the right type.
571///
572/// If D is non-null, it specifies a decl that correspond to this. This is used
573/// to set the attributes on the global when it is first created.
574llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
575 const llvm::PointerType*Ty,
576 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000577 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000578 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000579 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000580 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000581 return Entry;
582
Chris Lattner99b53612009-03-21 08:03:33 +0000583 // Make sure the result is of the correct type.
Chris Lattner74391b42009-03-22 21:03:39 +0000584 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000585 }
Chris Lattner67b00522009-03-21 09:44:56 +0000586
587 // This is the first use or definition of a mangled name. If there is a
588 // deferred decl with this name, remember that we need to emit it at the end
589 // of the file.
590 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
591 DeferredDecls.find(MangledName);
592 if (DDI != DeferredDecls.end()) {
593 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
594 // list, and remove it from DeferredDecls (since we don't need it anymore).
595 DeferredDeclsToEmit.push_back(DDI->second);
596 DeferredDecls.erase(DDI);
597 }
598
Chris Lattner99b53612009-03-21 08:03:33 +0000599 llvm::GlobalVariable *GV =
Chris Lattner74391b42009-03-22 21:03:39 +0000600 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000601 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000602 0, "", &getModule(),
Chris Lattner74391b42009-03-22 21:03:39 +0000603 0, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000604 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000605
606 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000607 if (D) {
608 // FIXME: This code is overly simple and should be merged with
609 // other global handling.
610 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000611
Chris Lattner74391b42009-03-22 21:03:39 +0000612 // FIXME: Merge with other attribute handling code.
613 if (D->getStorageClass() == VarDecl::PrivateExtern)
614 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000615
Chris Lattner74391b42009-03-22 21:03:39 +0000616 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
617 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
618 }
619
Chris Lattner99b53612009-03-21 08:03:33 +0000620 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000621}
622
Chris Lattner74391b42009-03-22 21:03:39 +0000623
624/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
625/// given global variable. If Ty is non-null and if the global doesn't exist,
626/// then it will be greated with the specified type instead of whatever the
627/// normal requested type would be.
628llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
629 const llvm::Type *Ty) {
630 assert(D->hasGlobalStorage() && "Not a global variable");
631 QualType ASTTy = D->getType();
632 if (Ty == 0)
633 Ty = getTypes().ConvertTypeForMem(ASTTy);
634
635 const llvm::PointerType *PTy =
636 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
637 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
638}
639
640/// CreateRuntimeVariable - Create a new runtime global variable with the
641/// specified type and name.
642llvm::Constant *
643CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
644 const char *Name) {
645 // Convert Name to be a uniqued string from the IdentifierInfo table.
646 Name = getContext().Idents.get(Name).getName();
647 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
648}
649
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000650void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000651 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000652 QualType ASTTy = D->getType();
Eli Friedman77ba7082008-05-30 19:50:47 +0000653
Chris Lattner8f32f712007-07-14 00:23:28 +0000654 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000655 // This is a tentative definition; tentative definitions are
656 // implicitly initialized with { 0 }
Chris Lattner570585c2009-03-21 09:16:30 +0000657 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000658 if (ASTTy->isIncompleteArrayType()) {
659 // An incomplete array is normally [ TYPE x 0 ], but we need
660 // to fix it to [ TYPE x 1 ].
Chris Lattner570585c2009-03-21 09:16:30 +0000661 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000662 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000663 }
664 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000665 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000666 Init = EmitConstantExpr(D->getInit());
Eli Friedman6e656f42009-02-20 01:18:21 +0000667 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000668 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000669 QualType T = D->getInit()->getType();
670 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
671 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000672 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000673
Chris Lattner2d584062009-03-21 08:13:05 +0000674 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000675 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000676
Chris Lattner570585c2009-03-21 09:16:30 +0000677 // Strip off a bitcast if we got one back.
678 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
679 assert(CE->getOpcode() == llvm::Instruction::BitCast);
680 Entry = CE->getOperand(0);
681 }
682
683 // Entry is now either a Function or GlobalVariable.
684 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
685
686 // If we already have this global and it has an initializer, then
687 // we are in the rare situation where we emitted the defining
688 // declaration of the global and are now being asked to emit a
689 // definition which would be common. This occurs, for example, in
690 // the following situation because statics can be emitted out of
691 // order:
692 //
693 // static int x;
694 // static int *y = &x;
695 // static int x = 10;
696 // int **z = &y;
697 //
698 // Bail here so we don't blow away the definition. Note that if we
699 // can't distinguish here if we emitted a definition with a null
700 // initializer, but this case is safe.
701 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000702 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
703 return;
Chris Lattner570585c2009-03-21 09:16:30 +0000704 }
705
706 // We have a definition after a declaration with the wrong type.
707 // We must make a new GlobalVariable* and update everything that used OldGV
708 // (a declaration or tentative definition) with the new GlobalVariable*
709 // (which will be a definition).
710 //
711 // This happens if there is a prototype for a global (e.g.
712 // "extern int x[];") and then a definition of a different type (e.g.
713 // "int x[10];"). This also happens when an initializer has a different type
714 // from the type of the global (this happens with unions).
715 //
716 // FIXME: This also ends up happening if there's a definition followed by
717 // a tentative definition! (Although Sema rejects that construct
718 // at the moment.)
719 if (GV == 0 ||
720 GV->getType()->getElementType() != InitType ||
721 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
722
723 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
724 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000725
Chris Lattner570585c2009-03-21 09:16:30 +0000726 // Make a new global with the correct type, this is now guaranteed to work.
727 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000728 GV->takeName(cast<llvm::GlobalValue>(Entry));
729
Eli Friedman77ba7082008-05-30 19:50:47 +0000730 // Replace all uses of the old global with the new global
731 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000732 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
733 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000734
735 // Erase the old global, since it is no longer used.
Chris Lattner2d584062009-03-21 08:13:05 +0000736 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattner570585c2009-03-21 09:16:30 +0000737 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000738 }
Devang Patel8e53e722007-10-26 16:31:40 +0000739
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000740 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
741 SourceManager &SM = Context.getSourceManager();
742 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000743 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000744 }
745
Chris Lattner88a69ad2007-07-13 05:13:43 +0000746 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000747 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000748 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000749
Chris Lattnerddee4232008-03-03 03:28:21 +0000750 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000751 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000752 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000753
Chris Lattner88a69ad2007-07-13 05:13:43 +0000754 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000755 if (D->getStorageClass() == VarDecl::Static)
756 GV->setLinkage(llvm::Function::InternalLinkage);
757 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000758 GV->setLinkage(llvm::Function::DLLImportLinkage);
759 else if (D->getAttr<DLLExportAttr>())
760 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000761 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000762 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000763 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000764 // FIXME: This isn't right. This should handle common linkage and other
765 // stuff.
766 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000767 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000768 case VarDecl::Auto:
769 case VarDecl::Register:
770 assert(0 && "Can't have auto or register globals");
771 case VarDecl::None:
Chris Lattnerbd360642009-03-26 05:00:52 +0000772 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sandsceb77d92009-03-11 20:15:27 +0000773 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000774 else
775 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000776 break;
777 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000778 // FIXME: common
779 break;
780
Chris Lattnerddee4232008-03-03 03:28:21 +0000781 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000782 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
783 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000784 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000785 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000786 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000787
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000788 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
789 GV->setSection(SA->getName());
790
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000791 if (D->getAttr<UsedAttr>())
792 AddUsedGlobal(GV);
793
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000794 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000795 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000796 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000797 DI->EmitGlobalVariable(GV, D);
798 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000799}
Reid Spencer5f016e22007-07-11 17:01:13 +0000800
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000801
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000802void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000803 const llvm::FunctionType *Ty =
804 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
805
806 // As a special case, make sure that definitions of K&R function
807 // "type foo()" aren't declared as varargs (which forces the backend
808 // to do unnecessary work).
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000809 if (D->getType()->isFunctionNoProtoType()) {
810 assert(Ty->isVarArg() && "Didn't lower type as expected");
811 // Due to stret, the lowered function could have arguments. Just create the
812 // same type as was lowered by ConvertType but strip off the varargs bit.
813 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
814 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
815 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000816
Chris Lattner34809502009-03-21 08:53:37 +0000817 // Get or create the prototype for teh function.
Chris Lattner0558e792009-03-21 09:25:43 +0000818 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000819
Chris Lattner0558e792009-03-21 09:25:43 +0000820 // Strip off a bitcast if we got one back.
821 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
822 assert(CE->getOpcode() == llvm::Instruction::BitCast);
823 Entry = CE->getOperand(0);
824 }
825
826
827 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +0000828 // If the types mismatch then we have to rewrite the definition.
Chris Lattner0558e792009-03-21 09:25:43 +0000829 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
830 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000831
Chris Lattner62b33ea2009-03-21 08:38:50 +0000832 // F is the Function* for the one with the wrong type, we must make a new
833 // Function* and update everything that used F (a declaration) with the new
834 // Function* (which will be a definition).
835 //
836 // This happens if there is a prototype for a function
837 // (e.g. "int f()") and then a definition of a different type
838 // (e.g. "int f(int x)"). Start by making a new function of the
839 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +0000840 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner0558e792009-03-21 09:25:43 +0000841 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
842 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattner62b33ea2009-03-21 08:38:50 +0000843
844 // Replace uses of F with the Function we will endow with a body.
845 llvm::Constant *NewPtrForOldDecl =
Chris Lattner0558e792009-03-21 09:25:43 +0000846 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
847 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner62b33ea2009-03-21 08:38:50 +0000848
849 // Ok, delete the old function now, which is dead.
Chris Lattner34809502009-03-21 08:53:37 +0000850 // FIXME: If it was attribute(used) the pointer will dangle from the
851 // LLVMUsed array!
Chris Lattner0558e792009-03-21 09:25:43 +0000852 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +0000853
Chris Lattner0558e792009-03-21 09:25:43 +0000854 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000855 }
Chris Lattner0558e792009-03-21 09:25:43 +0000856
857 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000858
Daniel Dunbar219df662008-09-08 23:44:31 +0000859 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000860
Daniel Dunbar219df662008-09-08 23:44:31 +0000861 SetFunctionAttributesForDefinition(D, Fn);
862
Chris Lattner34809502009-03-21 08:53:37 +0000863 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000864 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattner34809502009-03-21 08:53:37 +0000865 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000866 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000867}
868
Chris Lattnerbd532712009-03-22 21:47:11 +0000869void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
870 const AliasAttr *AA = D->getAttr<AliasAttr>();
871 assert(AA && "Not an alias?");
872
873 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
874
875 // Unique the name through the identifier table.
876 const char *AliaseeName = AA->getAliasee().c_str();
877 AliaseeName = getContext().Idents.get(AliaseeName).getName();
878
879 // Create a reference to the named value. This ensures that it is emitted
880 // if a deferred decl.
881 llvm::Constant *Aliasee;
882 if (isa<llvm::FunctionType>(DeclTy))
883 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
884 else
885 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
886 llvm::PointerType::getUnqual(DeclTy), 0);
887
888 // Create the new alias itself, but don't set a name yet.
889 llvm::GlobalValue *GA =
890 new llvm::GlobalAlias(Aliasee->getType(),
891 llvm::Function::ExternalLinkage,
892 "", Aliasee, &getModule());
893
894 // See if there is already something with the alias' name in the module.
895 const char *MangledName = getMangledName(D);
896 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
897
898 if (Entry && !Entry->isDeclaration()) {
899 // If there is a definition in the module, then it wins over the alias.
900 // This is dubious, but allow it to be safe. Just ignore the alias.
901 GA->eraseFromParent();
902 return;
903 }
904
905 if (Entry) {
906 // If there is a declaration in the module, then we had an extern followed
907 // by the alias, as in:
908 // extern int test6();
909 // ...
910 // int test6() __attribute__((alias("test7")));
911 //
912 // Remove it and replace uses of it with the alias.
913
914 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
915 Entry->getType()));
916 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
917 Entry->eraseFromParent();
918 }
919
920 // Now we know that there is no conflict, set the name.
921 Entry = GA;
922 GA->setName(MangledName);
923
924 // Alias should never be internal or inline.
925 SetGlobalValueAttributes(D, false, false, GA, true);
926}
927
Chris Lattnerc5b88062008-02-06 05:08:19 +0000928void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
929 // Make sure that this type is translated.
930 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000931}
932
933
Chris Lattnerb808c952009-03-22 21:56:56 +0000934/// getBuiltinLibFunction - Given a builtin id for a function like
935/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +0000936llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +0000937 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
938 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
939 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000940
Douglas Gregor3e41d602009-02-13 23:20:09 +0000941 // Get the name, skip over the __builtin_ prefix (if necessary).
942 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
943 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
944 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000945
946 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000947 Builtin::Context::GetBuiltinTypeError Error;
948 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
949 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
950
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000951 const llvm::FunctionType *Ty =
952 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
953
Chris Lattnerb808c952009-03-22 21:56:56 +0000954 // Unique the name through the identifier table.
955 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000956 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb808c952009-03-22 21:56:56 +0000957 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000958}
959
Chris Lattner7acda7c2007-12-18 00:25:38 +0000960llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
961 unsigned NumTys) {
962 return llvm::Intrinsic::getDeclaration(&getModule(),
963 (llvm::Intrinsic::ID)IID, Tys, NumTys);
964}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966llvm::Function *CodeGenModule::getMemCpyFn() {
967 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000968 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
969 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000970}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000971
Eli Friedman0c995092008-05-26 12:59:39 +0000972llvm::Function *CodeGenModule::getMemMoveFn() {
973 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000974 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
975 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000976}
977
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000978llvm::Function *CodeGenModule::getMemSetFn() {
979 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000980 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
981 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000982}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000983
Anders Carlssone3daa762008-11-15 18:54:24 +0000984static void appendFieldAndPadding(CodeGenModule &CGM,
985 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000986 FieldDecl *FieldD, FieldDecl *NextFieldD,
987 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +0000988 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000989 // Append the field.
990 Fields.push_back(Field);
991
Douglas Gregor44b43212008-12-11 16:49:14 +0000992 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000993
994 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000995 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000996 NextStructFieldNo = STy->getNumElements();
997 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000998 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000999 }
1000
1001 // Append padding
1002 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1003 llvm::Constant *C =
1004 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1005
1006 Fields.push_back(C);
1007 }
1008}
1009
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001010// We still need to work out the details of handling UTF-16.
1011// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001012llvm::Constant *CodeGenModule::
1013GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +00001014 llvm::StringMapEntry<llvm::Constant *> &Entry =
1015 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1016
1017 if (Entry.getValue())
1018 return Entry.getValue();
1019
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001020 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1021 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001022
1023 if (!CFConstantStringClassRef) {
1024 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1025 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001026
1027 // FIXME: This is fairly broken if
1028 // __CFConstantStringClassReference is already defined, in that it
1029 // will get renamed and the user will most likely see an opaque
1030 // error message. This is a general issue with relying on
1031 // particular names.
1032 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001033 new llvm::GlobalVariable(Ty, false,
1034 llvm::GlobalVariable::ExternalLinkage, 0,
1035 "__CFConstantStringClassReference",
1036 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001037
1038 // Decay array -> ptr
1039 CFConstantStringClassRef =
1040 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001041 }
1042
Anders Carlssone3daa762008-11-15 18:54:24 +00001043 QualType CFTy = getContext().getCFConstantStringType();
1044 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001045
Anders Carlssone3daa762008-11-15 18:54:24 +00001046 const llvm::StructType *STy =
1047 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1048
1049 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +00001050 RecordDecl::field_iterator Field = CFRD->field_begin();
1051
Anders Carlssonc9e20912007-08-21 00:21:21 +00001052 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001053 FieldDecl *CurField = *Field++;
1054 FieldDecl *NextField = *Field++;
1055 appendFieldAndPadding(*this, Fields, CurField, NextField,
1056 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001057
1058 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001059 CurField = NextField;
1060 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001061 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001062 appendFieldAndPadding(*this, Fields, CurField, NextField,
1063 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001064
1065 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001066 CurField = NextField;
1067 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001068 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001069 C = new llvm::GlobalVariable(C->getType(), true,
1070 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +00001071 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +00001072 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +00001073 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1074 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001075
1076 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001077 CurField = NextField;
1078 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001079 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001080 appendFieldAndPadding(*this, Fields, CurField, NextField,
1081 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001082
1083 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001084 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +00001085 llvm::GlobalVariable *GV =
1086 new llvm::GlobalVariable(C->getType(), true,
1087 llvm::GlobalVariable::InternalLinkage,
1088 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001089
Anders Carlsson0c678292007-11-01 00:41:52 +00001090 GV->setSection("__DATA,__cfstring");
1091 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001092
Anders Carlsson0c678292007-11-01 00:41:52 +00001093 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001094}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001095
Daniel Dunbar61432932008-08-13 23:20:05 +00001096/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001097/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001098std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001099 const char *StrData = E->getStrData();
1100 unsigned Len = E->getByteLength();
1101
1102 const ConstantArrayType *CAT =
1103 getContext().getAsConstantArrayType(E->getType());
1104 assert(CAT && "String isn't pointer or array!");
1105
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001106 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001107 std::string Str(StrData, StrData+Len);
1108 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001109
1110 if (E->isWide())
1111 RealLen *= getContext().Target.getWCharWidth()/8;
1112
Daniel Dunbar1e049762008-08-10 20:25:57 +00001113 Str.resize(RealLen, '\0');
1114
1115 return Str;
1116}
1117
Daniel Dunbar61432932008-08-13 23:20:05 +00001118/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1119/// constant array for the given string literal.
1120llvm::Constant *
1121CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1122 // FIXME: This can be more efficient.
1123 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1124}
1125
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001126/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1127/// array for the given ObjCEncodeExpr node.
1128llvm::Constant *
1129CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1130 std::string Str;
1131 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001132
1133 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001134}
1135
1136
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001137/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001138static llvm::Constant *GenerateStringLiteral(const std::string &str,
1139 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001140 CodeGenModule &CGM,
1141 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001142 // Create Constant for this string literal. Don't add a '\0'.
1143 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001144
1145 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001146 return new llvm::GlobalVariable(C->getType(), constant,
1147 llvm::GlobalValue::InternalLinkage,
1148 C, GlobalName ? GlobalName : ".str",
1149 &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001150}
1151
Daniel Dunbar61432932008-08-13 23:20:05 +00001152/// GetAddrOfConstantString - Returns a pointer to a character array
1153/// containing the literal. This contents are exactly that of the
1154/// given string, i.e. it will not be null terminated automatically;
1155/// see GetAddrOfConstantCString. Note that whether the result is
1156/// actually a pointer to an LLVM constant depends on
1157/// Feature.WriteableStrings.
1158///
1159/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001160llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1161 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001162 // Don't share any string literals if writable-strings is turned on.
1163 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001164 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001165
1166 llvm::StringMapEntry<llvm::Constant *> &Entry =
1167 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1168
1169 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001170 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001171
1172 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001173 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001174 Entry.setValue(C);
1175 return C;
1176}
Daniel Dunbar61432932008-08-13 23:20:05 +00001177
1178/// GetAddrOfConstantCString - Returns a pointer to a character
1179/// array containing the literal and a terminating '\-'
1180/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001181llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1182 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001183 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001184}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001185
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001186/// EmitObjCPropertyImplementations - Emit information for synthesized
1187/// properties for an implementation.
1188void CodeGenModule::EmitObjCPropertyImplementations(const
1189 ObjCImplementationDecl *D) {
1190 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1191 e = D->propimpl_end(); i != e; ++i) {
1192 ObjCPropertyImplDecl *PID = *i;
1193
1194 // Dynamic is just for type-checking.
1195 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1196 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1197
1198 // Determine which methods need to be implemented, some may have
1199 // been overridden. Note that ::isSynthesized is not the method
1200 // we want, that just indicates if the decl came from a
1201 // property. What we want to know is if the method is defined in
1202 // this implementation.
1203 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001204 CodeGenFunction(*this).GenerateObjCGetter(
1205 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001206 if (!PD->isReadOnly() &&
1207 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001208 CodeGenFunction(*this).GenerateObjCSetter(
1209 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001210 }
1211 }
1212}
1213
Daniel Dunbar41071de2008-08-15 23:26:23 +00001214/// EmitTopLevelDecl - Emit code for a single top level declaration.
1215void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1216 // If an error has occurred, stop code generation, but continue
1217 // parsing and semantic analysis (to ensure all warnings and errors
1218 // are emitted).
1219 if (Diags.hasErrorOccurred())
1220 return;
1221
1222 switch (D->getKind()) {
1223 case Decl::Function:
1224 case Decl::Var:
1225 EmitGlobal(cast<ValueDecl>(D));
1226 break;
1227
1228 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001229 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001230 break;
1231
1232 // Objective-C Decls
1233
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001234 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001235 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001236 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001237 case Decl::ObjCCategory:
1238 case Decl::ObjCInterface:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001239 break;
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001240
Daniel Dunbar41071de2008-08-15 23:26:23 +00001241 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001242 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001243 break;
1244
1245 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001246 // Categories have properties but don't support synthesize so we
1247 // can ignore them here.
1248
Daniel Dunbar41071de2008-08-15 23:26:23 +00001249 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1250 break;
1251
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001252 case Decl::ObjCImplementation: {
1253 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1254 EmitObjCPropertyImplementations(OMD);
1255 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001256 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001257 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001258 case Decl::ObjCMethod: {
1259 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1260 // If this is not a prototype, emit the body.
1261 if (OMD->getBody())
1262 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1263 break;
1264 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001265 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001266 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001267 break;
1268
1269 case Decl::LinkageSpec: {
1270 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1271 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001272 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001273 // FIXME: implement C++ linkage, C linkage works mostly by C
1274 // language reuse already.
1275 break;
1276 }
1277
1278 case Decl::FileScopeAsm: {
1279 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1280 std::string AsmString(AD->getAsmString()->getStrData(),
1281 AD->getAsmString()->getByteLength());
1282
1283 const std::string &S = getModule().getModuleInlineAsm();
1284 if (S.empty())
1285 getModule().setModuleInlineAsm(AsmString);
1286 else
1287 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1288 break;
1289 }
1290
1291 default:
1292 // Make sure we handled everything we should, every other kind is
1293 // a non-top-level decl. FIXME: Would be nice to have an
1294 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1295 // that easily.
1296 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1297 }
1298}