blob: 0759abdd33f07d45bdf2de97eb4a50502a859da7 [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
14#include "CodeGenModule.h"
Chris Lattnerf04a7562009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#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 Lattnerf04a7562009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000027#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000028#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000030#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerf04a7562009-03-26 05:00:52 +000035CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerf04a7562009-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 Stump1f010b52009-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 Dunbarfc69bde2008-08-11 18:12:00 +000042
Chris Lattner08b05eb2009-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 Gupta40e56a12008-05-08 08:54:20 +000051
52 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerf04a7562009-03-26 05:00:52 +000053 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000054}
55
56CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000057 delete Runtime;
58 delete DebugInfo;
59}
60
61void CodeGenModule::Release() {
Chris Lattner13137542009-03-22 21:21:57 +000062 EmitDeferred();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000063 if (Runtime)
64 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
65 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000066 EmitCtorList(GlobalCtors, "llvm.global_ctors");
67 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000068 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000069 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000070}
71
Daniel Dunbar9503b782008-08-16 00:56:44 +000072/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000073/// specified stmt yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +000078 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000079 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +000080 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000081 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
82 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +000083}
Chris Lattner0e4755d2007-12-02 06:27:33 +000084
Daniel Dunbar9503b782008-08-16 00:56:44 +000085/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000086/// specified decl yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +000091 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000092 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +000093 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000094 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +000095}
96
Daniel Dunbar27250d32008-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 Gohman4751a3a2008-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 Gregor3556bc72009-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 Lattnerdaa199c2009-03-21 06:31:09 +0000118/// const char* containing the mangled name. Otherwise, returns
119/// the unmangled name.
Douglas Gregor3556bc72009-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 Dunbar7b7f4f42009-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 Gregor3556bc72009-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 Gregor3c3c4542009-02-18 23:53:56 +0000132const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-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 Lattner08b05eb2009-03-21 07:12:05 +0000136 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000137 }
138
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000139 llvm::SmallString<256> Name;
140 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000141 if (!mangleName(ND, Context, Out)) {
142 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000143 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000144 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000145
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000146 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000147 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000148}
149
Chris Lattner753d2592008-03-14 17:18:18 +0000150/// AddGlobalCtor - Add a function to the list that will be called before
151/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000153 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000154 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000155}
156
Daniel Dunbardd2e9ca2008-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 Dunbar3a80fc02009-01-13 02:25:00 +0000160 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-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 Lattnera18c12e2008-03-19 05:24:56 +0000173 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000174 llvm::StructType::get(llvm::Type::Int32Ty,
175 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000176
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000184 }
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000194}
195
Nate Begeman52da5c72008-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 Dunbar375da3f2009-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 Dunbar3a80fc02009-01-13 02:25:00 +0000217 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000218 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000219 if (!ForDefinition) {
220 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000221 if (D->getAttr<DLLImportAttr>()) {
222 // The dllimport attribute is overridden by a subsequent declaration as
223 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000224 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-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 Redle299eb42009-01-05 20:53:53 +0000232 }
Daniel Dunbar80f5f992009-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 Sands9aa5c262009-03-11 08:40:02 +0000237 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000238 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000239 } else {
240 if (IsInternal) {
241 GV->setLinkage(llvm::Function::InternalLinkage);
242 } else {
Anton Korobeynikovb27a8702008-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 Dunbar80f5f992009-03-06 16:20:49 +0000250 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
251 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000252 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000253 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000254 }
Nuno Lopes78534382008-06-08 15:45:52 +0000255
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000256 // FIXME: Figure out the relative priority of the attribute,
257 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000258 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000259 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000260 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000261
Daniel Dunbar97509722009-02-12 17:28:23 +0000262 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
263 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-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 Lopes78534382008-06-08 15:45:52 +0000272}
273
Devang Patela85a9ef2008-09-25 21:02:23 +0000274void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000275 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000276 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000277 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000278 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000279
Devang Patela85a9ef2008-09-25 21:02:23 +0000280 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
281 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000282
283 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000284 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-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);
Fariborz Jahanian97703432009-03-27 18:38:55 +0000289
290 if (D->getAttr<RegparmAttr>())
291 ErrorUnsupported(D, "regparm attribute");
Daniel Dunbarf2787002008-09-04 23:41:35 +0000292}
293
294/// SetFunctionAttributesForDefinition - Set function attributes
295/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000296void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
297 llvm::Function *F) {
298 if (isa<ObjCMethodDecl>(D)) {
299 SetGlobalValueAttributes(D, true, false, F, true);
300 } else {
301 const FunctionDecl *FD = cast<FunctionDecl>(D);
302 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
303 FD->isInline(), F, true);
304 }
305
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000306 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000307 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000308
309 if (D->getAttr<AlwaysInlineAttr>())
310 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000311
312 if (D->getAttr<NoinlineAttr>())
313 F->addFnAttr(llvm::Attribute::NoInline);
Fariborz Jahanian97703432009-03-27 18:38:55 +0000314
315 if (D->getAttr<RegparmAttr>())
316 ErrorUnsupported(D, "regparm attribute");
Daniel Dunbarf2787002008-09-04 23:41:35 +0000317}
318
319void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
320 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000321 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000322
Daniel Dunbar566a6502008-09-08 23:44:31 +0000323 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000324}
325
326void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
327 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000328 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000329
Daniel Dunbar566a6502008-09-08 23:44:31 +0000330 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
331 FD->isInline(), F, false);
332}
333
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000334void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
335 assert(!GV->isDeclaration() &&
336 "Only globals with definition can force usage.");
337 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
338 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
339}
340
341void CodeGenModule::EmitLLVMUsed() {
342 // Don't create llvm.used if there is no need.
343 if (LLVMUsed.empty())
344 return;
345
346 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
347 LLVMUsed.size());
348 llvm::GlobalVariable *GV =
349 new llvm::GlobalVariable(ATy, false,
350 llvm::GlobalValue::AppendingLinkage,
351 llvm::ConstantArray::get(ATy, LLVMUsed),
352 "llvm.used", &getModule());
353
354 GV->setSection("llvm.metadata");
355}
356
357void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000358 // Emit code for any potentially referenced deferred decls. Since a
359 // previously unused static decl may become used during the generation of code
360 // for a static function, iterate until no changes are made.
361 while (!DeferredDeclsToEmit.empty()) {
362 const ValueDecl *D = DeferredDeclsToEmit.back();
363 DeferredDeclsToEmit.pop_back();
364
365 // The mangled name for the decl must have been emitted in GlobalDeclMap.
366 // Look it up to see if it was defined with a stronger definition (e.g. an
367 // extern inline function with a strong function redefinition). If so,
368 // just ignore the deferred decl.
369 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
370 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000371
Chris Lattner38837f92009-03-21 09:44:56 +0000372 if (!CGRef->isDeclaration())
373 continue;
374
375 // Otherwise, emit the definition and move on to the next one.
376 EmitGlobalDefinition(D);
377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378}
379
Nate Begeman8a704172008-04-19 04:17:09 +0000380/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
381/// annotation information for a given GlobalValue. The annotation struct is
382/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000383/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000384/// created from the AnnotateAttr's annotation. The third field is a constant
385/// string containing the name of the translation unit. The fourth field is
386/// the line number in the file of the annotated value declaration.
387///
388/// FIXME: this does not unique the annotation string constants, as llvm-gcc
389/// appears to.
390///
391llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
392 const AnnotateAttr *AA,
393 unsigned LineNo) {
394 llvm::Module *M = &getModule();
395
396 // get [N x i8] constants for the annotation string, and the filename string
397 // which are the 2nd and 3rd elements of the global annotation structure.
398 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
399 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
400 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
401 true);
402
403 // Get the two global values corresponding to the ConstantArrays we just
404 // created to hold the bytes of the strings.
405 llvm::GlobalValue *annoGV =
406 new llvm::GlobalVariable(anno->getType(), false,
407 llvm::GlobalValue::InternalLinkage, anno,
408 GV->getName() + ".str", M);
409 // translation unit name string, emitted into the llvm.metadata section.
410 llvm::GlobalValue *unitGV =
411 new llvm::GlobalVariable(unit->getType(), false,
412 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
413
414 // Create the ConstantStruct that is the global annotion.
415 llvm::Constant *Fields[4] = {
416 llvm::ConstantExpr::getBitCast(GV, SBP),
417 llvm::ConstantExpr::getBitCast(annoGV, SBP),
418 llvm::ConstantExpr::getBitCast(unitGV, SBP),
419 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
420 };
421 return llvm::ConstantStruct::get(Fields, 4, false);
422}
423
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000424bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000425 // Never defer when EmitAllDecls is specified or the decl has
426 // attribute used.
427 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000428 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000429
430 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000431 // Constructors and destructors should never be deferred.
432 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
433 return false;
434
Chris Lattner7e5888f2009-03-21 08:03:33 +0000435 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000436 if (FD->getStorageClass() != FunctionDecl::Static)
437 return false;
438 } else {
439 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000440 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000441
442 if (VD->getStorageClass() != VarDecl::Static)
443 return false;
444 }
445
446 return true;
447}
448
449void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000450 // If this is an alias definition (which otherwise looks like a declaration)
451 // emit it now.
452 if (Global->getAttr<AliasAttr>())
453 return EmitAliasDefinition(Global);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000454
Chris Lattner38837f92009-03-21 09:44:56 +0000455 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000456 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000457 // Forward declarations are emitted lazily on first use.
458 if (!FD->isThisDeclarationADefinition())
459 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000460 } else {
461 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000462 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
463
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000464 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000465 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000466 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000467 }
468
Chris Lattner38837f92009-03-21 09:44:56 +0000469 // Defer code generation when possible if this is a static definition, inline
470 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000471 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000472 // If the value has already been used, add it directly to the
473 // DeferredDeclsToEmit list.
474 const char *MangledName = getMangledName(Global);
475 if (GlobalDeclMap.count(MangledName))
476 DeferredDeclsToEmit.push_back(Global);
477 else {
478 // Otherwise, remember that we saw a deferred decl with this name. The
479 // first use of the mangled name will cause it to move into
480 // DeferredDeclsToEmit.
481 DeferredDecls[MangledName] = Global;
482 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000483 return;
484 }
485
486 // Otherwise emit the definition.
487 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000488}
489
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000490void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
491 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
492 EmitGlobalFunctionDefinition(FD);
493 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
494 EmitGlobalVarDefinition(VD);
495 } else {
496 assert(0 && "Invalid argument to EmitGlobalDefinition()");
497 }
498}
499
Chris Lattneraea1aee2009-03-22 21:03:39 +0000500/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
501/// module, create and return an llvm Function with the specified type. If there
502/// is something in the module with the specified name, return it potentially
503/// bitcasted to the right type.
504///
505/// If D is non-null, it specifies a decl that correspond to this. This is used
506/// to set the attributes on the function when it is first created.
507llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
508 const llvm::Type *Ty,
509 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000510 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000511 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
512 if (Entry) {
513 if (Entry->getType()->getElementType() == Ty)
514 return Entry;
515
516 // Make sure the result is of the correct type.
517 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
518 return llvm::ConstantExpr::getBitCast(Entry, PTy);
519 }
520
Chris Lattner38837f92009-03-21 09:44:56 +0000521 // This is the first use or definition of a mangled name. If there is a
522 // deferred decl with this name, remember that we need to emit it at the end
523 // of the file.
524 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000525 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000526 if (DDI != DeferredDecls.end()) {
527 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
528 // list, and remove it from DeferredDecls (since we don't need it anymore).
529 DeferredDeclsToEmit.push_back(DDI->second);
530 DeferredDecls.erase(DDI);
531 }
532
Chris Lattner5dd030f2009-03-21 09:25:43 +0000533 // This function doesn't have a complete type (for example, the return
534 // type is an incomplete struct). Use a fake type instead, and make
535 // sure not to try to set attributes.
536 bool ShouldSetAttributes = true;
537 if (!isa<llvm::FunctionType>(Ty)) {
538 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
539 std::vector<const llvm::Type*>(), false);
540 ShouldSetAttributes = false;
541 }
542 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
543 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000544 "", &getModule());
545 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000546 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000547 SetFunctionAttributes(D, F);
548 Entry = F;
549 return F;
550}
551
Chris Lattneraea1aee2009-03-22 21:03:39 +0000552/// GetAddrOfFunction - Return the address of the given function. If Ty is
553/// non-null, then this function will use the specified type if it has to
554/// create it (this occurs when we see a definition of the function).
555llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
556 const llvm::Type *Ty) {
557 // If there was no specific requested type, just convert it now.
558 if (!Ty)
559 Ty = getTypes().ConvertType(D->getType());
560 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
561}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000562
Chris Lattneraea1aee2009-03-22 21:03:39 +0000563/// CreateRuntimeFunction - Create a new runtime function with the specified
564/// type and name.
565llvm::Constant *
566CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
567 const char *Name) {
568 // Convert Name to be a uniqued string from the IdentifierInfo table.
569 Name = getContext().Idents.get(Name).getName();
570 return GetOrCreateLLVMFunction(Name, FTy, 0);
571}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000572
Chris Lattneraea1aee2009-03-22 21:03:39 +0000573/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
574/// create and return an llvm GlobalVariable with the specified type. If there
575/// is something in the module with the specified name, return it potentially
576/// bitcasted to the right type.
577///
578/// If D is non-null, it specifies a decl that correspond to this. This is used
579/// to set the attributes on the global when it is first created.
580llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
581 const llvm::PointerType*Ty,
582 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000583 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000584 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000585 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000586 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000587 return Entry;
588
Chris Lattner7e5888f2009-03-21 08:03:33 +0000589 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000590 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000591 }
Chris Lattner38837f92009-03-21 09:44:56 +0000592
593 // This is the first use or definition of a mangled name. If there is a
594 // deferred decl with this name, remember that we need to emit it at the end
595 // of the file.
596 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
597 DeferredDecls.find(MangledName);
598 if (DDI != DeferredDecls.end()) {
599 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
600 // list, and remove it from DeferredDecls (since we don't need it anymore).
601 DeferredDeclsToEmit.push_back(DDI->second);
602 DeferredDecls.erase(DDI);
603 }
604
Chris Lattner7e5888f2009-03-21 08:03:33 +0000605 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000606 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000607 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000608 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000609 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000610 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000611
612 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000613 if (D) {
614 // FIXME: This code is overly simple and should be merged with
615 // other global handling.
616 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000617
Chris Lattneraea1aee2009-03-22 21:03:39 +0000618 // FIXME: Merge with other attribute handling code.
619 if (D->getStorageClass() == VarDecl::PrivateExtern)
620 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000621
Chris Lattneraea1aee2009-03-22 21:03:39 +0000622 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
623 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
624 }
625
Chris Lattner7e5888f2009-03-21 08:03:33 +0000626 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000627}
628
Chris Lattneraea1aee2009-03-22 21:03:39 +0000629
630/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
631/// given global variable. If Ty is non-null and if the global doesn't exist,
632/// then it will be greated with the specified type instead of whatever the
633/// normal requested type would be.
634llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
635 const llvm::Type *Ty) {
636 assert(D->hasGlobalStorage() && "Not a global variable");
637 QualType ASTTy = D->getType();
638 if (Ty == 0)
639 Ty = getTypes().ConvertTypeForMem(ASTTy);
640
641 const llvm::PointerType *PTy =
642 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
643 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
644}
645
646/// CreateRuntimeVariable - Create a new runtime global variable with the
647/// specified type and name.
648llvm::Constant *
649CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
650 const char *Name) {
651 // Convert Name to be a uniqued string from the IdentifierInfo table.
652 Name = getContext().Idents.get(Name).getName();
653 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
654}
655
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000656void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000657 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000658 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000659
Chris Lattner4b009652007-07-25 00:24:17 +0000660 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000661 // This is a tentative definition; tentative definitions are
662 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000663 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000664 if (ASTTy->isIncompleteArrayType()) {
665 // An incomplete array is normally [ TYPE x 0 ], but we need
666 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000667 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000668 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000669 }
670 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000671 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000672 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000673 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000674 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000675 QualType T = D->getInit()->getType();
676 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
677 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000678 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000679
Chris Lattner23afd5b2009-03-21 08:13:05 +0000680 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000681 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000682
Chris Lattnera6984932009-03-21 09:16:30 +0000683 // Strip off a bitcast if we got one back.
684 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
685 assert(CE->getOpcode() == llvm::Instruction::BitCast);
686 Entry = CE->getOperand(0);
687 }
688
689 // Entry is now either a Function or GlobalVariable.
690 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
691
692 // If we already have this global and it has an initializer, then
693 // we are in the rare situation where we emitted the defining
694 // declaration of the global and are now being asked to emit a
695 // definition which would be common. This occurs, for example, in
696 // the following situation because statics can be emitted out of
697 // order:
698 //
699 // static int x;
700 // static int *y = &x;
701 // static int x = 10;
702 // int **z = &y;
703 //
704 // Bail here so we don't blow away the definition. Note that if we
705 // can't distinguish here if we emitted a definition with a null
706 // initializer, but this case is safe.
707 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000708 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
709 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000710 }
711
712 // We have a definition after a declaration with the wrong type.
713 // We must make a new GlobalVariable* and update everything that used OldGV
714 // (a declaration or tentative definition) with the new GlobalVariable*
715 // (which will be a definition).
716 //
717 // This happens if there is a prototype for a global (e.g.
718 // "extern int x[];") and then a definition of a different type (e.g.
719 // "int x[10];"). This also happens when an initializer has a different type
720 // from the type of the global (this happens with unions).
721 //
722 // FIXME: This also ends up happening if there's a definition followed by
723 // a tentative definition! (Although Sema rejects that construct
724 // at the moment.)
725 if (GV == 0 ||
726 GV->getType()->getElementType() != InitType ||
727 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
728
729 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
730 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000731
Chris Lattnera6984932009-03-21 09:16:30 +0000732 // Make a new global with the correct type, this is now guaranteed to work.
733 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000734 GV->takeName(cast<llvm::GlobalValue>(Entry));
735
Eli Friedman43a0ce82008-05-30 19:50:47 +0000736 // Replace all uses of the old global with the new global
737 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000738 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
739 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000740
741 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000742 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattnera6984932009-03-21 09:16:30 +0000743 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000744 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000745
Nate Begeman8a704172008-04-19 04:17:09 +0000746 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
747 SourceManager &SM = Context.getSourceManager();
748 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000749 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000750 }
751
Chris Lattner4b009652007-07-25 00:24:17 +0000752 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000753 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000754 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000755
Chris Lattner402b3372008-03-03 03:28:21 +0000756 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000757 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000758 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000759
Chris Lattner4b009652007-07-25 00:24:17 +0000760 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000761 if (D->getStorageClass() == VarDecl::Static)
762 GV->setLinkage(llvm::Function::InternalLinkage);
763 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000764 GV->setLinkage(llvm::Function::DLLImportLinkage);
765 else if (D->getAttr<DLLExportAttr>())
766 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000767 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000768 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000769 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000770 // FIXME: This isn't right. This should handle common linkage and other
771 // stuff.
772 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000773 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000774 case VarDecl::Auto:
775 case VarDecl::Register:
776 assert(0 && "Can't have auto or register globals");
777 case VarDecl::None:
Chris Lattnerf04a7562009-03-26 05:00:52 +0000778 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sands78c33cc2009-03-11 20:15:27 +0000779 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000780 else
781 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000782 break;
783 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000784 // FIXME: common
785 break;
786
Chris Lattner402b3372008-03-03 03:28:21 +0000787 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000788 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
789 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000790 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000791 }
Chris Lattner4b009652007-07-25 00:24:17 +0000792 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000793
Daniel Dunbar97509722009-02-12 17:28:23 +0000794 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
795 GV->setSection(SA->getName());
796
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000797 if (D->getAttr<UsedAttr>())
798 AddUsedGlobal(GV);
799
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000800 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000801 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000802 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000803 DI->EmitGlobalVariable(GV, D);
804 }
Chris Lattner4b009652007-07-25 00:24:17 +0000805}
806
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000807
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000808void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000809 const llvm::FunctionType *Ty =
810 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
811
812 // As a special case, make sure that definitions of K&R function
813 // "type foo()" aren't declared as varargs (which forces the backend
814 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000815 if (D->getType()->isFunctionNoProtoType()) {
816 assert(Ty->isVarArg() && "Didn't lower type as expected");
817 // Due to stret, the lowered function could have arguments. Just create the
818 // same type as was lowered by ConvertType but strip off the varargs bit.
819 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
820 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
821 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000822
Chris Lattnerd26784e2009-03-21 08:53:37 +0000823 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000824 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000825
Chris Lattner5dd030f2009-03-21 09:25:43 +0000826 // Strip off a bitcast if we got one back.
827 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
828 assert(CE->getOpcode() == llvm::Instruction::BitCast);
829 Entry = CE->getOperand(0);
830 }
831
832
833 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000834 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000835 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
836 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000837
Chris Lattnere28718c2009-03-21 08:38:50 +0000838 // F is the Function* for the one with the wrong type, we must make a new
839 // Function* and update everything that used F (a declaration) with the new
840 // Function* (which will be a definition).
841 //
842 // This happens if there is a prototype for a function
843 // (e.g. "int f()") and then a definition of a different type
844 // (e.g. "int f(int x)"). Start by making a new function of the
845 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000846 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000847 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
848 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000849
850 // Replace uses of F with the Function we will endow with a body.
851 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000852 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
853 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000854
855 // Ok, delete the old function now, which is dead.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000856 // FIXME: If it was attribute(used) the pointer will dangle from the
857 // LLVMUsed array!
Chris Lattner5dd030f2009-03-21 09:25:43 +0000858 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000859
Chris Lattner5dd030f2009-03-21 09:25:43 +0000860 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000861 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000862
863 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000864
Daniel Dunbar566a6502008-09-08 23:44:31 +0000865 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000866
Daniel Dunbar566a6502008-09-08 23:44:31 +0000867 SetFunctionAttributesForDefinition(D, Fn);
868
Chris Lattnerd26784e2009-03-21 08:53:37 +0000869 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000870 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000871 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000872 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000873}
874
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000875void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
876 const AliasAttr *AA = D->getAttr<AliasAttr>();
877 assert(AA && "Not an alias?");
878
879 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
880
881 // Unique the name through the identifier table.
882 const char *AliaseeName = AA->getAliasee().c_str();
883 AliaseeName = getContext().Idents.get(AliaseeName).getName();
884
885 // Create a reference to the named value. This ensures that it is emitted
886 // if a deferred decl.
887 llvm::Constant *Aliasee;
888 if (isa<llvm::FunctionType>(DeclTy))
889 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
890 else
891 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
892 llvm::PointerType::getUnqual(DeclTy), 0);
893
894 // Create the new alias itself, but don't set a name yet.
895 llvm::GlobalValue *GA =
896 new llvm::GlobalAlias(Aliasee->getType(),
897 llvm::Function::ExternalLinkage,
898 "", Aliasee, &getModule());
899
900 // See if there is already something with the alias' name in the module.
901 const char *MangledName = getMangledName(D);
902 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
903
904 if (Entry && !Entry->isDeclaration()) {
905 // If there is a definition in the module, then it wins over the alias.
906 // This is dubious, but allow it to be safe. Just ignore the alias.
907 GA->eraseFromParent();
908 return;
909 }
910
911 if (Entry) {
912 // If there is a declaration in the module, then we had an extern followed
913 // by the alias, as in:
914 // extern int test6();
915 // ...
916 // int test6() __attribute__((alias("test7")));
917 //
918 // Remove it and replace uses of it with the alias.
919
920 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
921 Entry->getType()));
922 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
923 Entry->eraseFromParent();
924 }
925
926 // Now we know that there is no conflict, set the name.
927 Entry = GA;
928 GA->setName(MangledName);
929
930 // Alias should never be internal or inline.
931 SetGlobalValueAttributes(D, false, false, GA, true);
932}
933
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000934void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
935 // Make sure that this type is translated.
936 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000937}
938
939
Chris Lattnere6247a22009-03-22 21:56:56 +0000940/// getBuiltinLibFunction - Given a builtin id for a function like
941/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stump96b7a152009-02-27 22:42:30 +0000942llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor411889e2009-02-13 23:20:09 +0000943 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
944 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
945 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000946
Douglas Gregor411889e2009-02-13 23:20:09 +0000947 // Get the name, skip over the __builtin_ prefix (if necessary).
948 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
949 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
950 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000951
952 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000953 Builtin::Context::GetBuiltinTypeError Error;
954 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
955 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
956
Chris Lattnerab862cc2007-08-31 04:31:45 +0000957 const llvm::FunctionType *Ty =
958 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
959
Chris Lattnere6247a22009-03-22 21:56:56 +0000960 // Unique the name through the identifier table.
961 Name = getContext().Idents.get(Name).getName();
Chris Lattnerab862cc2007-08-31 04:31:45 +0000962 // FIXME: param attributes for sext/zext etc.
Chris Lattnere6247a22009-03-22 21:56:56 +0000963 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000964}
965
Chris Lattner4b23f942007-12-18 00:25:38 +0000966llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
967 unsigned NumTys) {
968 return llvm::Intrinsic::getDeclaration(&getModule(),
969 (llvm::Intrinsic::ID)IID, Tys, NumTys);
970}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000971
Chris Lattner4b009652007-07-25 00:24:17 +0000972llvm::Function *CodeGenModule::getMemCpyFn() {
973 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000974 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
975 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000976}
Anders Carlsson36a04872007-08-21 00:21:21 +0000977
Eli Friedman8f08a252008-05-26 12:59:39 +0000978llvm::Function *CodeGenModule::getMemMoveFn() {
979 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000980 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
981 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000982}
983
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000984llvm::Function *CodeGenModule::getMemSetFn() {
985 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000986 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
987 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000988}
Chris Lattner4b23f942007-12-18 00:25:38 +0000989
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000990static void appendFieldAndPadding(CodeGenModule &CGM,
991 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000992 FieldDecl *FieldD, FieldDecl *NextFieldD,
993 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +0000994 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000995 // Append the field.
996 Fields.push_back(Field);
997
Douglas Gregor8acb7272008-12-11 16:49:14 +0000998 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000999
1000 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001001 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001002 NextStructFieldNo = STy->getNumElements();
1003 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001004 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001005 }
1006
1007 // Append padding
1008 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1009 llvm::Constant *C =
1010 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1011
1012 Fields.push_back(C);
1013 }
1014}
1015
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001016// We still need to work out the details of handling UTF-16.
1017// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001018llvm::Constant *CodeGenModule::
1019GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001020 llvm::StringMapEntry<llvm::Constant *> &Entry =
1021 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1022
1023 if (Entry.getValue())
1024 return Entry.getValue();
1025
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001026 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1027 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001028
1029 if (!CFConstantStringClassRef) {
1030 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1031 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001032
1033 // FIXME: This is fairly broken if
1034 // __CFConstantStringClassReference is already defined, in that it
1035 // will get renamed and the user will most likely see an opaque
1036 // error message. This is a general issue with relying on
1037 // particular names.
1038 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001039 new llvm::GlobalVariable(Ty, false,
1040 llvm::GlobalVariable::ExternalLinkage, 0,
1041 "__CFConstantStringClassReference",
1042 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001043
1044 // Decay array -> ptr
1045 CFConstantStringClassRef =
1046 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001047 }
1048
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001049 QualType CFTy = getContext().getCFConstantStringType();
1050 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001051
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001052 const llvm::StructType *STy =
1053 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1054
1055 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001056 RecordDecl::field_iterator Field = CFRD->field_begin();
1057
Anders Carlsson36a04872007-08-21 00:21:21 +00001058 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001059 FieldDecl *CurField = *Field++;
1060 FieldDecl *NextField = *Field++;
1061 appendFieldAndPadding(*this, Fields, CurField, NextField,
1062 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001063
1064 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001065 CurField = NextField;
1066 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001067 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001068 appendFieldAndPadding(*this, Fields, CurField, NextField,
1069 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001070
1071 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001072 CurField = NextField;
1073 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001074 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001075 C = new llvm::GlobalVariable(C->getType(), true,
1076 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001077 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001078 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001079 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1080 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001081
1082 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001083 CurField = NextField;
1084 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001085 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001086 appendFieldAndPadding(*this, Fields, CurField, NextField,
1087 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001088
1089 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001090 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001091 llvm::GlobalVariable *GV =
1092 new llvm::GlobalVariable(C->getType(), true,
1093 llvm::GlobalVariable::InternalLinkage,
1094 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001095
Anders Carlsson9be009e2007-11-01 00:41:52 +00001096 GV->setSection("__DATA,__cfstring");
1097 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001098
Anders Carlsson9be009e2007-11-01 00:41:52 +00001099 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001100}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001101
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001102/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001103/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001104std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001105 const char *StrData = E->getStrData();
1106 unsigned Len = E->getByteLength();
1107
1108 const ConstantArrayType *CAT =
1109 getContext().getAsConstantArrayType(E->getType());
1110 assert(CAT && "String isn't pointer or array!");
1111
Chris Lattner14032222009-02-26 23:01:51 +00001112 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001113 std::string Str(StrData, StrData+Len);
1114 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001115
1116 if (E->isWide())
1117 RealLen *= getContext().Target.getWCharWidth()/8;
1118
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001119 Str.resize(RealLen, '\0');
1120
1121 return Str;
1122}
1123
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001124/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1125/// constant array for the given string literal.
1126llvm::Constant *
1127CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1128 // FIXME: This can be more efficient.
1129 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1130}
1131
Chris Lattnerc5d32632009-02-24 22:18:39 +00001132/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1133/// array for the given ObjCEncodeExpr node.
1134llvm::Constant *
1135CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1136 std::string Str;
1137 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001138
1139 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001140}
1141
1142
Chris Lattnera6dcce32008-02-11 00:02:17 +00001143/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001144static llvm::Constant *GenerateStringLiteral(const std::string &str,
1145 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001146 CodeGenModule &CGM,
1147 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001148 // Create Constant for this string literal. Don't add a '\0'.
1149 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001150
1151 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001152 return new llvm::GlobalVariable(C->getType(), constant,
1153 llvm::GlobalValue::InternalLinkage,
1154 C, GlobalName ? GlobalName : ".str",
1155 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001156}
1157
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001158/// GetAddrOfConstantString - Returns a pointer to a character array
1159/// containing the literal. This contents are exactly that of the
1160/// given string, i.e. it will not be null terminated automatically;
1161/// see GetAddrOfConstantCString. Note that whether the result is
1162/// actually a pointer to an LLVM constant depends on
1163/// Feature.WriteableStrings.
1164///
1165/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001166llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1167 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001168 // Don't share any string literals if writable-strings is turned on.
1169 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001170 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001171
1172 llvm::StringMapEntry<llvm::Constant *> &Entry =
1173 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1174
1175 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001176 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001177
1178 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001179 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001180 Entry.setValue(C);
1181 return C;
1182}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001183
1184/// GetAddrOfConstantCString - Returns a pointer to a character
1185/// array containing the literal and a terminating '\-'
1186/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001187llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1188 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001189 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001190}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001191
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001192/// EmitObjCPropertyImplementations - Emit information for synthesized
1193/// properties for an implementation.
1194void CodeGenModule::EmitObjCPropertyImplementations(const
1195 ObjCImplementationDecl *D) {
1196 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1197 e = D->propimpl_end(); i != e; ++i) {
1198 ObjCPropertyImplDecl *PID = *i;
1199
1200 // Dynamic is just for type-checking.
1201 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1202 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1203
1204 // Determine which methods need to be implemented, some may have
1205 // been overridden. Note that ::isSynthesized is not the method
1206 // we want, that just indicates if the decl came from a
1207 // property. What we want to know is if the method is defined in
1208 // this implementation.
1209 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001210 CodeGenFunction(*this).GenerateObjCGetter(
1211 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001212 if (!PD->isReadOnly() &&
1213 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001214 CodeGenFunction(*this).GenerateObjCSetter(
1215 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001216 }
1217 }
1218}
1219
Daniel Dunbar27250d32008-08-15 23:26:23 +00001220/// EmitTopLevelDecl - Emit code for a single top level declaration.
1221void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1222 // If an error has occurred, stop code generation, but continue
1223 // parsing and semantic analysis (to ensure all warnings and errors
1224 // are emitted).
1225 if (Diags.hasErrorOccurred())
1226 return;
1227
1228 switch (D->getKind()) {
1229 case Decl::Function:
1230 case Decl::Var:
1231 EmitGlobal(cast<ValueDecl>(D));
1232 break;
1233
1234 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001235 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001236 break;
1237
1238 // Objective-C Decls
1239
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001240 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001241 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001242 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001243 case Decl::ObjCCategory:
1244 case Decl::ObjCInterface:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001245 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001246
Daniel Dunbar27250d32008-08-15 23:26:23 +00001247 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001248 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001249 break;
1250
1251 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001252 // Categories have properties but don't support synthesize so we
1253 // can ignore them here.
1254
Daniel Dunbar27250d32008-08-15 23:26:23 +00001255 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1256 break;
1257
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001258 case Decl::ObjCImplementation: {
1259 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1260 EmitObjCPropertyImplementations(OMD);
1261 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001262 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001263 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001264 case Decl::ObjCMethod: {
1265 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1266 // If this is not a prototype, emit the body.
1267 if (OMD->getBody())
1268 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1269 break;
1270 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001271 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001272 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001273 break;
1274
1275 case Decl::LinkageSpec: {
1276 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1277 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001278 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001279 // FIXME: implement C++ linkage, C linkage works mostly by C
1280 // language reuse already.
1281 break;
1282 }
1283
1284 case Decl::FileScopeAsm: {
1285 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1286 std::string AsmString(AD->getAsmString()->getStrData(),
1287 AD->getAsmString()->getByteLength());
1288
1289 const std::string &S = getModule().getModuleInlineAsm();
1290 if (S.empty())
1291 getModule().setModuleInlineAsm(AsmString);
1292 else
1293 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1294 break;
1295 }
1296
1297 default:
1298 // Make sure we handled everything we should, every other kind is
1299 // a non-top-level decl. FIXME: Would be nice to have an
1300 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1301 // that easily.
1302 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1303 }
1304}