blob: a187f8a51bb4f1046f6d77dc0b980ba984237d3a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner45e8cbd2007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Mike Stump90a90432009-03-04 18:47:42 +000037 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000038 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000040
41 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000042 if (Features.NeXTRuntime) {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000043 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanianee0af742009-01-21 22:04:16 +000044 : CreateMacObjCRuntime(*this);
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000045 } else {
46 Runtime = CreateGNUObjCRuntime(*this);
47 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000048 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stump26efc332009-02-13 18:36:05 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Daniel Dunbar02698712009-02-13 20:29:50 +000060 EmitDeferred();
Daniel Dunbar219df662008-09-08 23:44:31 +000061 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000062 if (Runtime)
63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000065 EmitCtorList(GlobalCtors, "llvm.global_ctors");
66 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000067 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000068 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000069 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000070}
Reid Spencer5f016e22007-07-11 17:01:13 +000071
Daniel Dunbarf1968f22008-10-01 00:49:24 +000072void CodeGenModule::BindRuntimeFunctions() {
73 // Deal with protecting runtime function names.
74 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
75 llvm::Function *Fn = RuntimeFunctions[i].first;
76 const std::string &Name = RuntimeFunctions[i].second;
77
Daniel Dunbar0293d542008-11-19 06:15:35 +000078 // Discard unused runtime functions.
79 if (Fn->use_empty()) {
80 Fn->eraseFromParent();
81 continue;
82 }
83
Daniel Dunbarf1968f22008-10-01 00:49:24 +000084 // See if there is a conflict against a function.
85 llvm::Function *Conflict = TheModule.getFunction(Name);
86 if (Conflict) {
87 // Decide which version to take. If the conflict is a definition
88 // we are forced to take that, otherwise assume the runtime
89 // knows best.
90 if (!Conflict->isDeclaration()) {
91 llvm::Value *Casted =
92 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
93 Fn->replaceAllUsesWith(Casted);
94 Fn->eraseFromParent();
95 } else {
96 Fn->takeName(Conflict);
97 llvm::Value *Casted =
98 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
99 Conflict->replaceAllUsesWith(Casted);
100 Conflict->eraseFromParent();
101 }
102 } else {
103 // FIXME: There still may be conflicts with aliases and
104 // variables.
105 Fn->setName(Name);
106 }
107 }
108}
109
Daniel Dunbar488e9932008-08-16 00:56:44 +0000110/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000111/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000112void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
113 bool OmitOnError) {
114 if (OmitOnError && getDiags().hasErrorOccurred())
115 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000116 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000117 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000118 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000119 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
120 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000121}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000122
Daniel Dunbar488e9932008-08-16 00:56:44 +0000123/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000124/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000125void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
126 bool OmitOnError) {
127 if (OmitOnError && getDiags().hasErrorOccurred())
128 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000129 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000130 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000131 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000132 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000133}
134
Daniel Dunbar41071de2008-08-15 23:26:23 +0000135/// setGlobalVisibility - Set the visibility for the given LLVM
136/// GlobalValue according to the given clang AST visibility value.
137static void setGlobalVisibility(llvm::GlobalValue *GV,
138 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000139 switch (Vis) {
140 default: assert(0 && "Unknown visibility!");
141 case VisibilityAttr::DefaultVisibility:
142 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
143 break;
144 case VisibilityAttr::HiddenVisibility:
145 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
146 break;
147 case VisibilityAttr::ProtectedVisibility:
148 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
149 break;
150 }
151}
152
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000153/// \brief Retrieves the mangled name for the given declaration.
154///
155/// If the given declaration requires a mangled name, returns an
156/// IdentifierInfo* containing the mangled name. Otherwise, returns
157/// the name of the declaration as an identifier.
158///
159/// FIXME: Returning an IdentifierInfo* here is a total hack. We
160/// really need some kind of string abstraction that either stores a
161/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbarb5da3e92009-02-18 22:52:09 +0000162/// changes to the GlobalDeclMap, too. (I disagree, I think what we
163/// actually need is for Sema to provide some notion of which Decls
164/// refer to the same semantic decl. We shouldn't need to mangle the
165/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000166///
167/// FIXME: Performance here is going to be terribly until we start
168/// caching mangled names. However, we should fix the problem above
169/// first.
Douglas Gregor6ec36682009-02-18 23:53:56 +0000170const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
171 llvm::SmallString<256> Name;
172 llvm::raw_svector_ostream Out(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000173 if (!mangleName(ND, Context, Out))
Douglas Gregor6ec36682009-02-18 23:53:56 +0000174 return ND->getIdentifier()->getName();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000175
Douglas Gregor6ec36682009-02-18 23:53:56 +0000176 Name += '\0';
177 return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
178 .getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000179}
180
Chris Lattner6d397602008-03-14 17:18:18 +0000181/// AddGlobalCtor - Add a function to the list that will be called before
182/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000183void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000184 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000186}
187
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000188/// AddGlobalDtor - Add a function to the list that will be called
189/// when the module is unloaded.
190void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000191 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000192 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
193}
194
195void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
196 // Ctor function type is void()*.
197 llvm::FunctionType* CtorFTy =
198 llvm::FunctionType::get(llvm::Type::VoidTy,
199 std::vector<const llvm::Type*>(),
200 false);
201 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
202
203 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000204 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000205 llvm::StructType::get(llvm::Type::Int32Ty,
206 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000207
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000208 // Construct the constructor and destructor arrays.
209 std::vector<llvm::Constant*> Ctors;
210 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
211 std::vector<llvm::Constant*> S;
212 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
213 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
214 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000215 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000216
217 if (!Ctors.empty()) {
218 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
219 new llvm::GlobalVariable(AT, false,
220 llvm::GlobalValue::AppendingLinkage,
221 llvm::ConstantArray::get(AT, Ctors),
222 GlobalName,
223 &TheModule);
224 }
Chris Lattner6d397602008-03-14 17:18:18 +0000225}
226
Nate Begeman532485c2008-04-18 23:43:57 +0000227void CodeGenModule::EmitAnnotations() {
228 if (Annotations.empty())
229 return;
230
231 // Create a new global variable for the ConstantStruct in the Module.
232 llvm::Constant *Array =
233 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
234 Annotations.size()),
235 Annotations);
236 llvm::GlobalValue *gv =
237 new llvm::GlobalVariable(Array->getType(), false,
238 llvm::GlobalValue::AppendingLinkage, Array,
239 "llvm.global.annotations", &TheModule);
240 gv->setSection("llvm.metadata");
241}
242
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000243void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
244 bool IsInternal,
245 bool IsInline,
246 llvm::GlobalValue *GV,
247 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000248 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000249 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000250 if (!ForDefinition) {
251 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000252 if (D->getAttr<DLLImportAttr>()) {
253 // The dllimport attribute is overridden by a subsequent declaration as
254 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000255 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000256 // dllimport attribute can be applied only to function decls, not to
257 // definitions.
258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 if (!FD->getBody())
260 GV->setLinkage(llvm::Function::DLLImportLinkage);
261 } else
262 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000263 }
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000264 } else if (D->getAttr<WeakAttr>())
265 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000266 } else {
267 if (IsInternal) {
268 GV->setLinkage(llvm::Function::InternalLinkage);
269 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000270 if (D->getAttr<DLLExportAttr>()) {
271 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
272 // The dllexport attribute is ignored for undefined symbols.
273 if (FD->getBody())
274 GV->setLinkage(llvm::Function::DLLExportLinkage);
275 } else
276 GV->setLinkage(llvm::Function::DLLExportLinkage);
277 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000278 GV->setLinkage(llvm::Function::WeakLinkage);
279 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000280 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000281
Daniel Dunbar49988882009-01-13 02:25:00 +0000282 // FIXME: Figure out the relative priority of the attribute,
283 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000284 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000285 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000286 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000287
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000288 // Prefaced with special LLVM marker to indicate that the name
289 // should not be munged.
290 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
Daniel Dunbara735ad82008-08-06 00:03:29 +0000291 GV->setName("\01" + ALA->getLabel());
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000292
293 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
294 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000295
296 // Only add to llvm.used when we see a definition, otherwise we
297 // might add multiple times or risk the value being replaced by a
298 // subsequent RAUW.
299 if (ForDefinition) {
300 if (D->getAttr<UsedAttr>())
301 AddUsedGlobal(GV);
302 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000303}
304
Devang Patel761d7f72008-09-25 21:02:23 +0000305void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000306 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000307 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000308 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000309 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000310
Devang Patel761d7f72008-09-25 21:02:23 +0000311 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
312 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000313
314 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000315 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000316 F->setCallingConv(llvm::CallingConv::X86_FastCall);
317
318 if (D->getAttr<StdCallAttr>())
319 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000320}
321
322/// SetFunctionAttributesForDefinition - Set function attributes
323/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000324void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
325 llvm::Function *F) {
326 if (isa<ObjCMethodDecl>(D)) {
327 SetGlobalValueAttributes(D, true, false, F, true);
328 } else {
329 const FunctionDecl *FD = cast<FunctionDecl>(D);
330 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
331 FD->isInline(), F, true);
332 }
333
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000334 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000335 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000336
337 if (D->getAttr<AlwaysInlineAttr>())
338 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000339
340 if (D->getAttr<NoinlineAttr>())
341 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000342}
343
344void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
345 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000346 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000347
Daniel Dunbar219df662008-09-08 23:44:31 +0000348 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000349}
350
351void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
352 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000353 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000354
Daniel Dunbar219df662008-09-08 23:44:31 +0000355 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
356 FD->isInline(), F, false);
357}
358
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000359
Daniel Dunbar219df662008-09-08 23:44:31 +0000360void CodeGenModule::EmitAliases() {
361 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
362 const FunctionDecl *D = Aliases[i];
363 const AliasAttr *AA = D->getAttr<AliasAttr>();
364
365 // This is something of a hack, if the FunctionDecl got overridden
366 // then its attributes will be moved to the new declaration. In
367 // this case the current decl has no alias attribute, but we will
368 // eventually see it.
369 if (!AA)
370 continue;
371
372 const std::string& aliaseeName = AA->getAliasee();
373 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
374 if (!aliasee) {
375 // FIXME: This isn't unsupported, this is just an error, which
376 // sema should catch, but...
377 ErrorUnsupported(D, "alias referencing a missing function");
378 continue;
379 }
380
381 llvm::GlobalValue *GA =
382 new llvm::GlobalAlias(aliasee->getType(),
383 llvm::Function::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000384 getMangledName(D), aliasee,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000385 &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000386
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000387 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar219df662008-09-08 23:44:31 +0000388 if (Entry) {
389 // If we created a dummy function for this then replace it.
390 GA->takeName(Entry);
391
392 llvm::Value *Casted =
393 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
394 Entry->replaceAllUsesWith(Casted);
395 Entry->eraseFromParent();
396
397 Entry = GA;
398 }
399
400 // Alias should never be internal or inline.
401 SetGlobalValueAttributes(D, false, false, GA, true);
402 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000403}
404
Daniel Dunbar02698712009-02-13 20:29:50 +0000405void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
406 assert(!GV->isDeclaration() &&
407 "Only globals with definition can force usage.");
408 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
409 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
410}
411
412void CodeGenModule::EmitLLVMUsed() {
413 // Don't create llvm.used if there is no need.
414 if (LLVMUsed.empty())
415 return;
416
417 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
418 LLVMUsed.size());
419 llvm::GlobalVariable *GV =
420 new llvm::GlobalVariable(ATy, false,
421 llvm::GlobalValue::AppendingLinkage,
422 llvm::ConstantArray::get(ATy, LLVMUsed),
423 "llvm.used", &getModule());
424
425 GV->setSection("llvm.metadata");
426}
427
428void CodeGenModule::EmitDeferred() {
429 // Emit code for any deferred decl which was used. Since a
430 // previously unused static decl may become used during the
431 // generation of code for a static function, iterate until no
432 // changes are made.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000433 bool Changed;
434 do {
435 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000436
Daniel Dunbar02698712009-02-13 20:29:50 +0000437 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
438 e = DeferredDecls.end(); i != e; ) {
Anders Carlssonb723f752009-01-04 02:08:04 +0000439 const ValueDecl *D = *i;
440
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000441 // Check if we have used a decl with the same name
442 // FIXME: The AST should have some sort of aggregate decls or
443 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000444 // FIXME: This is missing some important cases. For example, we
Daniel Dunbar73241df2009-02-13 21:18:01 +0000445 // need to check for uses in an alias.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000446 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000447 ++i;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000448 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000449 }
450
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000451 // Emit the definition.
452 EmitGlobalDefinition(D);
453
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000454 // Erase the used decl from the list.
Daniel Dunbar02698712009-02-13 20:29:50 +0000455 i = DeferredDecls.erase(i);
Anders Carlssonb723f752009-01-04 02:08:04 +0000456
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000457 // Remember that we made a change.
458 Changed = true;
459 }
460 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461}
462
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000463/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
464/// annotation information for a given GlobalValue. The annotation struct is
465/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000466/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000467/// created from the AnnotateAttr's annotation. The third field is a constant
468/// string containing the name of the translation unit. The fourth field is
469/// the line number in the file of the annotated value declaration.
470///
471/// FIXME: this does not unique the annotation string constants, as llvm-gcc
472/// appears to.
473///
474llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
475 const AnnotateAttr *AA,
476 unsigned LineNo) {
477 llvm::Module *M = &getModule();
478
479 // get [N x i8] constants for the annotation string, and the filename string
480 // which are the 2nd and 3rd elements of the global annotation structure.
481 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
482 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
483 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
484 true);
485
486 // Get the two global values corresponding to the ConstantArrays we just
487 // created to hold the bytes of the strings.
488 llvm::GlobalValue *annoGV =
489 new llvm::GlobalVariable(anno->getType(), false,
490 llvm::GlobalValue::InternalLinkage, anno,
491 GV->getName() + ".str", M);
492 // translation unit name string, emitted into the llvm.metadata section.
493 llvm::GlobalValue *unitGV =
494 new llvm::GlobalVariable(unit->getType(), false,
495 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
496
497 // Create the ConstantStruct that is the global annotion.
498 llvm::Constant *Fields[4] = {
499 llvm::ConstantExpr::getBitCast(GV, SBP),
500 llvm::ConstantExpr::getBitCast(annoGV, SBP),
501 llvm::ConstantExpr::getBitCast(unitGV, SBP),
502 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
503 };
504 return llvm::ConstantStruct::get(Fields, 4, false);
505}
506
Daniel Dunbar73241df2009-02-13 21:18:01 +0000507bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000508 // Never defer when EmitAllDecls is specified or the decl has
509 // attribute used.
510 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000511 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000512
513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000514 // Constructors and destructors should never be deferred.
515 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
516 return false;
517
518 if (FD->getStorageClass() != FunctionDecl::Static)
519 return false;
520 } else {
521 const VarDecl *VD = cast<VarDecl>(Global);
522 assert(VD->isFileVarDecl() && "Invalid decl.");
523
524 if (VD->getStorageClass() != VarDecl::Static)
525 return false;
526 }
527
528 return true;
529}
530
531void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
532 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000533 // Aliases are deferred until code for everything else has been
534 // emitted.
535 if (FD->getAttr<AliasAttr>()) {
536 assert(!FD->isThisDeclarationADefinition() &&
537 "Function alias cannot have a definition!");
538 Aliases.push_back(FD);
539 return;
540 }
541
Daniel Dunbar73241df2009-02-13 21:18:01 +0000542 // Forward declarations are emitted lazily on first use.
543 if (!FD->isThisDeclarationADefinition())
544 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000545 } else {
546 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000547 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
548
Daniel Dunbar73241df2009-02-13 21:18:01 +0000549 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000550 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000551 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000552 }
553
Daniel Dunbar73241df2009-02-13 21:18:01 +0000554 // Defer code generation when possible.
555 if (MayDeferGeneration(Global)) {
Daniel Dunbar02698712009-02-13 20:29:50 +0000556 DeferredDecls.push_back(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000557 return;
558 }
559
560 // Otherwise emit the definition.
561 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000562}
563
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000564void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
565 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
566 EmitGlobalFunctionDefinition(FD);
567 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
568 EmitGlobalVarDefinition(VD);
569 } else {
570 assert(0 && "Invalid argument to EmitGlobalDefinition()");
571 }
572}
573
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000574 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000575 assert(D->hasGlobalStorage() && "Not a global variable");
576
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000577 QualType ASTTy = D->getType();
578 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000579 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000580
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000581 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000582 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar49988882009-01-13 02:25:00 +0000583 if (!Entry) {
584 llvm::GlobalVariable *GV =
585 new llvm::GlobalVariable(Ty, false,
586 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000587 0, getMangledName(D), &getModule(),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000588 0, ASTTy.getAddressSpace());
Daniel Dunbar49988882009-01-13 02:25:00 +0000589 Entry = GV;
590
591 // Handle things which are present even on external declarations.
592
593 // FIXME: This code is overly simple and should be merged with
594 // other global handling.
595
596 GV->setConstant(D->getType().isConstant(Context));
597
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000598 // FIXME: Merge with other attribute handling code.
599
Daniel Dunbar49988882009-01-13 02:25:00 +0000600 if (D->getStorageClass() == VarDecl::PrivateExtern)
601 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000602
603 if (D->getAttr<WeakAttr>())
604 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Daniel Dunbar3f75c432009-03-04 17:31:19 +0000605
606 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
607 // Prefaced with special LLVM marker to indicate that the name
608 // should not be munged.
609 GV->setName("\01" + ALA->getLabel());
610 }
Daniel Dunbar49988882009-01-13 02:25:00 +0000611 }
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000612
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000613 // Make sure the result is of the correct type.
614 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000615}
616
617void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000618 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000619 QualType ASTTy = D->getType();
620 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000621
Chris Lattner8f32f712007-07-14 00:23:28 +0000622 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000623 // This is a tentative definition; tentative definitions are
624 // implicitly initialized with { 0 }
625 const llvm::Type* InitTy;
626 if (ASTTy->isIncompleteArrayType()) {
627 // An incomplete array is normally [ TYPE x 0 ], but we need
628 // to fix it to [ TYPE x 1 ].
629 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
630 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
631 } else {
632 InitTy = VarTy;
633 }
634 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000635 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000636 Init = EmitConstantExpr(D->getInit());
Eli Friedman6e656f42009-02-20 01:18:21 +0000637 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000638 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000639 QualType T = D->getInit()->getType();
640 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
641 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000642 }
643 const llvm::Type* InitType = Init->getType();
644
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000645 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000646 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
647
Eli Friedman77ba7082008-05-30 19:50:47 +0000648 if (!GV) {
649 GV = new llvm::GlobalVariable(InitType, false,
650 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000651 0, getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000652 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar232350d2009-02-19 05:36:41 +0000653
654 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
655 // If we already have this global and it has an initializer, then
656 // we are in the rare situation where we emitted the defining
657 // declaration of the global and are now being asked to emit a
658 // definition which would be common. This occurs, for example, in
659 // the following situation because statics can be emitted out of
660 // order:
661 //
662 // static int x;
663 // static int *y = &x;
664 // static int x = 10;
665 // int **z = &y;
666 //
667 // Bail here so we don't blow away the definition. Note that if we
668 // can't distinguish here if we emitted a definition with a null
669 // initializer, but this case is safe.
670 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
671 return;
672
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000673 } else if (GV->getType() !=
674 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000675 // We have a definition after a prototype with the wrong type.
676 // We must make a new GlobalVariable* and update everything that used OldGV
677 // (a declaration or tentative definition) with the new GlobalVariable*
678 // (which will be a definition).
679 //
680 // This happens if there is a prototype for a global (e.g. "extern int x[];")
681 // and then a definition of a different type (e.g. "int x[10];"). This also
682 // happens when an initializer has a different type from the type of the
683 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000684 //
685 // FIXME: This also ends up happening if there's a definition followed by
686 // a tentative definition! (Although Sema rejects that construct
687 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000688
689 // Save the old global
690 llvm::GlobalVariable *OldGV = GV;
691
692 // Make a new global with the correct type
693 GV = new llvm::GlobalVariable(InitType, false,
694 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000695 0, getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000696 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman77ba7082008-05-30 19:50:47 +0000697 // Steal the name of the old global
698 GV->takeName(OldGV);
699
700 // Replace all uses of the old global with the new global
701 llvm::Constant *NewPtrForOldDecl =
702 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
703 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000704
705 // Erase the old global, since it is no longer used.
706 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000707 }
Devang Patel8e53e722007-10-26 16:31:40 +0000708
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000709 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000710
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000711 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
712 SourceManager &SM = Context.getSourceManager();
713 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000714 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000715 }
716
Chris Lattner88a69ad2007-07-13 05:13:43 +0000717 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000718 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000719 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000720
Chris Lattnerddee4232008-03-03 03:28:21 +0000721 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000722 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000723 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000724
725 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
726 // Prefaced with special LLVM marker to indicate that the name
727 // should not be munged.
728 GV->setName("\01" + ALA->getLabel());
729 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000730
731 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000732 if (D->getStorageClass() == VarDecl::Static)
733 GV->setLinkage(llvm::Function::InternalLinkage);
734 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000735 GV->setLinkage(llvm::Function::DLLImportLinkage);
736 else if (D->getAttr<DLLExportAttr>())
737 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000738 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000739 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000740 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000741 // FIXME: This isn't right. This should handle common linkage and other
742 // stuff.
743 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000744 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000745 case VarDecl::Auto:
746 case VarDecl::Register:
747 assert(0 && "Can't have auto or register globals");
748 case VarDecl::None:
749 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000750 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000751 else
752 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000753 break;
754 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000755 // FIXME: common
756 break;
757
Chris Lattnerddee4232008-03-03 03:28:21 +0000758 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000759 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
760 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000761 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000762 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000763 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000764
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000765 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
766 GV->setSection(SA->getName());
767
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000768 if (D->getAttr<UsedAttr>())
769 AddUsedGlobal(GV);
770
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000771 // Emit global variable debug information.
772 CGDebugInfo *DI = getDebugInfo();
773 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000774 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000775 DI->EmitGlobalVariable(GV, D);
776 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000777}
Reid Spencer5f016e22007-07-11 17:01:13 +0000778
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000779llvm::GlobalValue *
Daniel Dunbard5d31802009-02-19 07:15:39 +0000780CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
781 const llvm::Type *Ty) {
Eli Friedman2136b2e2009-03-05 04:18:07 +0000782 bool DoSetAttributes = true;
783 if (!Ty) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000784 Ty = getTypes().ConvertType(D->getType());
Eli Friedman2136b2e2009-03-05 04:18:07 +0000785 if (!isa<llvm::FunctionType>(Ty)) {
786 // This function doesn't have a complete type (for example, the return
787 // type is an incomplete struct). Use a fake type instead, and make
788 // sure not to try to set attributes.
789 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
790 std::vector<const llvm::Type*>(), false);
791 DoSetAttributes = false;
792 }
793 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000794 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
795 llvm::Function::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000796 getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000797 &getModule());
Eli Friedman2136b2e2009-03-05 04:18:07 +0000798 if (DoSetAttributes)
799 SetFunctionAttributes(D, F);
Daniel Dunbar219df662008-09-08 23:44:31 +0000800 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000801}
802
803llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000804 QualType ASTTy = D->getType();
805 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
806 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000807
808 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000809 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000810 if (!Entry)
Daniel Dunbard5d31802009-02-19 07:15:39 +0000811 Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000812
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000813 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000814}
815
816void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000817 const llvm::FunctionType *Ty =
818 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
819
820 // As a special case, make sure that definitions of K&R function
821 // "type foo()" aren't declared as varargs (which forces the backend
822 // to do unnecessary work).
823 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
824 Ty = llvm::FunctionType::get(Ty->getReturnType(),
825 std::vector<const llvm::Type*>(),
826 false);
827
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000828 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000829 if (!Entry) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000830 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000831 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000832 // If the types mismatch then we have to rewrite the definition.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000833 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000834 // Otherwise, we have a definition after a prototype with the
835 // wrong type. F is the Function* for the one with the wrong
836 // type, we must make a new Function* and update everything that
837 // used F (a declaration) with the new Function* (which will be
838 // a definition).
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000839 //
Daniel Dunbard5d31802009-02-19 07:15:39 +0000840 // This happens if there is a prototype for a function
841 // (e.g. "int f()") and then a definition of a different type
842 // (e.g. "int f(int x)"). Start by making a new function of the
843 // correct type, RAUW, then steal the name.
844 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000845 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000846
847 // Replace uses of F with the Function we will endow with a body.
848 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000849 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
850 Entry->replaceAllUsesWith(NewPtrForOldDecl);
851
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000852 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000853 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000854 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000855
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000856 Entry = NewFn;
857 }
858 }
859
Daniel Dunbar219df662008-09-08 23:44:31 +0000860 llvm::Function *Fn = cast<llvm::Function>(Entry);
861 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000862
Daniel Dunbar219df662008-09-08 23:44:31 +0000863 SetFunctionAttributesForDefinition(D, Fn);
864
865 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
866 AddGlobalCtor(Fn, CA->getPriority());
867 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
868 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000869 }
870}
871
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000872llvm::Function *
873CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
874 const std::string &Name) {
875 llvm::Function *Fn = llvm::Function::Create(FTy,
876 llvm::Function::ExternalLinkage,
877 "", &TheModule);
878 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
879 return Fn;
880}
881
Chris Lattnerc5b88062008-02-06 05:08:19 +0000882void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
883 // Make sure that this type is translated.
884 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000885}
886
887
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000888/// getBuiltinLibFunction
Mike Stumpc136e6c2009-02-27 22:42:30 +0000889llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000890 if (BuiltinID > BuiltinFunctions.size())
891 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000892
Chris Lattner1426fec2007-12-13 00:38:03 +0000893 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
894 // a slot for it.
895 assert(BuiltinID && "Invalid Builtin ID");
Mike Stumpc136e6c2009-02-27 22:42:30 +0000896 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000897 if (FunctionSlot)
898 return FunctionSlot;
899
Douglas Gregor3e41d602009-02-13 23:20:09 +0000900 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
901 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
902 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000903
Douglas Gregor3e41d602009-02-13 23:20:09 +0000904 // Get the name, skip over the __builtin_ prefix (if necessary).
905 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
906 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
907 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000908
909 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000910 Builtin::Context::GetBuiltinTypeError Error;
911 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
912 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
913
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000914 const llvm::FunctionType *Ty =
915 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
916
917 // FIXME: This has a serious problem with code like this:
918 // void abs() {}
919 // ... __builtin_abs(x);
920 // The two versions of abs will collide. The fix is for the builtin to win,
921 // and for the existing one to be turned into a constantexpr cast of the
922 // builtin. In the case where the existing one is a static function, it
923 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000924 if (llvm::Function *Existing = getModule().getFunction(Name)) {
925 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
926 return FunctionSlot = Existing;
927 assert(Existing == 0 && "FIXME: Name collision");
928 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000929
Chris Lattner4667c4a2009-03-01 18:47:06 +0000930 llvm::GlobalValue *&ExistingFn =
931 GlobalDeclMap[getContext().Idents.get(Name).getName()];
932 if (ExistingFn)
933 return FunctionSlot = llvm::ConstantExpr::getBitCast(ExistingFn, Ty);
Mike Stumpc136e6c2009-02-27 22:42:30 +0000934
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000935 // FIXME: param attributes for sext/zext etc.
Chris Lattner4667c4a2009-03-01 18:47:06 +0000936 return FunctionSlot = ExistingFn =
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000937 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
938 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000939}
940
Chris Lattner7acda7c2007-12-18 00:25:38 +0000941llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
942 unsigned NumTys) {
943 return llvm::Intrinsic::getDeclaration(&getModule(),
944 (llvm::Intrinsic::ID)IID, Tys, NumTys);
945}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947llvm::Function *CodeGenModule::getMemCpyFn() {
948 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000949 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
950 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000951}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000952
Eli Friedman0c995092008-05-26 12:59:39 +0000953llvm::Function *CodeGenModule::getMemMoveFn() {
954 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000955 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
956 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000957}
958
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000959llvm::Function *CodeGenModule::getMemSetFn() {
960 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000961 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
962 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000963}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000964
Anders Carlssone3daa762008-11-15 18:54:24 +0000965static void appendFieldAndPadding(CodeGenModule &CGM,
966 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000967 FieldDecl *FieldD, FieldDecl *NextFieldD,
968 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000969 RecordDecl* RD, const llvm::StructType *STy)
970{
971 // Append the field.
972 Fields.push_back(Field);
973
Douglas Gregor44b43212008-12-11 16:49:14 +0000974 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000975
976 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000977 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000978 NextStructFieldNo = STy->getNumElements();
979 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000980 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000981 }
982
983 // Append padding
984 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
985 llvm::Constant *C =
986 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
987
988 Fields.push_back(C);
989 }
990}
991
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000992// We still need to work out the details of handling UTF-16.
993// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000994llvm::Constant *CodeGenModule::
995GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000996 llvm::StringMapEntry<llvm::Constant *> &Entry =
997 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
998
999 if (Entry.getValue())
1000 return Entry.getValue();
1001
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001002 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1003 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001004
1005 if (!CFConstantStringClassRef) {
1006 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1007 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001008
1009 // FIXME: This is fairly broken if
1010 // __CFConstantStringClassReference is already defined, in that it
1011 // will get renamed and the user will most likely see an opaque
1012 // error message. This is a general issue with relying on
1013 // particular names.
1014 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001015 new llvm::GlobalVariable(Ty, false,
1016 llvm::GlobalVariable::ExternalLinkage, 0,
1017 "__CFConstantStringClassReference",
1018 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001019
1020 // Decay array -> ptr
1021 CFConstantStringClassRef =
1022 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001023 }
1024
Anders Carlssone3daa762008-11-15 18:54:24 +00001025 QualType CFTy = getContext().getCFConstantStringType();
1026 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001027
Anders Carlssone3daa762008-11-15 18:54:24 +00001028 const llvm::StructType *STy =
1029 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1030
1031 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +00001032 RecordDecl::field_iterator Field = CFRD->field_begin();
1033
Anders Carlssonc9e20912007-08-21 00:21:21 +00001034 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001035 FieldDecl *CurField = *Field++;
1036 FieldDecl *NextField = *Field++;
1037 appendFieldAndPadding(*this, Fields, CurField, NextField,
1038 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001039
1040 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001041 CurField = NextField;
1042 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001043 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001044 appendFieldAndPadding(*this, Fields, CurField, NextField,
1045 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001046
1047 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001048 CurField = NextField;
1049 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001050 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001051 C = new llvm::GlobalVariable(C->getType(), true,
1052 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +00001053 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +00001054 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +00001055 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1056 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001057
1058 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001059 CurField = NextField;
1060 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001061 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001062 appendFieldAndPadding(*this, Fields, CurField, NextField,
1063 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001064
1065 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001066 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +00001067 llvm::GlobalVariable *GV =
1068 new llvm::GlobalVariable(C->getType(), true,
1069 llvm::GlobalVariable::InternalLinkage,
1070 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001071
Anders Carlsson0c678292007-11-01 00:41:52 +00001072 GV->setSection("__DATA,__cfstring");
1073 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001074
Anders Carlsson0c678292007-11-01 00:41:52 +00001075 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001076}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001077
Daniel Dunbar61432932008-08-13 23:20:05 +00001078/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001079/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001080std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001081 const char *StrData = E->getStrData();
1082 unsigned Len = E->getByteLength();
1083
1084 const ConstantArrayType *CAT =
1085 getContext().getAsConstantArrayType(E->getType());
1086 assert(CAT && "String isn't pointer or array!");
1087
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001088 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001089 std::string Str(StrData, StrData+Len);
1090 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001091
1092 if (E->isWide())
1093 RealLen *= getContext().Target.getWCharWidth()/8;
1094
Daniel Dunbar1e049762008-08-10 20:25:57 +00001095 Str.resize(RealLen, '\0');
1096
1097 return Str;
1098}
1099
Daniel Dunbar61432932008-08-13 23:20:05 +00001100/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1101/// constant array for the given string literal.
1102llvm::Constant *
1103CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1104 // FIXME: This can be more efficient.
1105 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1106}
1107
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001108/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1109/// array for the given ObjCEncodeExpr node.
1110llvm::Constant *
1111CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1112 std::string Str;
1113 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1114
1115 llvm::Constant *C = llvm::ConstantArray::get(Str);
1116 C = new llvm::GlobalVariable(C->getType(), true,
1117 llvm::GlobalValue::InternalLinkage,
1118 C, ".str", &getModule());
1119 return C;
1120}
1121
1122
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001123/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001124static llvm::Constant *GenerateStringLiteral(const std::string &str,
1125 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001126 CodeGenModule &CGM,
1127 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001128 // Create Constant for this string literal. Don't add a '\0'.
1129 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001130
1131 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001132 return new llvm::GlobalVariable(C->getType(), constant,
1133 llvm::GlobalValue::InternalLinkage,
1134 C, GlobalName ? GlobalName : ".str",
1135 &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001136}
1137
Daniel Dunbar61432932008-08-13 23:20:05 +00001138/// GetAddrOfConstantString - Returns a pointer to a character array
1139/// containing the literal. This contents are exactly that of the
1140/// given string, i.e. it will not be null terminated automatically;
1141/// see GetAddrOfConstantCString. Note that whether the result is
1142/// actually a pointer to an LLVM constant depends on
1143/// Feature.WriteableStrings.
1144///
1145/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001146llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1147 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001148 // Don't share any string literals if writable-strings is turned on.
1149 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001150 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001151
1152 llvm::StringMapEntry<llvm::Constant *> &Entry =
1153 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1154
1155 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001156 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001157
1158 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001159 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001160 Entry.setValue(C);
1161 return C;
1162}
Daniel Dunbar61432932008-08-13 23:20:05 +00001163
1164/// GetAddrOfConstantCString - Returns a pointer to a character
1165/// array containing the literal and a terminating '\-'
1166/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001167llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1168 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001169 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001170}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001171
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001172/// EmitObjCPropertyImplementations - Emit information for synthesized
1173/// properties for an implementation.
1174void CodeGenModule::EmitObjCPropertyImplementations(const
1175 ObjCImplementationDecl *D) {
1176 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1177 e = D->propimpl_end(); i != e; ++i) {
1178 ObjCPropertyImplDecl *PID = *i;
1179
1180 // Dynamic is just for type-checking.
1181 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1182 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1183
1184 // Determine which methods need to be implemented, some may have
1185 // been overridden. Note that ::isSynthesized is not the method
1186 // we want, that just indicates if the decl came from a
1187 // property. What we want to know is if the method is defined in
1188 // this implementation.
1189 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001190 CodeGenFunction(*this).GenerateObjCGetter(
1191 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001192 if (!PD->isReadOnly() &&
1193 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001194 CodeGenFunction(*this).GenerateObjCSetter(
1195 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001196 }
1197 }
1198}
1199
Daniel Dunbar41071de2008-08-15 23:26:23 +00001200/// EmitTopLevelDecl - Emit code for a single top level declaration.
1201void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1202 // If an error has occurred, stop code generation, but continue
1203 // parsing and semantic analysis (to ensure all warnings and errors
1204 // are emitted).
1205 if (Diags.hasErrorOccurred())
1206 return;
1207
1208 switch (D->getKind()) {
1209 case Decl::Function:
1210 case Decl::Var:
1211 EmitGlobal(cast<ValueDecl>(D));
1212 break;
1213
1214 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001215 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001216 break;
1217
1218 // Objective-C Decls
1219
1220 // Forward declarations, no (immediate) code generation.
1221 case Decl::ObjCClass:
1222 case Decl::ObjCCategory:
1223 case Decl::ObjCForwardProtocol:
1224 case Decl::ObjCInterface:
1225 break;
1226
1227 case Decl::ObjCProtocol:
1228 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1229 break;
1230
1231 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001232 // Categories have properties but don't support synthesize so we
1233 // can ignore them here.
1234
Daniel Dunbar41071de2008-08-15 23:26:23 +00001235 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1236 break;
1237
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001238 case Decl::ObjCImplementation: {
1239 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1240 EmitObjCPropertyImplementations(OMD);
1241 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001242 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001243 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001244 case Decl::ObjCMethod: {
1245 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1246 // If this is not a prototype, emit the body.
1247 if (OMD->getBody())
1248 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1249 break;
1250 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001251 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001252 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001253 break;
1254
1255 case Decl::LinkageSpec: {
1256 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1257 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001258 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001259 // FIXME: implement C++ linkage, C linkage works mostly by C
1260 // language reuse already.
1261 break;
1262 }
1263
1264 case Decl::FileScopeAsm: {
1265 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1266 std::string AsmString(AD->getAsmString()->getStrData(),
1267 AD->getAsmString()->getByteLength());
1268
1269 const std::string &S = getModule().getModuleInlineAsm();
1270 if (S.empty())
1271 getModule().setModuleInlineAsm(AsmString);
1272 else
1273 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1274 break;
1275 }
1276
1277 default:
1278 // Make sure we handled everything we should, every other kind is
1279 // a non-top-level decl. FIXME: Would be nice to have an
1280 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1281 // that easily.
1282 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1283 }
1284}