blob: c46db96bad64a8fba89f50bac3eb54d67184bfc5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Mike Stumpd6d0ebe2009-03-04 18:47:42 +000037 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
Mike Stump1f010b52009-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 Dunbarfc69bde2008-08-11 18:12:00 +000040
Chris Lattner08b05eb2009-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 Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stumpef2c82f2009-02-13 18:36:05 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000060 EmitDeferred();
Daniel Dunbar566a6502008-09-08 23:44:31 +000061 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000062 if (Runtime)
63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000065 EmitCtorList(GlobalCtors, "llvm.global_ctors");
66 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000067 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000068 EmitLLVMUsed();
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000069 BindRuntimeGlobals();
Chris Lattnercbfb5512008-03-01 08:45:05 +000070}
Chris Lattner4b009652007-07-25 00:24:17 +000071
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000072void CodeGenModule::BindRuntimeGlobals() {
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000073 // Deal with protecting runtime function names.
Daniel Dunbarf8fa6e12009-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 Dunbar18c2ec62008-10-01 00:49:24 +000077
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000078 // Discard unused runtime declarations.
79 if (GV->isDeclaration() && GV->use_empty()) {
80 GV->eraseFromParent();
Daniel Dunbarfc1543e2008-11-19 06:15:35 +000081 continue;
82 }
83
Chris Lattner535998b2009-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 Dunbarf8fa6e12009-03-06 22:13:30 +000091 llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name);
Chris Lattner535998b2009-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 Dunbarf8fa6e12009-03-06 22:13:30 +000097
Chris Lattner535998b2009-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 Dunbar18c2ec62008-10-01 00:49:24 +0000115 }
116}
117
Daniel Dunbar9503b782008-08-16 00:56:44 +0000118/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000119/// specified stmt yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +0000124 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000125 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000126 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000127 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
128 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000129}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000130
Daniel Dunbar9503b782008-08-16 00:56:44 +0000131/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000132/// specified decl yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +0000137 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000138 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +0000139 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000140 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000141}
142
Daniel Dunbar27250d32008-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 Gohman4751a3a2008-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 Gregor3556bc72009-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 Lattnerdaa199c2009-03-21 06:31:09 +0000164/// const char* containing the mangled name. Otherwise, returns
165/// the unmangled name.
Douglas Gregor3556bc72009-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 Dunbar7b7f4f42009-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 Gregor3556bc72009-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 Gregor3c3c4542009-02-18 23:53:56 +0000178const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-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 Lattner08b05eb2009-03-21 07:12:05 +0000182 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000183 }
184
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000185 llvm::SmallString<256> Name;
186 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000187 if (!mangleName(ND, Context, Out)) {
188 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000189 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000190 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000191
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000192 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000193 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000194}
195
Chris Lattner753d2592008-03-14 17:18:18 +0000196/// AddGlobalCtor - Add a function to the list that will be called before
197/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000198void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000199 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000200 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000201}
202
Daniel Dunbardd2e9ca2008-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 Dunbar3a80fc02009-01-13 02:25:00 +0000206 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-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 Lattnera18c12e2008-03-19 05:24:56 +0000219 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000220 llvm::StructType::get(llvm::Type::Int32Ty,
221 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000222
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000230 }
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000240}
241
Nate Begeman52da5c72008-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 Dunbar375da3f2009-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 Dunbar3a80fc02009-01-13 02:25:00 +0000263 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000264 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000265 if (!ForDefinition) {
266 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000267 if (D->getAttr<DLLImportAttr>()) {
268 // The dllimport attribute is overridden by a subsequent declaration as
269 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000270 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-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 Redle299eb42009-01-05 20:53:53 +0000278 }
Daniel Dunbar80f5f992009-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 Sands9aa5c262009-03-11 08:40:02 +0000283 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000284 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000285 } else {
286 if (IsInternal) {
287 GV->setLinkage(llvm::Function::InternalLinkage);
288 } else {
Anton Korobeynikovb27a8702008-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 Dunbar80f5f992009-03-06 16:20:49 +0000296 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
297 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000298 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000299 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000300 }
Nuno Lopes78534382008-06-08 15:45:52 +0000301
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000302 // FIXME: Figure out the relative priority of the attribute,
303 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000304 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000305 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000306 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000307
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000308 // Prefaced with special LLVM marker to indicate that the name
309 // should not be munged.
310 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
Daniel Dunbarced89142008-08-06 00:03:29 +0000311 GV->setName("\01" + ALA->getLabel());
Daniel Dunbar97509722009-02-12 17:28:23 +0000312
313 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
314 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000315
316 // Only add to llvm.used when we see a definition, otherwise we
317 // might add multiple times or risk the value being replaced by a
318 // subsequent RAUW.
319 if (ForDefinition) {
320 if (D->getAttr<UsedAttr>())
321 AddUsedGlobal(GV);
322 }
Nuno Lopes78534382008-06-08 15:45:52 +0000323}
324
Devang Patela85a9ef2008-09-25 21:02:23 +0000325void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000326 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000327 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000328 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000329 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000330
Devang Patela85a9ef2008-09-25 21:02:23 +0000331 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
332 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000333
334 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000335 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000336 F->setCallingConv(llvm::CallingConv::X86_FastCall);
337
338 if (D->getAttr<StdCallAttr>())
339 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000340}
341
342/// SetFunctionAttributesForDefinition - Set function attributes
343/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000344void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
345 llvm::Function *F) {
346 if (isa<ObjCMethodDecl>(D)) {
347 SetGlobalValueAttributes(D, true, false, F, true);
348 } else {
349 const FunctionDecl *FD = cast<FunctionDecl>(D);
350 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
351 FD->isInline(), F, true);
352 }
353
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000354 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000355 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000356
357 if (D->getAttr<AlwaysInlineAttr>())
358 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000359
360 if (D->getAttr<NoinlineAttr>())
361 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000362}
363
364void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
365 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000366 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000367
Daniel Dunbar566a6502008-09-08 23:44:31 +0000368 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000369}
370
371void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
372 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000373 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000374
Daniel Dunbar566a6502008-09-08 23:44:31 +0000375 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
376 FD->isInline(), F, false);
377}
378
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000379
Daniel Dunbar566a6502008-09-08 23:44:31 +0000380void CodeGenModule::EmitAliases() {
381 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000382 const ValueDecl *D = Aliases[i];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000383 const AliasAttr *AA = D->getAttr<AliasAttr>();
384
385 // This is something of a hack, if the FunctionDecl got overridden
386 // then its attributes will be moved to the new declaration. In
387 // this case the current decl has no alias attribute, but we will
388 // eventually see it.
389 if (!AA)
390 continue;
391
392 const std::string& aliaseeName = AA->getAliasee();
Daniel Dunbar36acae42009-03-19 08:27:24 +0000393 llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000394 if (!aliasee) {
395 // FIXME: This isn't unsupported, this is just an error, which
396 // sema should catch, but...
397 ErrorUnsupported(D, "alias referencing a missing function");
398 continue;
399 }
400
Chris Lattner0b506252009-03-21 08:06:59 +0000401 const char *MangledName = getMangledName(D);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000402 llvm::GlobalValue *GA =
403 new llvm::GlobalAlias(aliasee->getType(),
404 llvm::Function::ExternalLinkage,
Chris Lattner0b506252009-03-21 08:06:59 +0000405 MangledName, aliasee, &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000406
Chris Lattner0b506252009-03-21 08:06:59 +0000407 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000408 if (Entry) {
409 // If we created a dummy function for this then replace it.
410 GA->takeName(Entry);
411
412 llvm::Value *Casted =
413 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
414 Entry->replaceAllUsesWith(Casted);
415 Entry->eraseFromParent();
416
417 Entry = GA;
418 }
419
420 // Alias should never be internal or inline.
421 SetGlobalValueAttributes(D, false, false, GA, true);
422 }
Eli Friedman9be42212008-06-01 15:54:49 +0000423}
424
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000425void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
426 assert(!GV->isDeclaration() &&
427 "Only globals with definition can force usage.");
428 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
429 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
430}
431
432void CodeGenModule::EmitLLVMUsed() {
433 // Don't create llvm.used if there is no need.
434 if (LLVMUsed.empty())
435 return;
436
437 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
438 LLVMUsed.size());
439 llvm::GlobalVariable *GV =
440 new llvm::GlobalVariable(ATy, false,
441 llvm::GlobalValue::AppendingLinkage,
442 llvm::ConstantArray::get(ATy, LLVMUsed),
443 "llvm.used", &getModule());
444
445 GV->setSection("llvm.metadata");
446}
447
448void CodeGenModule::EmitDeferred() {
449 // Emit code for any deferred decl which was used. Since a
450 // previously unused static decl may become used during the
451 // generation of code for a static function, iterate until no
452 // changes are made.
Nate Begemanad320b62008-04-20 06:29:50 +0000453 bool Changed;
454 do {
455 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000456
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000457 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
458 e = DeferredDecls.end(); i != e; ) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000459 const ValueDecl *D = *i;
460
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000461 // Check if we have used a decl with the same name
462 // FIXME: The AST should have some sort of aggregate decls or
463 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000464 // FIXME: This is missing some important cases. For example, we
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000465 // need to check for uses in an alias.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000466 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000467 ++i;
Daniel Dunbarced89142008-08-06 00:03:29 +0000468 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000469 }
470
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000471 // Emit the definition.
472 EmitGlobalDefinition(D);
473
Nate Begemanad320b62008-04-20 06:29:50 +0000474 // Erase the used decl from the list.
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000475 i = DeferredDecls.erase(i);
Anders Carlsson2e427d52009-01-04 02:08:04 +0000476
Nate Begemanad320b62008-04-20 06:29:50 +0000477 // Remember that we made a change.
478 Changed = true;
479 }
480 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000481}
482
Nate Begeman8a704172008-04-19 04:17:09 +0000483/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
484/// annotation information for a given GlobalValue. The annotation struct is
485/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000486/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000487/// created from the AnnotateAttr's annotation. The third field is a constant
488/// string containing the name of the translation unit. The fourth field is
489/// the line number in the file of the annotated value declaration.
490///
491/// FIXME: this does not unique the annotation string constants, as llvm-gcc
492/// appears to.
493///
494llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
495 const AnnotateAttr *AA,
496 unsigned LineNo) {
497 llvm::Module *M = &getModule();
498
499 // get [N x i8] constants for the annotation string, and the filename string
500 // which are the 2nd and 3rd elements of the global annotation structure.
501 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
502 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
503 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
504 true);
505
506 // Get the two global values corresponding to the ConstantArrays we just
507 // created to hold the bytes of the strings.
508 llvm::GlobalValue *annoGV =
509 new llvm::GlobalVariable(anno->getType(), false,
510 llvm::GlobalValue::InternalLinkage, anno,
511 GV->getName() + ".str", M);
512 // translation unit name string, emitted into the llvm.metadata section.
513 llvm::GlobalValue *unitGV =
514 new llvm::GlobalVariable(unit->getType(), false,
515 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
516
517 // Create the ConstantStruct that is the global annotion.
518 llvm::Constant *Fields[4] = {
519 llvm::ConstantExpr::getBitCast(GV, SBP),
520 llvm::ConstantExpr::getBitCast(annoGV, SBP),
521 llvm::ConstantExpr::getBitCast(unitGV, SBP),
522 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
523 };
524 return llvm::ConstantStruct::get(Fields, 4, false);
525}
526
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000527bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000528 // Never defer when EmitAllDecls is specified or the decl has
529 // attribute used.
530 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000531 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000532
533 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000534 // Constructors and destructors should never be deferred.
535 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
536 return false;
537
Chris Lattner7e5888f2009-03-21 08:03:33 +0000538 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000539 if (FD->getStorageClass() != FunctionDecl::Static)
540 return false;
541 } else {
542 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000543 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000544
545 if (VD->getStorageClass() != VarDecl::Static)
546 return false;
547 }
548
549 return true;
550}
551
552void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000553 // Aliases are deferred until code for everything else has been
554 // emitted.
555 if (Global->getAttr<AliasAttr>()) {
556 Aliases.push_back(Global);
557 return;
558 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000559
Daniel Dunbar36acae42009-03-19 08:27:24 +0000560 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000561 // Forward declarations are emitted lazily on first use.
562 if (!FD->isThisDeclarationADefinition())
563 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000564 } else {
565 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000566 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
567
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000568 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000569 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000570 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000571 }
572
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000573 // Defer code generation when possible.
574 if (MayDeferGeneration(Global)) {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000575 DeferredDecls.push_back(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000576 return;
577 }
578
579 // Otherwise emit the definition.
580 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000581}
582
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000583void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
584 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
585 EmitGlobalFunctionDefinition(FD);
586 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
587 EmitGlobalVarDefinition(VD);
588 } else {
589 assert(0 && "Invalid argument to EmitGlobalDefinition()");
590 }
591}
592
Daniel Dunbar2188c532008-07-30 16:32:24 +0000593 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000594 assert(D->hasGlobalStorage() && "Not a global variable");
595
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000596 QualType ASTTy = D->getType();
597 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
598
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000599 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000600 const char *MangledName = getMangledName(D);
601 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000602 if (Entry) {
603 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
604
605 // Make sure the result is of the correct type.
606 if (Entry->getType() != PTy)
607 return llvm::ConstantExpr::getBitCast(Entry, PTy);
608 return Entry;
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000609 }
Chris Lattner7e5888f2009-03-21 08:03:33 +0000610
611 llvm::GlobalVariable *GV =
612 new llvm::GlobalVariable(Ty, false,
613 llvm::GlobalValue::ExternalLinkage,
Chris Lattner0b506252009-03-21 08:06:59 +0000614 0, MangledName, &getModule(),
Chris Lattner7e5888f2009-03-21 08:03:33 +0000615 0, ASTTy.getAddressSpace());
616
617 // Handle things which are present even on external declarations.
618
619 // FIXME: This code is overly simple and should be merged with
620 // other global handling.
621
622 GV->setConstant(D->getType().isConstant(Context));
623
624 // FIXME: Merge with other attribute handling code.
625
626 if (D->getStorageClass() == VarDecl::PrivateExtern)
627 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
628
629 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
630 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
631
632 // FIXME: This should be handled by the mangler!
633 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
634 // Prefaced with special LLVM marker to indicate that the name
635 // should not be munged.
636 GV->setName("\01" + ALA->getLabel());
637 }
638 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000639}
640
641void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000643 QualType ASTTy = D->getType();
644 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000645
Chris Lattner4b009652007-07-25 00:24:17 +0000646 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000647 // This is a tentative definition; tentative definitions are
648 // implicitly initialized with { 0 }
Chris Lattner23afd5b2009-03-21 08:13:05 +0000649 const llvm::Type *InitTy = VarTy;
Eli Friedman7008e9a2008-05-30 20:39:54 +0000650 if (ASTTy->isIncompleteArrayType()) {
651 // An incomplete array is normally [ TYPE x 0 ], but we need
652 // to fix it to [ TYPE x 1 ].
653 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
654 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000655 }
656 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000657 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000658 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000659 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000660 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000661 QualType T = D->getInit()->getType();
662 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
663 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000664 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000665
Chris Lattner23afd5b2009-03-21 08:13:05 +0000666 const llvm::Type* InitType = Init->getType();
Chris Lattner0b506252009-03-21 08:06:59 +0000667 const char *MangledName = getMangledName(D);
668 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000669 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
670
Eli Friedman43a0ce82008-05-30 19:50:47 +0000671 if (!GV) {
672 GV = new llvm::GlobalVariable(InitType, false,
673 llvm::GlobalValue::ExternalLinkage,
Chris Lattner0b506252009-03-21 08:06:59 +0000674 0, MangledName,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000675 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000676
677 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
678 // If we already have this global and it has an initializer, then
679 // we are in the rare situation where we emitted the defining
680 // declaration of the global and are now being asked to emit a
681 // definition which would be common. This occurs, for example, in
682 // the following situation because statics can be emitted out of
683 // order:
684 //
685 // static int x;
686 // static int *y = &x;
687 // static int x = 10;
688 // int **z = &y;
689 //
690 // Bail here so we don't blow away the definition. Note that if we
691 // can't distinguish here if we emitted a definition with a null
692 // initializer, but this case is safe.
693 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
694 return;
695
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000696 } else if (GV->getType() !=
697 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000698 // We have a definition after a prototype with the wrong type.
699 // We must make a new GlobalVariable* and update everything that used OldGV
700 // (a declaration or tentative definition) with the new GlobalVariable*
701 // (which will be a definition).
702 //
Chris Lattner23afd5b2009-03-21 08:13:05 +0000703 // This happens if there is a prototype for a global (e.g.
704 // "extern int x[];") and then a definition of a different type (e.g.
705 // "int x[10];"). This also happens when an initializer has a different type
706 // from the type of the global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000707 //
708 // FIXME: This also ends up happening if there's a definition followed by
709 // a tentative definition! (Although Sema rejects that construct
710 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000711
712 // Save the old global
713 llvm::GlobalVariable *OldGV = GV;
714
715 // Make a new global with the correct type
716 GV = new llvm::GlobalVariable(InitType, false,
717 llvm::GlobalValue::ExternalLinkage,
Chris Lattner0b506252009-03-21 08:06:59 +0000718 0, MangledName,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000719 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000720 // Steal the name of the old global
721 GV->takeName(OldGV);
722
723 // Replace all uses of the old global with the new global
724 llvm::Constant *NewPtrForOldDecl =
725 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
726 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000727
728 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000729 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Eli Friedman43a0ce82008-05-30 19:50:47 +0000730 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000731 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000732
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000733 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000734
Nate Begeman8a704172008-04-19 04:17:09 +0000735 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
736 SourceManager &SM = Context.getSourceManager();
737 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000738 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000739 }
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000742 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000743 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000744
Chris Lattner402b3372008-03-03 03:28:21 +0000745 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000746 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000747 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000748
Chris Lattner23afd5b2009-03-21 08:13:05 +0000749 // FIXME: This should be a mangling issue.
Daniel Dunbarced89142008-08-06 00:03:29 +0000750 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
751 // Prefaced with special LLVM marker to indicate that the name
752 // should not be munged.
753 GV->setName("\01" + ALA->getLabel());
754 }
Chris Lattner4b009652007-07-25 00:24:17 +0000755
756 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000757 if (D->getStorageClass() == VarDecl::Static)
758 GV->setLinkage(llvm::Function::InternalLinkage);
759 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000760 GV->setLinkage(llvm::Function::DLLImportLinkage);
761 else if (D->getAttr<DLLExportAttr>())
762 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000763 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000764 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000765 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000766 // FIXME: This isn't right. This should handle common linkage and other
767 // stuff.
768 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000769 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000770 case VarDecl::Auto:
771 case VarDecl::Register:
772 assert(0 && "Can't have auto or register globals");
773 case VarDecl::None:
774 if (!D->getInit())
Duncan Sands78c33cc2009-03-11 20:15:27 +0000775 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000776 else
777 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000778 break;
779 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000780 // FIXME: common
781 break;
782
Chris Lattner402b3372008-03-03 03:28:21 +0000783 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000784 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
785 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000786 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000787 }
Chris Lattner4b009652007-07-25 00:24:17 +0000788 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000789
Daniel Dunbar97509722009-02-12 17:28:23 +0000790 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
791 GV->setSection(SA->getName());
792
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000793 if (D->getAttr<UsedAttr>())
794 AddUsedGlobal(GV);
795
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000796 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000797 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000798 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000799 DI->EmitGlobalVariable(GV, D);
800 }
Chris Lattner4b009652007-07-25 00:24:17 +0000801}
802
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000803llvm::GlobalValue *
Daniel Dunbar3f197842009-02-19 07:15:39 +0000804CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000805 const llvm::Type *Ty) {
Eli Friedman040f4db2009-03-05 04:18:07 +0000806 bool DoSetAttributes = true;
807 if (!Ty) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000808 Ty = getTypes().ConvertType(D->getType());
Eli Friedman040f4db2009-03-05 04:18:07 +0000809 if (!isa<llvm::FunctionType>(Ty)) {
810 // This function doesn't have a complete type (for example, the return
811 // type is an incomplete struct). Use a fake type instead, and make
812 // sure not to try to set attributes.
813 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
814 std::vector<const llvm::Type*>(), false);
815 DoSetAttributes = false;
816 }
817 }
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000818 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
819 llvm::Function::ExternalLinkage,
820 getMangledName(D),
821 &getModule());
Eli Friedman040f4db2009-03-05 04:18:07 +0000822 if (DoSetAttributes)
823 SetFunctionAttributes(D, F);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000824 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000825}
826
827llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000828 QualType ASTTy = D->getType();
829 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
830 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000831
832 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000833 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000834 if (!Entry)
Chris Lattner7e5888f2009-03-21 08:03:33 +0000835 return Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000836
Chris Lattnerc3a26482009-03-21 06:53:34 +0000837 if (Entry->getType() != PTy)
838 return llvm::ConstantExpr::getBitCast(Entry, PTy);
839 return Entry;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000840}
841
842void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000843 const llvm::FunctionType *Ty =
844 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
845
846 // As a special case, make sure that definitions of K&R function
847 // "type foo()" aren't declared as varargs (which forces the backend
848 // to do unnecessary work).
849 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
850 Ty = llvm::FunctionType::get(Ty->getReturnType(),
851 std::vector<const llvm::Type*>(),
852 false);
853
Douglas Gregor3556bc72009-02-13 00:10:09 +0000854 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000855 if (!Entry) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000856 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000857 } else {
858 // If the types mismatch then we have to rewrite the definition.
859 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
860 // Otherwise, we have a definition after a prototype with the
861 // wrong type. F is the Function* for the one with the wrong
862 // type, we must make a new Function* and update everything that
863 // used F (a declaration) with the new Function* (which will be
864 // a definition).
865 //
866 // This happens if there is a prototype for a function
867 // (e.g. "int f()") and then a definition of a different type
868 // (e.g. "int f(int x)"). Start by making a new function of the
869 // correct type, RAUW, then steal the name.
870 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
871 NewFn->takeName(Entry);
872
873 // Replace uses of F with the Function we will endow with a body.
874 llvm::Constant *NewPtrForOldDecl =
875 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
876 Entry->replaceAllUsesWith(NewPtrForOldDecl);
877
878 // Ok, delete the old function now, which is dead.
879 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
880 Entry->eraseFromParent();
881
882 Entry = NewFn;
883 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000884 }
885
Daniel Dunbar566a6502008-09-08 23:44:31 +0000886 llvm::Function *Fn = cast<llvm::Function>(Entry);
887 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000888
Daniel Dunbar566a6502008-09-08 23:44:31 +0000889 SetFunctionAttributesForDefinition(D, Fn);
890
891 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
892 AddGlobalCtor(Fn, CA->getPriority());
893 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
894 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000895 }
896}
897
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000898llvm::Function *
899CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
900 const std::string &Name) {
901 llvm::Function *Fn = llvm::Function::Create(FTy,
902 llvm::Function::ExternalLinkage,
903 "", &TheModule);
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000904 RuntimeGlobals.push_back(std::make_pair(Fn, Name));
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000905 return Fn;
906}
907
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000908llvm::GlobalVariable *
909CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
910 const std::string &Name) {
911 llvm::GlobalVariable *GV =
912 new llvm::GlobalVariable(Ty, /*Constant=*/false,
913 llvm::GlobalValue::ExternalLinkage,
914 0, "", &TheModule);
915 RuntimeGlobals.push_back(std::make_pair(GV, Name));
916 return GV;
917}
918
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000919void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
920 // Make sure that this type is translated.
921 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000922}
923
924
Chris Lattnerab862cc2007-08-31 04:31:45 +0000925/// getBuiltinLibFunction
Mike Stump96b7a152009-02-27 22:42:30 +0000926llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000927 if (BuiltinID > BuiltinFunctions.size())
928 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000929
Chris Lattner9f2d6892007-12-13 00:38:03 +0000930 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
931 // a slot for it.
932 assert(BuiltinID && "Invalid Builtin ID");
Mike Stump96b7a152009-02-27 22:42:30 +0000933 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000934 if (FunctionSlot)
935 return FunctionSlot;
936
Douglas Gregor411889e2009-02-13 23:20:09 +0000937 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
938 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
939 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000940
Douglas Gregor411889e2009-02-13 23:20:09 +0000941 // Get the name, skip over the __builtin_ prefix (if necessary).
942 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
943 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
944 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000945
946 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000947 Builtin::Context::GetBuiltinTypeError Error;
948 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
949 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
950
Chris Lattnerab862cc2007-08-31 04:31:45 +0000951 const llvm::FunctionType *Ty =
952 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
953
954 // FIXME: This has a serious problem with code like this:
955 // void abs() {}
956 // ... __builtin_abs(x);
957 // The two versions of abs will collide. The fix is for the builtin to win,
958 // and for the existing one to be turned into a constantexpr cast of the
959 // builtin. In the case where the existing one is a static function, it
960 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000961 if (llvm::Function *Existing = getModule().getFunction(Name)) {
962 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
963 return FunctionSlot = Existing;
964 assert(Existing == 0 && "FIXME: Name collision");
965 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000966
Chris Lattner72cdb962009-03-01 18:47:06 +0000967 llvm::GlobalValue *&ExistingFn =
968 GlobalDeclMap[getContext().Idents.get(Name).getName()];
Chris Lattner71fc5812009-03-21 06:58:21 +0000969 assert(!ExistingFn && "Asking for the same builtin multiple times?");
Mike Stump96b7a152009-02-27 22:42:30 +0000970
Chris Lattnerab862cc2007-08-31 04:31:45 +0000971 // FIXME: param attributes for sext/zext etc.
Chris Lattner72cdb962009-03-01 18:47:06 +0000972 return FunctionSlot = ExistingFn =
Nate Begemanad320b62008-04-20 06:29:50 +0000973 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
974 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000975}
976
Chris Lattner4b23f942007-12-18 00:25:38 +0000977llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
978 unsigned NumTys) {
979 return llvm::Intrinsic::getDeclaration(&getModule(),
980 (llvm::Intrinsic::ID)IID, Tys, NumTys);
981}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000982
Chris Lattner4b009652007-07-25 00:24:17 +0000983llvm::Function *CodeGenModule::getMemCpyFn() {
984 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000985 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
986 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000987}
Anders Carlsson36a04872007-08-21 00:21:21 +0000988
Eli Friedman8f08a252008-05-26 12:59:39 +0000989llvm::Function *CodeGenModule::getMemMoveFn() {
990 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000991 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
992 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000993}
994
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000995llvm::Function *CodeGenModule::getMemSetFn() {
996 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000997 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
998 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000999}
Chris Lattner4b23f942007-12-18 00:25:38 +00001000
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001001static void appendFieldAndPadding(CodeGenModule &CGM,
1002 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +00001003 FieldDecl *FieldD, FieldDecl *NextFieldD,
1004 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +00001005 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001006 // Append the field.
1007 Fields.push_back(Field);
1008
Douglas Gregor8acb7272008-12-11 16:49:14 +00001009 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001010
1011 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001012 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001013 NextStructFieldNo = STy->getNumElements();
1014 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001015 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001016 }
1017
1018 // Append padding
1019 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1020 llvm::Constant *C =
1021 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1022
1023 Fields.push_back(C);
1024 }
1025}
1026
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001027// We still need to work out the details of handling UTF-16.
1028// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001029llvm::Constant *CodeGenModule::
1030GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001031 llvm::StringMapEntry<llvm::Constant *> &Entry =
1032 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1033
1034 if (Entry.getValue())
1035 return Entry.getValue();
1036
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001037 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1038 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001039
1040 if (!CFConstantStringClassRef) {
1041 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1042 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001043
1044 // FIXME: This is fairly broken if
1045 // __CFConstantStringClassReference is already defined, in that it
1046 // will get renamed and the user will most likely see an opaque
1047 // error message. This is a general issue with relying on
1048 // particular names.
1049 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001050 new llvm::GlobalVariable(Ty, false,
1051 llvm::GlobalVariable::ExternalLinkage, 0,
1052 "__CFConstantStringClassReference",
1053 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001054
1055 // Decay array -> ptr
1056 CFConstantStringClassRef =
1057 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001058 }
1059
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001060 QualType CFTy = getContext().getCFConstantStringType();
1061 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001062
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001063 const llvm::StructType *STy =
1064 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1065
1066 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001067 RecordDecl::field_iterator Field = CFRD->field_begin();
1068
Anders Carlsson36a04872007-08-21 00:21:21 +00001069 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001070 FieldDecl *CurField = *Field++;
1071 FieldDecl *NextField = *Field++;
1072 appendFieldAndPadding(*this, Fields, CurField, NextField,
1073 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001074
1075 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001076 CurField = NextField;
1077 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001078 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001079 appendFieldAndPadding(*this, Fields, CurField, NextField,
1080 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001081
1082 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001083 CurField = NextField;
1084 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001085 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001086 C = new llvm::GlobalVariable(C->getType(), true,
1087 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001088 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001089 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001090 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1091 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001092
1093 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001094 CurField = NextField;
1095 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001096 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001097 appendFieldAndPadding(*this, Fields, CurField, NextField,
1098 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001099
1100 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001101 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001102 llvm::GlobalVariable *GV =
1103 new llvm::GlobalVariable(C->getType(), true,
1104 llvm::GlobalVariable::InternalLinkage,
1105 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001106
Anders Carlsson9be009e2007-11-01 00:41:52 +00001107 GV->setSection("__DATA,__cfstring");
1108 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001109
Anders Carlsson9be009e2007-11-01 00:41:52 +00001110 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001111}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001112
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001113/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001114/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001115std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001116 const char *StrData = E->getStrData();
1117 unsigned Len = E->getByteLength();
1118
1119 const ConstantArrayType *CAT =
1120 getContext().getAsConstantArrayType(E->getType());
1121 assert(CAT && "String isn't pointer or array!");
1122
Chris Lattner14032222009-02-26 23:01:51 +00001123 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001124 std::string Str(StrData, StrData+Len);
1125 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001126
1127 if (E->isWide())
1128 RealLen *= getContext().Target.getWCharWidth()/8;
1129
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001130 Str.resize(RealLen, '\0');
1131
1132 return Str;
1133}
1134
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001135/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1136/// constant array for the given string literal.
1137llvm::Constant *
1138CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1139 // FIXME: This can be more efficient.
1140 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1141}
1142
Chris Lattnerc5d32632009-02-24 22:18:39 +00001143/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1144/// array for the given ObjCEncodeExpr node.
1145llvm::Constant *
1146CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1147 std::string Str;
1148 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001149
1150 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001151}
1152
1153
Chris Lattnera6dcce32008-02-11 00:02:17 +00001154/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001155static llvm::Constant *GenerateStringLiteral(const std::string &str,
1156 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001157 CodeGenModule &CGM,
1158 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001159 // Create Constant for this string literal. Don't add a '\0'.
1160 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001161
1162 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001163 return new llvm::GlobalVariable(C->getType(), constant,
1164 llvm::GlobalValue::InternalLinkage,
1165 C, GlobalName ? GlobalName : ".str",
1166 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001167}
1168
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001169/// GetAddrOfConstantString - Returns a pointer to a character array
1170/// containing the literal. This contents are exactly that of the
1171/// given string, i.e. it will not be null terminated automatically;
1172/// see GetAddrOfConstantCString. Note that whether the result is
1173/// actually a pointer to an LLVM constant depends on
1174/// Feature.WriteableStrings.
1175///
1176/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001177llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1178 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001179 // Don't share any string literals if writable-strings is turned on.
1180 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001181 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001182
1183 llvm::StringMapEntry<llvm::Constant *> &Entry =
1184 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1185
1186 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001187 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001188
1189 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001190 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001191 Entry.setValue(C);
1192 return C;
1193}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001194
1195/// GetAddrOfConstantCString - Returns a pointer to a character
1196/// array containing the literal and a terminating '\-'
1197/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001198llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1199 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001200 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001201}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001202
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001203/// EmitObjCPropertyImplementations - Emit information for synthesized
1204/// properties for an implementation.
1205void CodeGenModule::EmitObjCPropertyImplementations(const
1206 ObjCImplementationDecl *D) {
1207 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1208 e = D->propimpl_end(); i != e; ++i) {
1209 ObjCPropertyImplDecl *PID = *i;
1210
1211 // Dynamic is just for type-checking.
1212 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1213 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1214
1215 // Determine which methods need to be implemented, some may have
1216 // been overridden. Note that ::isSynthesized is not the method
1217 // we want, that just indicates if the decl came from a
1218 // property. What we want to know is if the method is defined in
1219 // this implementation.
1220 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001221 CodeGenFunction(*this).GenerateObjCGetter(
1222 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001223 if (!PD->isReadOnly() &&
1224 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001225 CodeGenFunction(*this).GenerateObjCSetter(
1226 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001227 }
1228 }
1229}
1230
Daniel Dunbar27250d32008-08-15 23:26:23 +00001231/// EmitTopLevelDecl - Emit code for a single top level declaration.
1232void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1233 // If an error has occurred, stop code generation, but continue
1234 // parsing and semantic analysis (to ensure all warnings and errors
1235 // are emitted).
1236 if (Diags.hasErrorOccurred())
1237 return;
1238
1239 switch (D->getKind()) {
1240 case Decl::Function:
1241 case Decl::Var:
1242 EmitGlobal(cast<ValueDecl>(D));
1243 break;
1244
1245 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001246 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001247 break;
1248
1249 // Objective-C Decls
1250
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001251 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001252 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001253 case Decl::ObjCForwardProtocol:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001254 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001255
Daniel Dunbar27250d32008-08-15 23:26:23 +00001256 case Decl::ObjCProtocol:
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001257 case Decl::ObjCCategory:
1258 case Decl::ObjCInterface: {
1259 ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D);
1260 for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(),
1261 e = OCD->tuvar_end(); i != e; ++i) {
1262 VarDecl *VD = *i;
1263 EmitGlobal(VD);
1264 }
1265 if (D->getKind() == Decl::ObjCProtocol)
1266 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001267 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001268 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001269
1270 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001271 // Categories have properties but don't support synthesize so we
1272 // can ignore them here.
1273
Daniel Dunbar27250d32008-08-15 23:26:23 +00001274 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1275 break;
1276
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001277 case Decl::ObjCImplementation: {
1278 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1279 EmitObjCPropertyImplementations(OMD);
1280 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001281 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001282 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001283 case Decl::ObjCMethod: {
1284 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1285 // If this is not a prototype, emit the body.
1286 if (OMD->getBody())
1287 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1288 break;
1289 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001290 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001291 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001292 break;
1293
1294 case Decl::LinkageSpec: {
1295 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1296 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001297 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001298 // FIXME: implement C++ linkage, C linkage works mostly by C
1299 // language reuse already.
1300 break;
1301 }
1302
1303 case Decl::FileScopeAsm: {
1304 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1305 std::string AsmString(AD->getAsmString()->getStrData(),
1306 AD->getAsmString()->getByteLength());
1307
1308 const std::string &S = getModule().getModuleInlineAsm();
1309 if (S.empty())
1310 getModule().setModuleInlineAsm(AsmString);
1311 else
1312 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1313 break;
1314 }
1315
1316 default:
1317 // Make sure we handled everything we should, every other kind is
1318 // a non-top-level decl. FIXME: Would be nice to have an
1319 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1320 // that easily.
1321 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1322 }
1323}