blob: 907ade569bbcc8ca2d37c8b588a1461e0f57a441 [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);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000314}
315
316void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
317 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000318 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000319
Daniel Dunbar566a6502008-09-08 23:44:31 +0000320 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000321}
322
323void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
324 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000325 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000326
Daniel Dunbar566a6502008-09-08 23:44:31 +0000327 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
328 FD->isInline(), F, false);
329}
330
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000331void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
332 assert(!GV->isDeclaration() &&
333 "Only globals with definition can force usage.");
334 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
335 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
336}
337
338void CodeGenModule::EmitLLVMUsed() {
339 // Don't create llvm.used if there is no need.
340 if (LLVMUsed.empty())
341 return;
342
343 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
344 LLVMUsed.size());
345 llvm::GlobalVariable *GV =
346 new llvm::GlobalVariable(ATy, false,
347 llvm::GlobalValue::AppendingLinkage,
348 llvm::ConstantArray::get(ATy, LLVMUsed),
349 "llvm.used", &getModule());
350
351 GV->setSection("llvm.metadata");
352}
353
354void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000355 // Emit code for any potentially referenced deferred decls. Since a
356 // previously unused static decl may become used during the generation of code
357 // for a static function, iterate until no changes are made.
358 while (!DeferredDeclsToEmit.empty()) {
359 const ValueDecl *D = DeferredDeclsToEmit.back();
360 DeferredDeclsToEmit.pop_back();
361
362 // The mangled name for the decl must have been emitted in GlobalDeclMap.
363 // Look it up to see if it was defined with a stronger definition (e.g. an
364 // extern inline function with a strong function redefinition). If so,
365 // just ignore the deferred decl.
366 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
367 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000368
Chris Lattner38837f92009-03-21 09:44:56 +0000369 if (!CGRef->isDeclaration())
370 continue;
371
372 // Otherwise, emit the definition and move on to the next one.
373 EmitGlobalDefinition(D);
374 }
Chris Lattner4b009652007-07-25 00:24:17 +0000375}
376
Nate Begeman8a704172008-04-19 04:17:09 +0000377/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
378/// annotation information for a given GlobalValue. The annotation struct is
379/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000380/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000381/// created from the AnnotateAttr's annotation. The third field is a constant
382/// string containing the name of the translation unit. The fourth field is
383/// the line number in the file of the annotated value declaration.
384///
385/// FIXME: this does not unique the annotation string constants, as llvm-gcc
386/// appears to.
387///
388llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
389 const AnnotateAttr *AA,
390 unsigned LineNo) {
391 llvm::Module *M = &getModule();
392
393 // get [N x i8] constants for the annotation string, and the filename string
394 // which are the 2nd and 3rd elements of the global annotation structure.
395 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
397 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
398 true);
399
400 // Get the two global values corresponding to the ConstantArrays we just
401 // created to hold the bytes of the strings.
402 llvm::GlobalValue *annoGV =
403 new llvm::GlobalVariable(anno->getType(), false,
404 llvm::GlobalValue::InternalLinkage, anno,
405 GV->getName() + ".str", M);
406 // translation unit name string, emitted into the llvm.metadata section.
407 llvm::GlobalValue *unitGV =
408 new llvm::GlobalVariable(unit->getType(), false,
409 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
410
411 // Create the ConstantStruct that is the global annotion.
412 llvm::Constant *Fields[4] = {
413 llvm::ConstantExpr::getBitCast(GV, SBP),
414 llvm::ConstantExpr::getBitCast(annoGV, SBP),
415 llvm::ConstantExpr::getBitCast(unitGV, SBP),
416 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
417 };
418 return llvm::ConstantStruct::get(Fields, 4, false);
419}
420
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000421bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000422 // Never defer when EmitAllDecls is specified or the decl has
423 // attribute used.
424 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000425 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000426
427 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000428 // Constructors and destructors should never be deferred.
429 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
430 return false;
431
Chris Lattner7e5888f2009-03-21 08:03:33 +0000432 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000433 if (FD->getStorageClass() != FunctionDecl::Static)
434 return false;
435 } else {
436 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000437 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000438
439 if (VD->getStorageClass() != VarDecl::Static)
440 return false;
441 }
442
443 return true;
444}
445
446void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000447 // If this is an alias definition (which otherwise looks like a declaration)
448 // emit it now.
449 if (Global->getAttr<AliasAttr>())
450 return EmitAliasDefinition(Global);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000451
Chris Lattner38837f92009-03-21 09:44:56 +0000452 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000453 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000454 // Forward declarations are emitted lazily on first use.
455 if (!FD->isThisDeclarationADefinition())
456 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000457 } else {
458 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000459 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
460
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000461 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000462 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000463 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000464 }
465
Chris Lattner38837f92009-03-21 09:44:56 +0000466 // Defer code generation when possible if this is a static definition, inline
467 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000468 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000469 // If the value has already been used, add it directly to the
470 // DeferredDeclsToEmit list.
471 const char *MangledName = getMangledName(Global);
472 if (GlobalDeclMap.count(MangledName))
473 DeferredDeclsToEmit.push_back(Global);
474 else {
475 // Otherwise, remember that we saw a deferred decl with this name. The
476 // first use of the mangled name will cause it to move into
477 // DeferredDeclsToEmit.
478 DeferredDecls[MangledName] = Global;
479 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000480 return;
481 }
482
483 // Otherwise emit the definition.
484 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000485}
486
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000487void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
488 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
489 EmitGlobalFunctionDefinition(FD);
490 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
491 EmitGlobalVarDefinition(VD);
492 } else {
493 assert(0 && "Invalid argument to EmitGlobalDefinition()");
494 }
495}
496
Chris Lattneraea1aee2009-03-22 21:03:39 +0000497/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
498/// module, create and return an llvm Function with the specified type. If there
499/// is something in the module with the specified name, return it potentially
500/// bitcasted to the right type.
501///
502/// If D is non-null, it specifies a decl that correspond to this. This is used
503/// to set the attributes on the function when it is first created.
504llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
505 const llvm::Type *Ty,
506 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000507 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000508 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
509 if (Entry) {
510 if (Entry->getType()->getElementType() == Ty)
511 return Entry;
512
513 // Make sure the result is of the correct type.
514 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
515 return llvm::ConstantExpr::getBitCast(Entry, PTy);
516 }
517
Chris Lattner38837f92009-03-21 09:44:56 +0000518 // This is the first use or definition of a mangled name. If there is a
519 // deferred decl with this name, remember that we need to emit it at the end
520 // of the file.
521 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000522 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000523 if (DDI != DeferredDecls.end()) {
524 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
525 // list, and remove it from DeferredDecls (since we don't need it anymore).
526 DeferredDeclsToEmit.push_back(DDI->second);
527 DeferredDecls.erase(DDI);
528 }
529
Chris Lattner5dd030f2009-03-21 09:25:43 +0000530 // This function doesn't have a complete type (for example, the return
531 // type is an incomplete struct). Use a fake type instead, and make
532 // sure not to try to set attributes.
533 bool ShouldSetAttributes = true;
534 if (!isa<llvm::FunctionType>(Ty)) {
535 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
536 std::vector<const llvm::Type*>(), false);
537 ShouldSetAttributes = false;
538 }
539 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
540 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000541 "", &getModule());
542 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000543 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000544 SetFunctionAttributes(D, F);
545 Entry = F;
546 return F;
547}
548
Chris Lattneraea1aee2009-03-22 21:03:39 +0000549/// GetAddrOfFunction - Return the address of the given function. If Ty is
550/// non-null, then this function will use the specified type if it has to
551/// create it (this occurs when we see a definition of the function).
552llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
553 const llvm::Type *Ty) {
554 // If there was no specific requested type, just convert it now.
555 if (!Ty)
556 Ty = getTypes().ConvertType(D->getType());
557 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
558}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000559
Chris Lattneraea1aee2009-03-22 21:03:39 +0000560/// CreateRuntimeFunction - Create a new runtime function with the specified
561/// type and name.
562llvm::Constant *
563CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
564 const char *Name) {
565 // Convert Name to be a uniqued string from the IdentifierInfo table.
566 Name = getContext().Idents.get(Name).getName();
567 return GetOrCreateLLVMFunction(Name, FTy, 0);
568}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000569
Chris Lattneraea1aee2009-03-22 21:03:39 +0000570/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
571/// create and return an llvm GlobalVariable with the specified type. If there
572/// is something in the module with the specified name, return it potentially
573/// bitcasted to the right type.
574///
575/// If D is non-null, it specifies a decl that correspond to this. This is used
576/// to set the attributes on the global when it is first created.
577llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
578 const llvm::PointerType*Ty,
579 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000580 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000581 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000582 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000583 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000584 return Entry;
585
Chris Lattner7e5888f2009-03-21 08:03:33 +0000586 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000587 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000588 }
Chris Lattner38837f92009-03-21 09:44:56 +0000589
590 // This is the first use or definition of a mangled name. If there is a
591 // deferred decl with this name, remember that we need to emit it at the end
592 // of the file.
593 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
594 DeferredDecls.find(MangledName);
595 if (DDI != DeferredDecls.end()) {
596 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
597 // list, and remove it from DeferredDecls (since we don't need it anymore).
598 DeferredDeclsToEmit.push_back(DDI->second);
599 DeferredDecls.erase(DDI);
600 }
601
Chris Lattner7e5888f2009-03-21 08:03:33 +0000602 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000603 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000604 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000605 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000606 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000607 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000608
609 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000610 if (D) {
611 // FIXME: This code is overly simple and should be merged with
612 // other global handling.
613 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000614
Chris Lattneraea1aee2009-03-22 21:03:39 +0000615 // FIXME: Merge with other attribute handling code.
616 if (D->getStorageClass() == VarDecl::PrivateExtern)
617 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000618
Chris Lattneraea1aee2009-03-22 21:03:39 +0000619 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
620 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
621 }
622
Chris Lattner7e5888f2009-03-21 08:03:33 +0000623 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000624}
625
Chris Lattneraea1aee2009-03-22 21:03:39 +0000626
627/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
628/// given global variable. If Ty is non-null and if the global doesn't exist,
629/// then it will be greated with the specified type instead of whatever the
630/// normal requested type would be.
631llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
632 const llvm::Type *Ty) {
633 assert(D->hasGlobalStorage() && "Not a global variable");
634 QualType ASTTy = D->getType();
635 if (Ty == 0)
636 Ty = getTypes().ConvertTypeForMem(ASTTy);
637
638 const llvm::PointerType *PTy =
639 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
640 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
641}
642
643/// CreateRuntimeVariable - Create a new runtime global variable with the
644/// specified type and name.
645llvm::Constant *
646CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
647 const char *Name) {
648 // Convert Name to be a uniqued string from the IdentifierInfo table.
649 Name = getContext().Idents.get(Name).getName();
650 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
651}
652
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000653void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000654 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000655 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000656
Chris Lattner4b009652007-07-25 00:24:17 +0000657 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000658 // This is a tentative definition; tentative definitions are
659 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000660 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000661 if (ASTTy->isIncompleteArrayType()) {
662 // An incomplete array is normally [ TYPE x 0 ], but we need
663 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000664 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000665 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000666 }
667 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000668 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000669 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000670 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000671 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000672 QualType T = D->getInit()->getType();
673 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
674 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000675 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000676
Chris Lattner23afd5b2009-03-21 08:13:05 +0000677 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000678 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000679
Chris Lattnera6984932009-03-21 09:16:30 +0000680 // Strip off a bitcast if we got one back.
681 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
682 assert(CE->getOpcode() == llvm::Instruction::BitCast);
683 Entry = CE->getOperand(0);
684 }
685
686 // Entry is now either a Function or GlobalVariable.
687 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
688
689 // If we already have this global and it has an initializer, then
690 // we are in the rare situation where we emitted the defining
691 // declaration of the global and are now being asked to emit a
692 // definition which would be common. This occurs, for example, in
693 // the following situation because statics can be emitted out of
694 // order:
695 //
696 // static int x;
697 // static int *y = &x;
698 // static int x = 10;
699 // int **z = &y;
700 //
701 // Bail here so we don't blow away the definition. Note that if we
702 // can't distinguish here if we emitted a definition with a null
703 // initializer, but this case is safe.
704 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000705 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
706 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000707 }
708
709 // We have a definition after a declaration with the wrong type.
710 // We must make a new GlobalVariable* and update everything that used OldGV
711 // (a declaration or tentative definition) with the new GlobalVariable*
712 // (which will be a definition).
713 //
714 // This happens if there is a prototype for a global (e.g.
715 // "extern int x[];") and then a definition of a different type (e.g.
716 // "int x[10];"). This also happens when an initializer has a different type
717 // from the type of the global (this happens with unions).
718 //
719 // FIXME: This also ends up happening if there's a definition followed by
720 // a tentative definition! (Although Sema rejects that construct
721 // at the moment.)
722 if (GV == 0 ||
723 GV->getType()->getElementType() != InitType ||
724 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
725
726 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
727 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000728
Chris Lattnera6984932009-03-21 09:16:30 +0000729 // Make a new global with the correct type, this is now guaranteed to work.
730 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000731 GV->takeName(cast<llvm::GlobalValue>(Entry));
732
Eli Friedman43a0ce82008-05-30 19:50:47 +0000733 // Replace all uses of the old global with the new global
734 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000735 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
736 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000737
738 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000739 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattnera6984932009-03-21 09:16:30 +0000740 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000741 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000742
Nate Begeman8a704172008-04-19 04:17:09 +0000743 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
744 SourceManager &SM = Context.getSourceManager();
745 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000746 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000747 }
748
Chris Lattner4b009652007-07-25 00:24:17 +0000749 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000750 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000751 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000752
Chris Lattner402b3372008-03-03 03:28:21 +0000753 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000754 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000755 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000756
Chris Lattner4b009652007-07-25 00:24:17 +0000757 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000758 if (D->getStorageClass() == VarDecl::Static)
759 GV->setLinkage(llvm::Function::InternalLinkage);
760 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000761 GV->setLinkage(llvm::Function::DLLImportLinkage);
762 else if (D->getAttr<DLLExportAttr>())
763 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000764 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000765 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000766 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000767 // FIXME: This isn't right. This should handle common linkage and other
768 // stuff.
769 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000770 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000771 case VarDecl::Auto:
772 case VarDecl::Register:
773 assert(0 && "Can't have auto or register globals");
774 case VarDecl::None:
Chris Lattnerf04a7562009-03-26 05:00:52 +0000775 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sands78c33cc2009-03-11 20:15:27 +0000776 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000777 else
778 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000779 break;
780 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000781 // FIXME: common
782 break;
783
Chris Lattner402b3372008-03-03 03:28:21 +0000784 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000785 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
786 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000787 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000788 }
Chris Lattner4b009652007-07-25 00:24:17 +0000789 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000790
Daniel Dunbar97509722009-02-12 17:28:23 +0000791 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
792 GV->setSection(SA->getName());
793
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000794 if (D->getAttr<UsedAttr>())
795 AddUsedGlobal(GV);
796
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000797 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000798 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000799 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000800 DI->EmitGlobalVariable(GV, D);
801 }
Chris Lattner4b009652007-07-25 00:24:17 +0000802}
803
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000804
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000805void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000806 const llvm::FunctionType *Ty =
807 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
808
809 // As a special case, make sure that definitions of K&R function
810 // "type foo()" aren't declared as varargs (which forces the backend
811 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000812 if (D->getType()->isFunctionNoProtoType()) {
813 assert(Ty->isVarArg() && "Didn't lower type as expected");
814 // Due to stret, the lowered function could have arguments. Just create the
815 // same type as was lowered by ConvertType but strip off the varargs bit.
816 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
817 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
818 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000819
Chris Lattnerd26784e2009-03-21 08:53:37 +0000820 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000821 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000822
Chris Lattner5dd030f2009-03-21 09:25:43 +0000823 // Strip off a bitcast if we got one back.
824 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
825 assert(CE->getOpcode() == llvm::Instruction::BitCast);
826 Entry = CE->getOperand(0);
827 }
828
829
830 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000831 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000832 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
833 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000834
Chris Lattnere28718c2009-03-21 08:38:50 +0000835 // F is the Function* for the one with the wrong type, we must make a new
836 // Function* and update everything that used F (a declaration) with the new
837 // Function* (which will be a definition).
838 //
839 // This happens if there is a prototype for a function
840 // (e.g. "int f()") and then a definition of a different type
841 // (e.g. "int f(int x)"). Start by making a new function of the
842 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000843 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000844 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
845 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000846
847 // Replace uses of F with the Function we will endow with a body.
848 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000849 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
850 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000851
852 // Ok, delete the old function now, which is dead.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000853 // FIXME: If it was attribute(used) the pointer will dangle from the
854 // LLVMUsed array!
Chris Lattner5dd030f2009-03-21 09:25:43 +0000855 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000856
Chris Lattner5dd030f2009-03-21 09:25:43 +0000857 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000858 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000859
860 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000861
Daniel Dunbar566a6502008-09-08 23:44:31 +0000862 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000863
Daniel Dunbar566a6502008-09-08 23:44:31 +0000864 SetFunctionAttributesForDefinition(D, Fn);
865
Chris Lattnerd26784e2009-03-21 08:53:37 +0000866 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000867 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000868 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000869 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000870}
871
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000872void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
873 const AliasAttr *AA = D->getAttr<AliasAttr>();
874 assert(AA && "Not an alias?");
875
876 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
877
878 // Unique the name through the identifier table.
879 const char *AliaseeName = AA->getAliasee().c_str();
880 AliaseeName = getContext().Idents.get(AliaseeName).getName();
881
882 // Create a reference to the named value. This ensures that it is emitted
883 // if a deferred decl.
884 llvm::Constant *Aliasee;
885 if (isa<llvm::FunctionType>(DeclTy))
886 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
887 else
888 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
889 llvm::PointerType::getUnqual(DeclTy), 0);
890
891 // Create the new alias itself, but don't set a name yet.
892 llvm::GlobalValue *GA =
893 new llvm::GlobalAlias(Aliasee->getType(),
894 llvm::Function::ExternalLinkage,
895 "", Aliasee, &getModule());
896
897 // See if there is already something with the alias' name in the module.
898 const char *MangledName = getMangledName(D);
899 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
900
901 if (Entry && !Entry->isDeclaration()) {
902 // If there is a definition in the module, then it wins over the alias.
903 // This is dubious, but allow it to be safe. Just ignore the alias.
904 GA->eraseFromParent();
905 return;
906 }
907
908 if (Entry) {
909 // If there is a declaration in the module, then we had an extern followed
910 // by the alias, as in:
911 // extern int test6();
912 // ...
913 // int test6() __attribute__((alias("test7")));
914 //
915 // Remove it and replace uses of it with the alias.
916
917 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
918 Entry->getType()));
919 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
920 Entry->eraseFromParent();
921 }
922
923 // Now we know that there is no conflict, set the name.
924 Entry = GA;
925 GA->setName(MangledName);
926
927 // Alias should never be internal or inline.
928 SetGlobalValueAttributes(D, false, false, GA, true);
929}
930
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000931void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
932 // Make sure that this type is translated.
933 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000934}
935
936
Chris Lattnere6247a22009-03-22 21:56:56 +0000937/// getBuiltinLibFunction - Given a builtin id for a function like
938/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stump96b7a152009-02-27 22:42:30 +0000939llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor411889e2009-02-13 23:20:09 +0000940 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
941 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
942 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000943
Douglas Gregor411889e2009-02-13 23:20:09 +0000944 // Get the name, skip over the __builtin_ prefix (if necessary).
945 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
946 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
947 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000948
949 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000950 Builtin::Context::GetBuiltinTypeError Error;
951 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
952 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
953
Chris Lattnerab862cc2007-08-31 04:31:45 +0000954 const llvm::FunctionType *Ty =
955 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
956
Chris Lattnere6247a22009-03-22 21:56:56 +0000957 // Unique the name through the identifier table.
958 Name = getContext().Idents.get(Name).getName();
Chris Lattnerab862cc2007-08-31 04:31:45 +0000959 // FIXME: param attributes for sext/zext etc.
Chris Lattnere6247a22009-03-22 21:56:56 +0000960 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000961}
962
Chris Lattner4b23f942007-12-18 00:25:38 +0000963llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
964 unsigned NumTys) {
965 return llvm::Intrinsic::getDeclaration(&getModule(),
966 (llvm::Intrinsic::ID)IID, Tys, NumTys);
967}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000968
Chris Lattner4b009652007-07-25 00:24:17 +0000969llvm::Function *CodeGenModule::getMemCpyFn() {
970 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000971 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
972 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000973}
Anders Carlsson36a04872007-08-21 00:21:21 +0000974
Eli Friedman8f08a252008-05-26 12:59:39 +0000975llvm::Function *CodeGenModule::getMemMoveFn() {
976 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000977 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
978 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000979}
980
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000981llvm::Function *CodeGenModule::getMemSetFn() {
982 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000983 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
984 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000985}
Chris Lattner4b23f942007-12-18 00:25:38 +0000986
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000987static void appendFieldAndPadding(CodeGenModule &CGM,
988 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000989 FieldDecl *FieldD, FieldDecl *NextFieldD,
990 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +0000991 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000992 // Append the field.
993 Fields.push_back(Field);
994
Douglas Gregor8acb7272008-12-11 16:49:14 +0000995 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000996
997 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000998 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000999 NextStructFieldNo = STy->getNumElements();
1000 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001001 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001002 }
1003
1004 // Append padding
1005 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1006 llvm::Constant *C =
1007 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1008
1009 Fields.push_back(C);
1010 }
1011}
1012
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001013// We still need to work out the details of handling UTF-16.
1014// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001015llvm::Constant *CodeGenModule::
1016GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001017 llvm::StringMapEntry<llvm::Constant *> &Entry =
1018 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1019
1020 if (Entry.getValue())
1021 return Entry.getValue();
1022
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001023 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1024 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001025
1026 if (!CFConstantStringClassRef) {
1027 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1028 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001029
1030 // FIXME: This is fairly broken if
1031 // __CFConstantStringClassReference is already defined, in that it
1032 // will get renamed and the user will most likely see an opaque
1033 // error message. This is a general issue with relying on
1034 // particular names.
1035 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001036 new llvm::GlobalVariable(Ty, false,
1037 llvm::GlobalVariable::ExternalLinkage, 0,
1038 "__CFConstantStringClassReference",
1039 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001040
1041 // Decay array -> ptr
1042 CFConstantStringClassRef =
1043 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001044 }
1045
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001046 QualType CFTy = getContext().getCFConstantStringType();
1047 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001048
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001049 const llvm::StructType *STy =
1050 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1051
1052 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001053 RecordDecl::field_iterator Field = CFRD->field_begin();
1054
Anders Carlsson36a04872007-08-21 00:21:21 +00001055 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001056 FieldDecl *CurField = *Field++;
1057 FieldDecl *NextField = *Field++;
1058 appendFieldAndPadding(*this, Fields, CurField, NextField,
1059 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001060
1061 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001062 CurField = NextField;
1063 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001064 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001065 appendFieldAndPadding(*this, Fields, CurField, NextField,
1066 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001067
1068 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001069 CurField = NextField;
1070 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001071 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001072 C = new llvm::GlobalVariable(C->getType(), true,
1073 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001074 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001075 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001076 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1077 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001078
1079 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001080 CurField = NextField;
1081 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001082 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001083 appendFieldAndPadding(*this, Fields, CurField, NextField,
1084 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001085
1086 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001087 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001088 llvm::GlobalVariable *GV =
1089 new llvm::GlobalVariable(C->getType(), true,
1090 llvm::GlobalVariable::InternalLinkage,
1091 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001092
Anders Carlsson9be009e2007-11-01 00:41:52 +00001093 GV->setSection("__DATA,__cfstring");
1094 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001095
Anders Carlsson9be009e2007-11-01 00:41:52 +00001096 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001097}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001098
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001099/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001100/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001101std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001102 const char *StrData = E->getStrData();
1103 unsigned Len = E->getByteLength();
1104
1105 const ConstantArrayType *CAT =
1106 getContext().getAsConstantArrayType(E->getType());
1107 assert(CAT && "String isn't pointer or array!");
1108
Chris Lattner14032222009-02-26 23:01:51 +00001109 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001110 std::string Str(StrData, StrData+Len);
1111 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001112
1113 if (E->isWide())
1114 RealLen *= getContext().Target.getWCharWidth()/8;
1115
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001116 Str.resize(RealLen, '\0');
1117
1118 return Str;
1119}
1120
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001121/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1122/// constant array for the given string literal.
1123llvm::Constant *
1124CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1125 // FIXME: This can be more efficient.
1126 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1127}
1128
Chris Lattnerc5d32632009-02-24 22:18:39 +00001129/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1130/// array for the given ObjCEncodeExpr node.
1131llvm::Constant *
1132CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1133 std::string Str;
1134 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001135
1136 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001137}
1138
1139
Chris Lattnera6dcce32008-02-11 00:02:17 +00001140/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001141static llvm::Constant *GenerateStringLiteral(const std::string &str,
1142 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001143 CodeGenModule &CGM,
1144 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001145 // Create Constant for this string literal. Don't add a '\0'.
1146 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001147
1148 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001149 return new llvm::GlobalVariable(C->getType(), constant,
1150 llvm::GlobalValue::InternalLinkage,
1151 C, GlobalName ? GlobalName : ".str",
1152 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001153}
1154
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001155/// GetAddrOfConstantString - Returns a pointer to a character array
1156/// containing the literal. This contents are exactly that of the
1157/// given string, i.e. it will not be null terminated automatically;
1158/// see GetAddrOfConstantCString. Note that whether the result is
1159/// actually a pointer to an LLVM constant depends on
1160/// Feature.WriteableStrings.
1161///
1162/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001163llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1164 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001165 // Don't share any string literals if writable-strings is turned on.
1166 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001167 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001168
1169 llvm::StringMapEntry<llvm::Constant *> &Entry =
1170 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1171
1172 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001173 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001174
1175 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001176 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001177 Entry.setValue(C);
1178 return C;
1179}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001180
1181/// GetAddrOfConstantCString - Returns a pointer to a character
1182/// array containing the literal and a terminating '\-'
1183/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001184llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1185 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001186 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001187}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001188
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001189/// EmitObjCPropertyImplementations - Emit information for synthesized
1190/// properties for an implementation.
1191void CodeGenModule::EmitObjCPropertyImplementations(const
1192 ObjCImplementationDecl *D) {
1193 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1194 e = D->propimpl_end(); i != e; ++i) {
1195 ObjCPropertyImplDecl *PID = *i;
1196
1197 // Dynamic is just for type-checking.
1198 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1199 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1200
1201 // Determine which methods need to be implemented, some may have
1202 // been overridden. Note that ::isSynthesized is not the method
1203 // we want, that just indicates if the decl came from a
1204 // property. What we want to know is if the method is defined in
1205 // this implementation.
1206 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001207 CodeGenFunction(*this).GenerateObjCGetter(
1208 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001209 if (!PD->isReadOnly() &&
1210 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001211 CodeGenFunction(*this).GenerateObjCSetter(
1212 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001213 }
1214 }
1215}
1216
Daniel Dunbar27250d32008-08-15 23:26:23 +00001217/// EmitTopLevelDecl - Emit code for a single top level declaration.
1218void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1219 // If an error has occurred, stop code generation, but continue
1220 // parsing and semantic analysis (to ensure all warnings and errors
1221 // are emitted).
1222 if (Diags.hasErrorOccurred())
1223 return;
1224
1225 switch (D->getKind()) {
1226 case Decl::Function:
1227 case Decl::Var:
1228 EmitGlobal(cast<ValueDecl>(D));
1229 break;
1230
1231 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001232 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001233 break;
1234
1235 // Objective-C Decls
1236
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001237 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001238 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001239 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001240 case Decl::ObjCCategory:
1241 case Decl::ObjCInterface:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001242 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001243
Daniel Dunbar27250d32008-08-15 23:26:23 +00001244 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001245 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001246 break;
1247
1248 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001249 // Categories have properties but don't support synthesize so we
1250 // can ignore them here.
1251
Daniel Dunbar27250d32008-08-15 23:26:23 +00001252 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1253 break;
1254
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001255 case Decl::ObjCImplementation: {
1256 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1257 EmitObjCPropertyImplementations(OMD);
1258 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001259 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001260 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001261 case Decl::ObjCMethod: {
1262 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1263 // If this is not a prototype, emit the body.
1264 if (OMD->getBody())
1265 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1266 break;
1267 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001268 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001269 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001270 break;
1271
1272 case Decl::LinkageSpec: {
1273 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1274 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001275 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001276 // FIXME: implement C++ linkage, C linkage works mostly by C
1277 // language reuse already.
1278 break;
1279 }
1280
1281 case Decl::FileScopeAsm: {
1282 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1283 std::string AsmString(AD->getAsmString()->getStrData(),
1284 AD->getAsmString()->getByteLength());
1285
1286 const std::string &S = getModule().getModuleInlineAsm();
1287 if (S.empty())
1288 getModule().setModuleInlineAsm(AsmString);
1289 else
1290 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1291 break;
1292 }
1293
1294 default:
1295 // Make sure we handled everything we should, every other kind is
1296 // a non-top-level decl. FIXME: Would be nice to have an
1297 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1298 // that easily.
1299 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1300 }
1301}