blob: 93bf6dd8f00fc139fe8d8d39885b2b34d3b027ea [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
Chris Lattner3c8f1532009-03-21 07:12:05 +000041 if (!Features.ObjC1)
42 Runtime = 0;
43 else if (!Features.NeXTRuntime)
44 Runtime = CreateGNUObjCRuntime(*this);
45 else if (Features.ObjCNonFragileABI)
46 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
47 else
48 Runtime = CreateMacObjCRuntime(*this);
Sanjiv 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 Dunbarb681b8f2009-03-06 22:13:30 +000069 BindRuntimeGlobals();
Chris Lattner2b94fe32008-03-01 08:45:05 +000070}
Reid Spencer5f016e22007-07-11 17:01:13 +000071
Daniel Dunbarb681b8f2009-03-06 22:13:30 +000072void CodeGenModule::BindRuntimeGlobals() {
Daniel Dunbarf1968f22008-10-01 00:49:24 +000073 // Deal with protecting runtime function names.
Daniel Dunbarb681b8f2009-03-06 22:13:30 +000074 for (unsigned i = 0, e = RuntimeGlobals.size(); i < e; ++i) {
75 llvm::GlobalValue *GV = RuntimeGlobals[i].first;
76 const std::string &Name = RuntimeGlobals[i].second;
Daniel Dunbarf1968f22008-10-01 00:49:24 +000077
Daniel Dunbarb681b8f2009-03-06 22:13:30 +000078 // Discard unused runtime declarations.
79 if (GV->isDeclaration() && GV->use_empty()) {
80 GV->eraseFromParent();
Daniel Dunbar0293d542008-11-19 06:15:35 +000081 continue;
82 }
83
Chris Lattnere21c4b82009-03-21 07:48:31 +000084 // See if there is a conflict against a function by setting the name and
85 // seeing if we got the desired name.
86 GV->setName(Name);
87 if (GV->isName(Name.c_str()))
88 continue; // Yep, it worked!
89
90 GV->setName(""); // Zap the bogus name until we work out the conflict.
Daniel Dunbarb681b8f2009-03-06 22:13:30 +000091 llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name);
Chris Lattnere21c4b82009-03-21 07:48:31 +000092 assert(Conflict && "Must have conflicted!");
93
94 // Decide which version to take. If the conflict is a definition
95 // we are forced to take that, otherwise assume the runtime
96 // knows best.
Daniel Dunbarb681b8f2009-03-06 22:13:30 +000097
Chris Lattnere21c4b82009-03-21 07:48:31 +000098 // FIXME: This will fail phenomenally when the conflict is the
99 // wrong type of value. Just bail on it for now. This should
100 // really reuse something inside the LLVM Linker code.
101 assert(GV->getValueID() == Conflict->getValueID() &&
102 "Unable to resolve conflict between globals of different types.");
103 if (!Conflict->isDeclaration()) {
104 llvm::Value *Casted =
105 llvm::ConstantExpr::getBitCast(Conflict, GV->getType());
106 GV->replaceAllUsesWith(Casted);
107 GV->eraseFromParent();
108 } else {
109 GV->takeName(Conflict);
110 llvm::Value *Casted =
111 llvm::ConstantExpr::getBitCast(GV, Conflict->getType());
112 Conflict->replaceAllUsesWith(Casted);
113 Conflict->eraseFromParent();
114 }
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000115 }
116}
117
Daniel Dunbar488e9932008-08-16 00:56:44 +0000118/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000119/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000120void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
121 bool OmitOnError) {
122 if (OmitOnError && getDiags().hasErrorOccurred())
123 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000124 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000125 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000126 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000127 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
128 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000129}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000130
Daniel Dunbar488e9932008-08-16 00:56:44 +0000131/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000132/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000133void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
134 bool OmitOnError) {
135 if (OmitOnError && getDiags().hasErrorOccurred())
136 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000137 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000138 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000139 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000140 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000141}
142
Daniel Dunbar41071de2008-08-15 23:26:23 +0000143/// setGlobalVisibility - Set the visibility for the given LLVM
144/// GlobalValue according to the given clang AST visibility value.
145static void setGlobalVisibility(llvm::GlobalValue *GV,
146 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000147 switch (Vis) {
148 default: assert(0 && "Unknown visibility!");
149 case VisibilityAttr::DefaultVisibility:
150 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
151 break;
152 case VisibilityAttr::HiddenVisibility:
153 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
154 break;
155 case VisibilityAttr::ProtectedVisibility:
156 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
157 break;
158 }
159}
160
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000161/// \brief Retrieves the mangled name for the given declaration.
162///
163/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000164/// const char* containing the mangled name. Otherwise, returns
165/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000166///
167/// FIXME: Returning an IdentifierInfo* here is a total hack. We
168/// really need some kind of string abstraction that either stores a
169/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbarb5da3e92009-02-18 22:52:09 +0000170/// changes to the GlobalDeclMap, too. (I disagree, I think what we
171/// actually need is for Sema to provide some notion of which Decls
172/// refer to the same semantic decl. We shouldn't need to mangle the
173/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000174///
175/// FIXME: Performance here is going to be terribly until we start
176/// caching mangled names. However, we should fix the problem above
177/// first.
Douglas Gregor6ec36682009-02-18 23:53:56 +0000178const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000179 // In C, functions with no attributes never need to be mangled. Fastpath them.
180 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
181 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000182 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000183 }
184
Douglas Gregor6ec36682009-02-18 23:53:56 +0000185 llvm::SmallString<256> Name;
186 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000187 if (!mangleName(ND, Context, Out)) {
188 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000189 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000190 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000191
Douglas Gregor6ec36682009-02-18 23:53:56 +0000192 Name += '\0';
Chris Lattner3c8f1532009-03-21 07:12:05 +0000193 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000194}
195
Chris Lattner6d397602008-03-14 17:18:18 +0000196/// AddGlobalCtor - Add a function to the list that will be called before
197/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000198void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000199 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000200 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000201}
202
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000203/// AddGlobalDtor - Add a function to the list that will be called
204/// when the module is unloaded.
205void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000206 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000207 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
208}
209
210void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
211 // Ctor function type is void()*.
212 llvm::FunctionType* CtorFTy =
213 llvm::FunctionType::get(llvm::Type::VoidTy,
214 std::vector<const llvm::Type*>(),
215 false);
216 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
217
218 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000219 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000220 llvm::StructType::get(llvm::Type::Int32Ty,
221 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000222
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000223 // Construct the constructor and destructor arrays.
224 std::vector<llvm::Constant*> Ctors;
225 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
226 std::vector<llvm::Constant*> S;
227 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
228 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
229 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000230 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000231
232 if (!Ctors.empty()) {
233 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
234 new llvm::GlobalVariable(AT, false,
235 llvm::GlobalValue::AppendingLinkage,
236 llvm::ConstantArray::get(AT, Ctors),
237 GlobalName,
238 &TheModule);
239 }
Chris Lattner6d397602008-03-14 17:18:18 +0000240}
241
Nate Begeman532485c2008-04-18 23:43:57 +0000242void CodeGenModule::EmitAnnotations() {
243 if (Annotations.empty())
244 return;
245
246 // Create a new global variable for the ConstantStruct in the Module.
247 llvm::Constant *Array =
248 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
249 Annotations.size()),
250 Annotations);
251 llvm::GlobalValue *gv =
252 new llvm::GlobalVariable(Array->getType(), false,
253 llvm::GlobalValue::AppendingLinkage, Array,
254 "llvm.global.annotations", &TheModule);
255 gv->setSection("llvm.metadata");
256}
257
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000258void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
259 bool IsInternal,
260 bool IsInline,
261 llvm::GlobalValue *GV,
262 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000263 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000264 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000265 if (!ForDefinition) {
266 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000267 if (D->getAttr<DLLImportAttr>()) {
268 // The dllimport attribute is overridden by a subsequent declaration as
269 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000270 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000271 // dllimport attribute can be applied only to function decls, not to
272 // definitions.
273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
274 if (!FD->getBody())
275 GV->setLinkage(llvm::Function::DLLImportLinkage);
276 } else
277 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000278 }
Daniel Dunbar5e273142009-03-06 16:20:49 +0000279 } else if (D->getAttr<WeakAttr>() ||
280 D->getAttr<WeakImportAttr>()) {
281 // "extern_weak" is overloaded in LLVM; we probably should have
282 // separate linkage types for this.
Duncan Sandse3fedbe2009-03-11 08:40:02 +0000283 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000284 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000285 } else {
286 if (IsInternal) {
287 GV->setLinkage(llvm::Function::InternalLinkage);
288 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000289 if (D->getAttr<DLLExportAttr>()) {
290 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
291 // The dllexport attribute is ignored for undefined symbols.
292 if (FD->getBody())
293 GV->setLinkage(llvm::Function::DLLExportLinkage);
294 } else
295 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000296 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
297 IsInline)
Mike Stump286acbd2009-03-07 16:33:28 +0000298 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000299 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000300 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000301
Daniel Dunbar49988882009-01-13 02:25:00 +0000302 // FIXME: Figure out the relative priority of the attribute,
303 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000304 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000305 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000306 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000307
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000308 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
309 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000310
311 // Only add to llvm.used when we see a definition, otherwise we
312 // might add multiple times or risk the value being replaced by a
313 // subsequent RAUW.
314 if (ForDefinition) {
315 if (D->getAttr<UsedAttr>())
316 AddUsedGlobal(GV);
317 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000318}
319
Devang Patel761d7f72008-09-25 21:02:23 +0000320void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000321 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000322 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000323 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000324 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000325
Devang Patel761d7f72008-09-25 21:02:23 +0000326 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
327 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000328
329 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000330 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000331 F->setCallingConv(llvm::CallingConv::X86_FastCall);
332
333 if (D->getAttr<StdCallAttr>())
334 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000335}
336
337/// SetFunctionAttributesForDefinition - Set function attributes
338/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000339void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
340 llvm::Function *F) {
341 if (isa<ObjCMethodDecl>(D)) {
342 SetGlobalValueAttributes(D, true, false, F, true);
343 } else {
344 const FunctionDecl *FD = cast<FunctionDecl>(D);
345 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
346 FD->isInline(), F, true);
347 }
348
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000349 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000350 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000351
352 if (D->getAttr<AlwaysInlineAttr>())
353 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000354
355 if (D->getAttr<NoinlineAttr>())
356 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000357}
358
359void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
360 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000361 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000362
Daniel Dunbar219df662008-09-08 23:44:31 +0000363 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000364}
365
366void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
367 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000368 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000369
Daniel Dunbar219df662008-09-08 23:44:31 +0000370 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
371 FD->isInline(), F, false);
372}
373
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000374
Daniel Dunbar219df662008-09-08 23:44:31 +0000375void CodeGenModule::EmitAliases() {
376 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000377 const ValueDecl *D = Aliases[i];
Daniel Dunbar219df662008-09-08 23:44:31 +0000378 const AliasAttr *AA = D->getAttr<AliasAttr>();
379
380 // This is something of a hack, if the FunctionDecl got overridden
381 // then its attributes will be moved to the new declaration. In
382 // this case the current decl has no alias attribute, but we will
383 // eventually see it.
384 if (!AA)
385 continue;
386
387 const std::string& aliaseeName = AA->getAliasee();
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000388 llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName);
Daniel Dunbar219df662008-09-08 23:44:31 +0000389 if (!aliasee) {
390 // FIXME: This isn't unsupported, this is just an error, which
391 // sema should catch, but...
392 ErrorUnsupported(D, "alias referencing a missing function");
393 continue;
394 }
395
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000396 const char *MangledName = getMangledName(D);
Daniel Dunbar219df662008-09-08 23:44:31 +0000397 llvm::GlobalValue *GA =
398 new llvm::GlobalAlias(aliasee->getType(),
399 llvm::Function::ExternalLinkage,
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000400 MangledName, aliasee, &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000401
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000402 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Daniel Dunbar219df662008-09-08 23:44:31 +0000403 if (Entry) {
404 // If we created a dummy function for this then replace it.
405 GA->takeName(Entry);
406
407 llvm::Value *Casted =
408 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
409 Entry->replaceAllUsesWith(Casted);
410 Entry->eraseFromParent();
411
412 Entry = GA;
413 }
414
415 // Alias should never be internal or inline.
416 SetGlobalValueAttributes(D, false, false, GA, true);
417 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000418}
419
Daniel Dunbar02698712009-02-13 20:29:50 +0000420void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
421 assert(!GV->isDeclaration() &&
422 "Only globals with definition can force usage.");
423 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
424 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
425}
426
427void CodeGenModule::EmitLLVMUsed() {
428 // Don't create llvm.used if there is no need.
429 if (LLVMUsed.empty())
430 return;
431
432 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
433 LLVMUsed.size());
434 llvm::GlobalVariable *GV =
435 new llvm::GlobalVariable(ATy, false,
436 llvm::GlobalValue::AppendingLinkage,
437 llvm::ConstantArray::get(ATy, LLVMUsed),
438 "llvm.used", &getModule());
439
440 GV->setSection("llvm.metadata");
441}
442
443void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000444 // Emit code for any potentially referenced deferred decls. Since a
445 // previously unused static decl may become used during the generation of code
446 // for a static function, iterate until no changes are made.
447 while (!DeferredDeclsToEmit.empty()) {
448 const ValueDecl *D = DeferredDeclsToEmit.back();
449 DeferredDeclsToEmit.pop_back();
450
451 // The mangled name for the decl must have been emitted in GlobalDeclMap.
452 // Look it up to see if it was defined with a stronger definition (e.g. an
453 // extern inline function with a strong function redefinition). If so,
454 // just ignore the deferred decl.
455 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
456 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000457
Chris Lattner67b00522009-03-21 09:44:56 +0000458 if (!CGRef->isDeclaration())
459 continue;
460
461 // Otherwise, emit the definition and move on to the next one.
462 EmitGlobalDefinition(D);
463 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000464}
465
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000466/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
467/// annotation information for a given GlobalValue. The annotation struct is
468/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000469/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000470/// created from the AnnotateAttr's annotation. The third field is a constant
471/// string containing the name of the translation unit. The fourth field is
472/// the line number in the file of the annotated value declaration.
473///
474/// FIXME: this does not unique the annotation string constants, as llvm-gcc
475/// appears to.
476///
477llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
478 const AnnotateAttr *AA,
479 unsigned LineNo) {
480 llvm::Module *M = &getModule();
481
482 // get [N x i8] constants for the annotation string, and the filename string
483 // which are the 2nd and 3rd elements of the global annotation structure.
484 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
485 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
486 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
487 true);
488
489 // Get the two global values corresponding to the ConstantArrays we just
490 // created to hold the bytes of the strings.
491 llvm::GlobalValue *annoGV =
492 new llvm::GlobalVariable(anno->getType(), false,
493 llvm::GlobalValue::InternalLinkage, anno,
494 GV->getName() + ".str", M);
495 // translation unit name string, emitted into the llvm.metadata section.
496 llvm::GlobalValue *unitGV =
497 new llvm::GlobalVariable(unit->getType(), false,
498 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
499
500 // Create the ConstantStruct that is the global annotion.
501 llvm::Constant *Fields[4] = {
502 llvm::ConstantExpr::getBitCast(GV, SBP),
503 llvm::ConstantExpr::getBitCast(annoGV, SBP),
504 llvm::ConstantExpr::getBitCast(unitGV, SBP),
505 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
506 };
507 return llvm::ConstantStruct::get(Fields, 4, false);
508}
509
Daniel Dunbar73241df2009-02-13 21:18:01 +0000510bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000511 // Never defer when EmitAllDecls is specified or the decl has
512 // attribute used.
513 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000514 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000515
516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000517 // Constructors and destructors should never be deferred.
518 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
519 return false;
520
Chris Lattner99b53612009-03-21 08:03:33 +0000521 // FIXME: What about inline, and/or extern inline?
Daniel Dunbar73241df2009-02-13 21:18:01 +0000522 if (FD->getStorageClass() != FunctionDecl::Static)
523 return false;
524 } else {
525 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner99b53612009-03-21 08:03:33 +0000526 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbar73241df2009-02-13 21:18:01 +0000527
528 if (VD->getStorageClass() != VarDecl::Static)
529 return false;
530 }
531
532 return true;
533}
534
535void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000536 // Aliases are deferred until code for everything else has been
537 // emitted.
538 if (Global->getAttr<AliasAttr>()) {
539 Aliases.push_back(Global);
540 return;
541 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000542
Chris Lattner67b00522009-03-21 09:44:56 +0000543 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000544 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000545 // Forward declarations are emitted lazily on first use.
546 if (!FD->isThisDeclarationADefinition())
547 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000548 } else {
549 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000550 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
551
Daniel Dunbar73241df2009-02-13 21:18:01 +0000552 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000553 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000554 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000555 }
556
Chris Lattner67b00522009-03-21 09:44:56 +0000557 // Defer code generation when possible if this is a static definition, inline
558 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000559 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000560 // If the value has already been used, add it directly to the
561 // DeferredDeclsToEmit list.
562 const char *MangledName = getMangledName(Global);
563 if (GlobalDeclMap.count(MangledName))
564 DeferredDeclsToEmit.push_back(Global);
565 else {
566 // Otherwise, remember that we saw a deferred decl with this name. The
567 // first use of the mangled name will cause it to move into
568 // DeferredDeclsToEmit.
569 DeferredDecls[MangledName] = Global;
570 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000571 return;
572 }
573
574 // Otherwise emit the definition.
575 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000576}
577
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000578void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
579 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
580 EmitGlobalFunctionDefinition(FD);
581 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
582 EmitGlobalVarDefinition(VD);
583 } else {
584 assert(0 && "Invalid argument to EmitGlobalDefinition()");
585 }
586}
587
Chris Lattner0558e792009-03-21 09:25:43 +0000588/// GetAddrOfFunction - Return the address of the given function. If Ty is
589/// non-null, then this function will use the specified type if it has to
590/// create it (this occurs when we see a definition of the function).
591llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
592 const llvm::Type *Ty) {
593 // If there was no specific requested type, just convert it now.
594 if (!Ty)
595 Ty = getTypes().ConvertType(D->getType());
596
597 // Lookup the entry, lazily creating it if necessary.
598 const char *MangledName = getMangledName(D);
599 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
600 if (Entry) {
601 if (Entry->getType()->getElementType() == Ty)
602 return Entry;
603
604 // Make sure the result is of the correct type.
605 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
606 return llvm::ConstantExpr::getBitCast(Entry, PTy);
607 }
608
Chris Lattner67b00522009-03-21 09:44:56 +0000609 // This is the first use or definition of a mangled name. If there is a
610 // deferred decl with this name, remember that we need to emit it at the end
611 // of the file.
612 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
613 DeferredDecls.find(MangledName);
614 if (DDI != DeferredDecls.end()) {
615 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
616 // list, and remove it from DeferredDecls (since we don't need it anymore).
617 DeferredDeclsToEmit.push_back(DDI->second);
618 DeferredDecls.erase(DDI);
619 }
620
621
Chris Lattner0558e792009-03-21 09:25:43 +0000622 // This function doesn't have a complete type (for example, the return
623 // type is an incomplete struct). Use a fake type instead, and make
624 // sure not to try to set attributes.
625 bool ShouldSetAttributes = true;
626 if (!isa<llvm::FunctionType>(Ty)) {
627 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
628 std::vector<const llvm::Type*>(), false);
629 ShouldSetAttributes = false;
630 }
631 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
632 llvm::Function::ExternalLinkage,
633 MangledName, &getModule());
634 if (ShouldSetAttributes)
635 SetFunctionAttributes(D, F);
636 Entry = F;
637 return F;
638}
639
Chris Lattner570585c2009-03-21 09:16:30 +0000640/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
641/// given global variable. If Ty is non-null and if the global doesn't exist,
642/// then it will be greated with the specified type instead of whatever the
643/// normal requested type would be.
644llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
645 const llvm::Type *Ty) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000646 assert(D->hasGlobalStorage() && "Not a global variable");
647
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000648 QualType ASTTy = D->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000649 if (Ty == 0)
650 Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000651
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000652 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000653 const char *MangledName = getMangledName(D);
654 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000655 if (Entry) {
Chris Lattner570585c2009-03-21 09:16:30 +0000656 if (Entry->getType()->getElementType() == Ty &&
657 Entry->getType()->getAddressSpace() == ASTTy.getAddressSpace())
658 return Entry;
659
Chris Lattner99b53612009-03-21 08:03:33 +0000660 // Make sure the result is of the correct type.
Chris Lattner570585c2009-03-21 09:16:30 +0000661 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
662 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar49988882009-01-13 02:25:00 +0000663 }
Chris Lattner67b00522009-03-21 09:44:56 +0000664
665 // This is the first use or definition of a mangled name. If there is a
666 // deferred decl with this name, remember that we need to emit it at the end
667 // of the file.
668 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
669 DeferredDecls.find(MangledName);
670 if (DDI != DeferredDecls.end()) {
671 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
672 // list, and remove it from DeferredDecls (since we don't need it anymore).
673 DeferredDeclsToEmit.push_back(DDI->second);
674 DeferredDecls.erase(DDI);
675 }
676
Chris Lattner99b53612009-03-21 08:03:33 +0000677 llvm::GlobalVariable *GV =
678 new llvm::GlobalVariable(Ty, false,
679 llvm::GlobalValue::ExternalLinkage,
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000680 0, MangledName, &getModule(),
Chris Lattner99b53612009-03-21 08:03:33 +0000681 0, ASTTy.getAddressSpace());
682
683 // Handle things which are present even on external declarations.
684
685 // FIXME: This code is overly simple and should be merged with
686 // other global handling.
687
688 GV->setConstant(D->getType().isConstant(Context));
689
690 // FIXME: Merge with other attribute handling code.
691
692 if (D->getStorageClass() == VarDecl::PrivateExtern)
693 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
694
695 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
696 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
697
Chris Lattner99b53612009-03-21 08:03:33 +0000698 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000699}
700
701void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000702 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000703 QualType ASTTy = D->getType();
Eli Friedman77ba7082008-05-30 19:50:47 +0000704
Chris Lattner8f32f712007-07-14 00:23:28 +0000705 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000706 // This is a tentative definition; tentative definitions are
707 // implicitly initialized with { 0 }
Chris Lattner570585c2009-03-21 09:16:30 +0000708 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000709 if (ASTTy->isIncompleteArrayType()) {
710 // An incomplete array is normally [ TYPE x 0 ], but we need
711 // to fix it to [ TYPE x 1 ].
Chris Lattner570585c2009-03-21 09:16:30 +0000712 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000713 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000714 }
715 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000716 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000717 Init = EmitConstantExpr(D->getInit());
Eli Friedman6e656f42009-02-20 01:18:21 +0000718 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000719 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000720 QualType T = D->getInit()->getType();
721 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
722 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000723 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000724
Chris Lattner2d584062009-03-21 08:13:05 +0000725 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000726 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000727
Chris Lattner570585c2009-03-21 09:16:30 +0000728 // Strip off a bitcast if we got one back.
729 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
730 assert(CE->getOpcode() == llvm::Instruction::BitCast);
731 Entry = CE->getOperand(0);
732 }
733
734 // Entry is now either a Function or GlobalVariable.
735 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
736
737 // If we already have this global and it has an initializer, then
738 // we are in the rare situation where we emitted the defining
739 // declaration of the global and are now being asked to emit a
740 // definition which would be common. This occurs, for example, in
741 // the following situation because statics can be emitted out of
742 // order:
743 //
744 // static int x;
745 // static int *y = &x;
746 // static int x = 10;
747 // int **z = &y;
748 //
749 // Bail here so we don't blow away the definition. Note that if we
750 // can't distinguish here if we emitted a definition with a null
751 // initializer, but this case is safe.
752 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000753 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
754 return;
Chris Lattner570585c2009-03-21 09:16:30 +0000755 }
756
757 // We have a definition after a declaration with the wrong type.
758 // We must make a new GlobalVariable* and update everything that used OldGV
759 // (a declaration or tentative definition) with the new GlobalVariable*
760 // (which will be a definition).
761 //
762 // This happens if there is a prototype for a global (e.g.
763 // "extern int x[];") and then a definition of a different type (e.g.
764 // "int x[10];"). This also happens when an initializer has a different type
765 // from the type of the global (this happens with unions).
766 //
767 // FIXME: This also ends up happening if there's a definition followed by
768 // a tentative definition! (Although Sema rejects that construct
769 // at the moment.)
770 if (GV == 0 ||
771 GV->getType()->getElementType() != InitType ||
772 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
773
774 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
775 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000776
Chris Lattner570585c2009-03-21 09:16:30 +0000777 // Make a new global with the correct type, this is now guaranteed to work.
778 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000779 GV->takeName(cast<llvm::GlobalValue>(Entry));
780
Eli Friedman77ba7082008-05-30 19:50:47 +0000781 // Replace all uses of the old global with the new global
782 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000783 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
784 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000785
786 // Erase the old global, since it is no longer used.
Chris Lattner2d584062009-03-21 08:13:05 +0000787 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattner570585c2009-03-21 09:16:30 +0000788 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000789 }
Devang Patel8e53e722007-10-26 16:31:40 +0000790
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000791 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
792 SourceManager &SM = Context.getSourceManager();
793 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000794 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000795 }
796
Chris Lattner88a69ad2007-07-13 05:13:43 +0000797 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000798 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000799 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000800
Chris Lattnerddee4232008-03-03 03:28:21 +0000801 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000802 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000803 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000804
Chris Lattner88a69ad2007-07-13 05:13:43 +0000805 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000806 if (D->getStorageClass() == VarDecl::Static)
807 GV->setLinkage(llvm::Function::InternalLinkage);
808 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000809 GV->setLinkage(llvm::Function::DLLImportLinkage);
810 else if (D->getAttr<DLLExportAttr>())
811 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000812 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000813 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000814 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000815 // FIXME: This isn't right. This should handle common linkage and other
816 // stuff.
817 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000818 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000819 case VarDecl::Auto:
820 case VarDecl::Register:
821 assert(0 && "Can't have auto or register globals");
822 case VarDecl::None:
823 if (!D->getInit())
Duncan Sandsceb77d92009-03-11 20:15:27 +0000824 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000825 else
826 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000827 break;
828 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000829 // FIXME: common
830 break;
831
Chris Lattnerddee4232008-03-03 03:28:21 +0000832 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000833 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
834 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000835 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000836 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000837 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000838
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000839 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
840 GV->setSection(SA->getName());
841
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000842 if (D->getAttr<UsedAttr>())
843 AddUsedGlobal(GV);
844
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000845 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000846 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000847 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000848 DI->EmitGlobalVariable(GV, D);
849 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000850}
Reid Spencer5f016e22007-07-11 17:01:13 +0000851
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000852
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000853void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000854 const llvm::FunctionType *Ty =
855 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
856
857 // As a special case, make sure that definitions of K&R function
858 // "type foo()" aren't declared as varargs (which forces the backend
859 // to do unnecessary work).
Chris Lattner34809502009-03-21 08:53:37 +0000860 // FIXME: what about stret() functions, this doesn't handle them!?
861 if (Ty->isVarArg() && Ty->getNumParams() == 0)
Daniel Dunbard5d31802009-02-19 07:15:39 +0000862 Ty = llvm::FunctionType::get(Ty->getReturnType(),
Chris Lattner62b33ea2009-03-21 08:38:50 +0000863 std::vector<const llvm::Type*>(), false);
Daniel Dunbard5d31802009-02-19 07:15:39 +0000864
Chris Lattner34809502009-03-21 08:53:37 +0000865 // Get or create the prototype for teh function.
Chris Lattner0558e792009-03-21 09:25:43 +0000866 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000867
Chris Lattner0558e792009-03-21 09:25:43 +0000868 // Strip off a bitcast if we got one back.
869 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
870 assert(CE->getOpcode() == llvm::Instruction::BitCast);
871 Entry = CE->getOperand(0);
872 }
873
874
875 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +0000876 // If the types mismatch then we have to rewrite the definition.
Chris Lattner0558e792009-03-21 09:25:43 +0000877 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
878 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000879
Chris Lattner62b33ea2009-03-21 08:38:50 +0000880 // F is the Function* for the one with the wrong type, we must make a new
881 // Function* and update everything that used F (a declaration) with the new
882 // Function* (which will be a definition).
883 //
884 // This happens if there is a prototype for a function
885 // (e.g. "int f()") and then a definition of a different type
886 // (e.g. "int f(int x)"). Start by making a new function of the
887 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +0000888 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner0558e792009-03-21 09:25:43 +0000889 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
890 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattner62b33ea2009-03-21 08:38:50 +0000891
892 // Replace uses of F with the Function we will endow with a body.
893 llvm::Constant *NewPtrForOldDecl =
Chris Lattner0558e792009-03-21 09:25:43 +0000894 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
895 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner62b33ea2009-03-21 08:38:50 +0000896
897 // Ok, delete the old function now, which is dead.
Chris Lattner34809502009-03-21 08:53:37 +0000898 // FIXME: If it was attribute(used) the pointer will dangle from the
899 // LLVMUsed array!
Chris Lattner0558e792009-03-21 09:25:43 +0000900 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +0000901
Chris Lattner0558e792009-03-21 09:25:43 +0000902 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000903 }
Chris Lattner0558e792009-03-21 09:25:43 +0000904
905 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000906
Daniel Dunbar219df662008-09-08 23:44:31 +0000907 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000908
Daniel Dunbar219df662008-09-08 23:44:31 +0000909 SetFunctionAttributesForDefinition(D, Fn);
910
Chris Lattner34809502009-03-21 08:53:37 +0000911 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000912 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattner34809502009-03-21 08:53:37 +0000913 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000914 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000915}
916
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000917llvm::Function *
918CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
919 const std::string &Name) {
920 llvm::Function *Fn = llvm::Function::Create(FTy,
921 llvm::Function::ExternalLinkage,
922 "", &TheModule);
Daniel Dunbarb681b8f2009-03-06 22:13:30 +0000923 RuntimeGlobals.push_back(std::make_pair(Fn, Name));
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000924 return Fn;
925}
926
Daniel Dunbarb681b8f2009-03-06 22:13:30 +0000927llvm::GlobalVariable *
928CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
929 const std::string &Name) {
930 llvm::GlobalVariable *GV =
931 new llvm::GlobalVariable(Ty, /*Constant=*/false,
932 llvm::GlobalValue::ExternalLinkage,
933 0, "", &TheModule);
934 RuntimeGlobals.push_back(std::make_pair(GV, Name));
935 return GV;
936}
937
Chris Lattnerc5b88062008-02-06 05:08:19 +0000938void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
939 // Make sure that this type is translated.
940 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000941}
942
943
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000944/// getBuiltinLibFunction
Mike Stumpc136e6c2009-02-27 22:42:30 +0000945llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000946 if (BuiltinID > BuiltinFunctions.size())
947 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000948
Chris Lattner1426fec2007-12-13 00:38:03 +0000949 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
950 // a slot for it.
951 assert(BuiltinID && "Invalid Builtin ID");
Mike Stumpc136e6c2009-02-27 22:42:30 +0000952 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000953 if (FunctionSlot)
954 return FunctionSlot;
955
Douglas Gregor3e41d602009-02-13 23:20:09 +0000956 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
957 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
958 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000959
Douglas Gregor3e41d602009-02-13 23:20:09 +0000960 // Get the name, skip over the __builtin_ prefix (if necessary).
961 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
962 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
963 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000964
965 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000966 Builtin::Context::GetBuiltinTypeError Error;
967 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
968 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
969
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000970 const llvm::FunctionType *Ty =
971 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
972
973 // FIXME: This has a serious problem with code like this:
974 // void abs() {}
975 // ... __builtin_abs(x);
976 // The two versions of abs will collide. The fix is for the builtin to win,
977 // and for the existing one to be turned into a constantexpr cast of the
978 // builtin. In the case where the existing one is a static function, it
979 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000980 if (llvm::Function *Existing = getModule().getFunction(Name)) {
981 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
982 return FunctionSlot = Existing;
983 assert(Existing == 0 && "FIXME: Name collision");
984 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000985
Chris Lattner4667c4a2009-03-01 18:47:06 +0000986 llvm::GlobalValue *&ExistingFn =
987 GlobalDeclMap[getContext().Idents.get(Name).getName()];
Chris Lattner5b60a0e2009-03-21 06:58:21 +0000988 assert(!ExistingFn && "Asking for the same builtin multiple times?");
Mike Stumpc136e6c2009-02-27 22:42:30 +0000989
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000990 // FIXME: param attributes for sext/zext etc.
Chris Lattner4667c4a2009-03-01 18:47:06 +0000991 return FunctionSlot = ExistingFn =
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000992 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
993 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000994}
995
Chris Lattner7acda7c2007-12-18 00:25:38 +0000996llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
997 unsigned NumTys) {
998 return llvm::Intrinsic::getDeclaration(&getModule(),
999 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1000}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001001
Reid Spencer5f016e22007-07-11 17:01:13 +00001002llvm::Function *CodeGenModule::getMemCpyFn() {
1003 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001004 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1005 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001006}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001007
Eli Friedman0c995092008-05-26 12:59:39 +00001008llvm::Function *CodeGenModule::getMemMoveFn() {
1009 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001010 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1011 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +00001012}
1013
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001014llvm::Function *CodeGenModule::getMemSetFn() {
1015 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001016 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1017 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001018}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001019
Anders Carlssone3daa762008-11-15 18:54:24 +00001020static void appendFieldAndPadding(CodeGenModule &CGM,
1021 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001022 FieldDecl *FieldD, FieldDecl *NextFieldD,
1023 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001024 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001025 // Append the field.
1026 Fields.push_back(Field);
1027
Douglas Gregor44b43212008-12-11 16:49:14 +00001028 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001029
1030 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001031 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001032 NextStructFieldNo = STy->getNumElements();
1033 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001034 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001035 }
1036
1037 // Append padding
1038 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1039 llvm::Constant *C =
1040 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1041
1042 Fields.push_back(C);
1043 }
1044}
1045
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001046// We still need to work out the details of handling UTF-16.
1047// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001048llvm::Constant *CodeGenModule::
1049GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +00001050 llvm::StringMapEntry<llvm::Constant *> &Entry =
1051 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1052
1053 if (Entry.getValue())
1054 return Entry.getValue();
1055
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001056 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1057 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001058
1059 if (!CFConstantStringClassRef) {
1060 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1061 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001062
1063 // FIXME: This is fairly broken if
1064 // __CFConstantStringClassReference is already defined, in that it
1065 // will get renamed and the user will most likely see an opaque
1066 // error message. This is a general issue with relying on
1067 // particular names.
1068 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001069 new llvm::GlobalVariable(Ty, false,
1070 llvm::GlobalVariable::ExternalLinkage, 0,
1071 "__CFConstantStringClassReference",
1072 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001073
1074 // Decay array -> ptr
1075 CFConstantStringClassRef =
1076 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001077 }
1078
Anders Carlssone3daa762008-11-15 18:54:24 +00001079 QualType CFTy = getContext().getCFConstantStringType();
1080 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001081
Anders Carlssone3daa762008-11-15 18:54:24 +00001082 const llvm::StructType *STy =
1083 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1084
1085 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +00001086 RecordDecl::field_iterator Field = CFRD->field_begin();
1087
Anders Carlssonc9e20912007-08-21 00:21:21 +00001088 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001089 FieldDecl *CurField = *Field++;
1090 FieldDecl *NextField = *Field++;
1091 appendFieldAndPadding(*this, Fields, CurField, NextField,
1092 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001093
1094 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001095 CurField = NextField;
1096 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001097 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001098 appendFieldAndPadding(*this, Fields, CurField, NextField,
1099 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001100
1101 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001102 CurField = NextField;
1103 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001104 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001105 C = new llvm::GlobalVariable(C->getType(), true,
1106 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +00001107 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +00001108 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +00001109 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1110 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001111
1112 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001113 CurField = NextField;
1114 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001115 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001116 appendFieldAndPadding(*this, Fields, CurField, NextField,
1117 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001118
1119 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001120 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +00001121 llvm::GlobalVariable *GV =
1122 new llvm::GlobalVariable(C->getType(), true,
1123 llvm::GlobalVariable::InternalLinkage,
1124 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001125
Anders Carlsson0c678292007-11-01 00:41:52 +00001126 GV->setSection("__DATA,__cfstring");
1127 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001128
Anders Carlsson0c678292007-11-01 00:41:52 +00001129 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001130}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001131
Daniel Dunbar61432932008-08-13 23:20:05 +00001132/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001133/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001134std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001135 const char *StrData = E->getStrData();
1136 unsigned Len = E->getByteLength();
1137
1138 const ConstantArrayType *CAT =
1139 getContext().getAsConstantArrayType(E->getType());
1140 assert(CAT && "String isn't pointer or array!");
1141
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001142 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001143 std::string Str(StrData, StrData+Len);
1144 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001145
1146 if (E->isWide())
1147 RealLen *= getContext().Target.getWCharWidth()/8;
1148
Daniel Dunbar1e049762008-08-10 20:25:57 +00001149 Str.resize(RealLen, '\0');
1150
1151 return Str;
1152}
1153
Daniel Dunbar61432932008-08-13 23:20:05 +00001154/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1155/// constant array for the given string literal.
1156llvm::Constant *
1157CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1158 // FIXME: This can be more efficient.
1159 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1160}
1161
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001162/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1163/// array for the given ObjCEncodeExpr node.
1164llvm::Constant *
1165CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1166 std::string Str;
1167 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001168
1169 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001170}
1171
1172
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001173/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001174static llvm::Constant *GenerateStringLiteral(const std::string &str,
1175 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001176 CodeGenModule &CGM,
1177 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001178 // Create Constant for this string literal. Don't add a '\0'.
1179 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001180
1181 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001182 return new llvm::GlobalVariable(C->getType(), constant,
1183 llvm::GlobalValue::InternalLinkage,
1184 C, GlobalName ? GlobalName : ".str",
1185 &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001186}
1187
Daniel Dunbar61432932008-08-13 23:20:05 +00001188/// GetAddrOfConstantString - Returns a pointer to a character array
1189/// containing the literal. This contents are exactly that of the
1190/// given string, i.e. it will not be null terminated automatically;
1191/// see GetAddrOfConstantCString. Note that whether the result is
1192/// actually a pointer to an LLVM constant depends on
1193/// Feature.WriteableStrings.
1194///
1195/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001196llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1197 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001198 // Don't share any string literals if writable-strings is turned on.
1199 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001200 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001201
1202 llvm::StringMapEntry<llvm::Constant *> &Entry =
1203 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1204
1205 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001206 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001207
1208 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001209 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001210 Entry.setValue(C);
1211 return C;
1212}
Daniel Dunbar61432932008-08-13 23:20:05 +00001213
1214/// GetAddrOfConstantCString - Returns a pointer to a character
1215/// array containing the literal and a terminating '\-'
1216/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001217llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1218 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001219 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001220}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001221
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001222/// EmitObjCPropertyImplementations - Emit information for synthesized
1223/// properties for an implementation.
1224void CodeGenModule::EmitObjCPropertyImplementations(const
1225 ObjCImplementationDecl *D) {
1226 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1227 e = D->propimpl_end(); i != e; ++i) {
1228 ObjCPropertyImplDecl *PID = *i;
1229
1230 // Dynamic is just for type-checking.
1231 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1232 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1233
1234 // Determine which methods need to be implemented, some may have
1235 // been overridden. Note that ::isSynthesized is not the method
1236 // we want, that just indicates if the decl came from a
1237 // property. What we want to know is if the method is defined in
1238 // this implementation.
1239 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001240 CodeGenFunction(*this).GenerateObjCGetter(
1241 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001242 if (!PD->isReadOnly() &&
1243 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001244 CodeGenFunction(*this).GenerateObjCSetter(
1245 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001246 }
1247 }
1248}
1249
Daniel Dunbar41071de2008-08-15 23:26:23 +00001250/// EmitTopLevelDecl - Emit code for a single top level declaration.
1251void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1252 // If an error has occurred, stop code generation, but continue
1253 // parsing and semantic analysis (to ensure all warnings and errors
1254 // are emitted).
1255 if (Diags.hasErrorOccurred())
1256 return;
1257
1258 switch (D->getKind()) {
1259 case Decl::Function:
1260 case Decl::Var:
1261 EmitGlobal(cast<ValueDecl>(D));
1262 break;
1263
1264 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001265 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001266 break;
1267
1268 // Objective-C Decls
1269
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001270 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001271 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001272 case Decl::ObjCForwardProtocol:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001273 break;
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001274
Daniel Dunbar41071de2008-08-15 23:26:23 +00001275 case Decl::ObjCProtocol:
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001276 case Decl::ObjCCategory:
1277 case Decl::ObjCInterface: {
1278 ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D);
1279 for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(),
1280 e = OCD->tuvar_end(); i != e; ++i) {
1281 VarDecl *VD = *i;
1282 EmitGlobal(VD);
1283 }
1284 if (D->getKind() == Decl::ObjCProtocol)
1285 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001286 break;
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001287 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001288
1289 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001290 // Categories have properties but don't support synthesize so we
1291 // can ignore them here.
1292
Daniel Dunbar41071de2008-08-15 23:26:23 +00001293 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1294 break;
1295
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001296 case Decl::ObjCImplementation: {
1297 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1298 EmitObjCPropertyImplementations(OMD);
1299 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001300 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001301 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001302 case Decl::ObjCMethod: {
1303 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1304 // If this is not a prototype, emit the body.
1305 if (OMD->getBody())
1306 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1307 break;
1308 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001309 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001310 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001311 break;
1312
1313 case Decl::LinkageSpec: {
1314 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1315 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001316 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001317 // FIXME: implement C++ linkage, C linkage works mostly by C
1318 // language reuse already.
1319 break;
1320 }
1321
1322 case Decl::FileScopeAsm: {
1323 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1324 std::string AsmString(AD->getAsmString()->getStrData(),
1325 AD->getAsmString()->getByteLength());
1326
1327 const std::string &S = getModule().getModuleInlineAsm();
1328 if (S.empty())
1329 getModule().setModuleInlineAsm(AsmString);
1330 else
1331 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1332 break;
1333 }
1334
1335 default:
1336 // Make sure we handled everything we should, every other kind is
1337 // a non-top-level decl. FIXME: Would be nice to have an
1338 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1339 // that easily.
1340 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1341 }
1342}