blob: 33aff2553fd0c599734de7721fc6ca6bf0c24cde [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)
Chris Lattnerfb97b032007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000038 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Anders Carlsson22c818a2009-03-01 01:17:11 +000039 CFConstantStringClassRef(0), NSConcreteGlobalBlock(0),
40 NSConcreteStackBlock(0),BlockDescriptorType(0), GenericBlockLiteralType(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000041
42 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000043 if (Features.NeXTRuntime) {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000044 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanianee0af742009-01-21 22:04:16 +000045 : CreateMacObjCRuntime(*this);
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000046 } else {
47 Runtime = CreateGNUObjCRuntime(*this);
48 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000049 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000050
51 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stump26efc332009-02-13 18:36:05 +000052 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
53
54 Block.GlobalUniqueCount = 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000055}
56
57CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000058 delete Runtime;
59 delete DebugInfo;
60}
61
62void CodeGenModule::Release() {
Daniel Dunbar02698712009-02-13 20:29:50 +000063 EmitDeferred();
Daniel Dunbar219df662008-09-08 23:44:31 +000064 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000065 if (Runtime)
66 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000068 EmitCtorList(GlobalCtors, "llvm.global_ctors");
69 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000070 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000071 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000072 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000073}
Reid Spencer5f016e22007-07-11 17:01:13 +000074
Daniel Dunbarf1968f22008-10-01 00:49:24 +000075void CodeGenModule::BindRuntimeFunctions() {
76 // Deal with protecting runtime function names.
77 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
78 llvm::Function *Fn = RuntimeFunctions[i].first;
79 const std::string &Name = RuntimeFunctions[i].second;
80
Daniel Dunbar0293d542008-11-19 06:15:35 +000081 // Discard unused runtime functions.
82 if (Fn->use_empty()) {
83 Fn->eraseFromParent();
84 continue;
85 }
86
Daniel Dunbarf1968f22008-10-01 00:49:24 +000087 // See if there is a conflict against a function.
88 llvm::Function *Conflict = TheModule.getFunction(Name);
89 if (Conflict) {
90 // Decide which version to take. If the conflict is a definition
91 // we are forced to take that, otherwise assume the runtime
92 // knows best.
93 if (!Conflict->isDeclaration()) {
94 llvm::Value *Casted =
95 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
96 Fn->replaceAllUsesWith(Casted);
97 Fn->eraseFromParent();
98 } else {
99 Fn->takeName(Conflict);
100 llvm::Value *Casted =
101 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
102 Conflict->replaceAllUsesWith(Casted);
103 Conflict->eraseFromParent();
104 }
105 } else {
106 // FIXME: There still may be conflicts with aliases and
107 // variables.
108 Fn->setName(Name);
109 }
110 }
111}
112
Daniel Dunbar488e9932008-08-16 00:56:44 +0000113/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000114/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000115void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116 bool OmitOnError) {
117 if (OmitOnError && getDiags().hasErrorOccurred())
118 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000119 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000120 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000121 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000122 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000124}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000125
Daniel Dunbar488e9932008-08-16 00:56:44 +0000126/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000127/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000128void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129 bool OmitOnError) {
130 if (OmitOnError && getDiags().hasErrorOccurred())
131 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000132 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000133 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000134 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000135 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000136}
137
Daniel Dunbar41071de2008-08-15 23:26:23 +0000138/// setGlobalVisibility - Set the visibility for the given LLVM
139/// GlobalValue according to the given clang AST visibility value.
140static void setGlobalVisibility(llvm::GlobalValue *GV,
141 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000142 switch (Vis) {
143 default: assert(0 && "Unknown visibility!");
144 case VisibilityAttr::DefaultVisibility:
145 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146 break;
147 case VisibilityAttr::HiddenVisibility:
148 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149 break;
150 case VisibilityAttr::ProtectedVisibility:
151 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152 break;
153 }
154}
155
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000156/// \brief Retrieves the mangled name for the given declaration.
157///
158/// If the given declaration requires a mangled name, returns an
159/// IdentifierInfo* containing the mangled name. Otherwise, returns
160/// the name of the declaration as an identifier.
161///
162/// FIXME: Returning an IdentifierInfo* here is a total hack. We
163/// really need some kind of string abstraction that either stores a
164/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbarb5da3e92009-02-18 22:52:09 +0000165/// changes to the GlobalDeclMap, too. (I disagree, I think what we
166/// actually need is for Sema to provide some notion of which Decls
167/// refer to the same semantic decl. We shouldn't need to mangle the
168/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000169///
170/// FIXME: Performance here is going to be terribly until we start
171/// caching mangled names. However, we should fix the problem above
172/// first.
Douglas Gregor6ec36682009-02-18 23:53:56 +0000173const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
174 llvm::SmallString<256> Name;
175 llvm::raw_svector_ostream Out(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000176 if (!mangleName(ND, Context, Out))
Douglas Gregor6ec36682009-02-18 23:53:56 +0000177 return ND->getIdentifier()->getName();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000178
Douglas Gregor6ec36682009-02-18 23:53:56 +0000179 Name += '\0';
180 return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
181 .getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000182}
183
Chris Lattner6d397602008-03-14 17:18:18 +0000184/// AddGlobalCtor - Add a function to the list that will be called before
185/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000187 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000188 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000189}
190
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000191/// AddGlobalDtor - Add a function to the list that will be called
192/// when the module is unloaded.
193void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000194 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000195 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
196}
197
198void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
199 // Ctor function type is void()*.
200 llvm::FunctionType* CtorFTy =
201 llvm::FunctionType::get(llvm::Type::VoidTy,
202 std::vector<const llvm::Type*>(),
203 false);
204 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
205
206 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000207 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000208 llvm::StructType::get(llvm::Type::Int32Ty,
209 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000210
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000211 // Construct the constructor and destructor arrays.
212 std::vector<llvm::Constant*> Ctors;
213 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
214 std::vector<llvm::Constant*> S;
215 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
216 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
217 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000218 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000219
220 if (!Ctors.empty()) {
221 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
222 new llvm::GlobalVariable(AT, false,
223 llvm::GlobalValue::AppendingLinkage,
224 llvm::ConstantArray::get(AT, Ctors),
225 GlobalName,
226 &TheModule);
227 }
Chris Lattner6d397602008-03-14 17:18:18 +0000228}
229
Nate Begeman532485c2008-04-18 23:43:57 +0000230void CodeGenModule::EmitAnnotations() {
231 if (Annotations.empty())
232 return;
233
234 // Create a new global variable for the ConstantStruct in the Module.
235 llvm::Constant *Array =
236 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
237 Annotations.size()),
238 Annotations);
239 llvm::GlobalValue *gv =
240 new llvm::GlobalVariable(Array->getType(), false,
241 llvm::GlobalValue::AppendingLinkage, Array,
242 "llvm.global.annotations", &TheModule);
243 gv->setSection("llvm.metadata");
244}
245
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000246void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
247 bool IsInternal,
248 bool IsInline,
249 llvm::GlobalValue *GV,
250 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000251 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000252 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000253 if (!ForDefinition) {
254 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000255 if (D->getAttr<DLLImportAttr>()) {
256 // The dllimport attribute is overridden by a subsequent declaration as
257 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000258 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000259 // dllimport attribute can be applied only to function decls, not to
260 // definitions.
261 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
262 if (!FD->getBody())
263 GV->setLinkage(llvm::Function::DLLImportLinkage);
264 } else
265 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000266 }
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000267 } else if (D->getAttr<WeakAttr>())
268 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000269 } else {
270 if (IsInternal) {
271 GV->setLinkage(llvm::Function::InternalLinkage);
272 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000273 if (D->getAttr<DLLExportAttr>()) {
274 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
275 // The dllexport attribute is ignored for undefined symbols.
276 if (FD->getBody())
277 GV->setLinkage(llvm::Function::DLLExportLinkage);
278 } else
279 GV->setLinkage(llvm::Function::DLLExportLinkage);
280 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000281 GV->setLinkage(llvm::Function::WeakLinkage);
282 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000283 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000284
Daniel Dunbar49988882009-01-13 02:25:00 +0000285 // FIXME: Figure out the relative priority of the attribute,
286 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000287 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000288 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000289 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000290
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000291 // Prefaced with special LLVM marker to indicate that the name
292 // should not be munged.
293 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
Daniel Dunbara735ad82008-08-06 00:03:29 +0000294 GV->setName("\01" + ALA->getLabel());
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000295
296 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
297 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000298
299 // Only add to llvm.used when we see a definition, otherwise we
300 // might add multiple times or risk the value being replaced by a
301 // subsequent RAUW.
302 if (ForDefinition) {
303 if (D->getAttr<UsedAttr>())
304 AddUsedGlobal(GV);
305 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000306}
307
Devang Patel761d7f72008-09-25 21:02:23 +0000308void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000309 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000310 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000311 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000312 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000313
Devang Patel761d7f72008-09-25 21:02:23 +0000314 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
315 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000316
317 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000318 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000319 F->setCallingConv(llvm::CallingConv::X86_FastCall);
320
321 if (D->getAttr<StdCallAttr>())
322 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000323}
324
325/// SetFunctionAttributesForDefinition - Set function attributes
326/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000327void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
328 llvm::Function *F) {
329 if (isa<ObjCMethodDecl>(D)) {
330 SetGlobalValueAttributes(D, true, false, F, true);
331 } else {
332 const FunctionDecl *FD = cast<FunctionDecl>(D);
333 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
334 FD->isInline(), F, true);
335 }
336
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000337 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000338 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000339
340 if (D->getAttr<AlwaysInlineAttr>())
341 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000342
343 if (D->getAttr<NoinlineAttr>())
344 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000345}
346
347void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
348 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000349 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000350
Daniel Dunbar219df662008-09-08 23:44:31 +0000351 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000352}
353
354void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
355 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000356 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000357
Daniel Dunbar219df662008-09-08 23:44:31 +0000358 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
359 FD->isInline(), F, false);
360}
361
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000362
Daniel Dunbar219df662008-09-08 23:44:31 +0000363void CodeGenModule::EmitAliases() {
364 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
365 const FunctionDecl *D = Aliases[i];
366 const AliasAttr *AA = D->getAttr<AliasAttr>();
367
368 // This is something of a hack, if the FunctionDecl got overridden
369 // then its attributes will be moved to the new declaration. In
370 // this case the current decl has no alias attribute, but we will
371 // eventually see it.
372 if (!AA)
373 continue;
374
375 const std::string& aliaseeName = AA->getAliasee();
376 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
377 if (!aliasee) {
378 // FIXME: This isn't unsupported, this is just an error, which
379 // sema should catch, but...
380 ErrorUnsupported(D, "alias referencing a missing function");
381 continue;
382 }
383
384 llvm::GlobalValue *GA =
385 new llvm::GlobalAlias(aliasee->getType(),
386 llvm::Function::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000387 getMangledName(D), aliasee,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000388 &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000389
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000390 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar219df662008-09-08 23:44:31 +0000391 if (Entry) {
392 // If we created a dummy function for this then replace it.
393 GA->takeName(Entry);
394
395 llvm::Value *Casted =
396 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
397 Entry->replaceAllUsesWith(Casted);
398 Entry->eraseFromParent();
399
400 Entry = GA;
401 }
402
403 // Alias should never be internal or inline.
404 SetGlobalValueAttributes(D, false, false, GA, true);
405 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000406}
407
Daniel Dunbar02698712009-02-13 20:29:50 +0000408void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
409 assert(!GV->isDeclaration() &&
410 "Only globals with definition can force usage.");
411 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
412 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
413}
414
415void CodeGenModule::EmitLLVMUsed() {
416 // Don't create llvm.used if there is no need.
417 if (LLVMUsed.empty())
418 return;
419
420 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
421 LLVMUsed.size());
422 llvm::GlobalVariable *GV =
423 new llvm::GlobalVariable(ATy, false,
424 llvm::GlobalValue::AppendingLinkage,
425 llvm::ConstantArray::get(ATy, LLVMUsed),
426 "llvm.used", &getModule());
427
428 GV->setSection("llvm.metadata");
429}
430
431void CodeGenModule::EmitDeferred() {
432 // Emit code for any deferred decl which was used. Since a
433 // previously unused static decl may become used during the
434 // generation of code for a static function, iterate until no
435 // changes are made.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000436 bool Changed;
437 do {
438 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000439
Daniel Dunbar02698712009-02-13 20:29:50 +0000440 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
441 e = DeferredDecls.end(); i != e; ) {
Anders Carlssonb723f752009-01-04 02:08:04 +0000442 const ValueDecl *D = *i;
443
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000444 // Check if we have used a decl with the same name
445 // FIXME: The AST should have some sort of aggregate decls or
446 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000447 // FIXME: This is missing some important cases. For example, we
Daniel Dunbar73241df2009-02-13 21:18:01 +0000448 // need to check for uses in an alias.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000449 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000450 ++i;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000451 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000452 }
453
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000454 // Emit the definition.
455 EmitGlobalDefinition(D);
456
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000457 // Erase the used decl from the list.
Daniel Dunbar02698712009-02-13 20:29:50 +0000458 i = DeferredDecls.erase(i);
Anders Carlssonb723f752009-01-04 02:08:04 +0000459
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000460 // Remember that we made a change.
461 Changed = true;
462 }
463 } while (Changed);
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
521 if (FD->getStorageClass() != FunctionDecl::Static)
522 return false;
523 } else {
524 const VarDecl *VD = cast<VarDecl>(Global);
525 assert(VD->isFileVarDecl() && "Invalid decl.");
526
527 if (VD->getStorageClass() != VarDecl::Static)
528 return false;
529 }
530
531 return true;
532}
533
534void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
535 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000536 // Aliases are deferred until code for everything else has been
537 // emitted.
538 if (FD->getAttr<AliasAttr>()) {
539 assert(!FD->isThisDeclarationADefinition() &&
540 "Function alias cannot have a definition!");
541 Aliases.push_back(FD);
542 return;
543 }
544
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
Daniel Dunbar73241df2009-02-13 21:18:01 +0000557 // Defer code generation when possible.
558 if (MayDeferGeneration(Global)) {
Daniel Dunbar02698712009-02-13 20:29:50 +0000559 DeferredDecls.push_back(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000560 return;
561 }
562
563 // Otherwise emit the definition.
564 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000565}
566
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000567void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
568 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
569 EmitGlobalFunctionDefinition(FD);
570 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
571 EmitGlobalVarDefinition(VD);
572 } else {
573 assert(0 && "Invalid argument to EmitGlobalDefinition()");
574 }
575}
576
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000577 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000578 assert(D->hasGlobalStorage() && "Not a global variable");
579
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000580 QualType ASTTy = D->getType();
581 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000582 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000583
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000584 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000585 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar49988882009-01-13 02:25:00 +0000586 if (!Entry) {
587 llvm::GlobalVariable *GV =
588 new llvm::GlobalVariable(Ty, false,
589 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000590 0, getMangledName(D), &getModule(),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000591 0, ASTTy.getAddressSpace());
Daniel Dunbar49988882009-01-13 02:25:00 +0000592 Entry = GV;
593
594 // Handle things which are present even on external declarations.
595
596 // FIXME: This code is overly simple and should be merged with
597 // other global handling.
598
599 GV->setConstant(D->getType().isConstant(Context));
600
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000601 // FIXME: Merge with other attribute handling code.
602
Daniel Dunbar49988882009-01-13 02:25:00 +0000603 if (D->getStorageClass() == VarDecl::PrivateExtern)
604 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Daniel Dunbareda9a5e2009-02-21 00:24:10 +0000605
606 if (D->getAttr<WeakAttr>())
607 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Daniel Dunbar3f75c432009-03-04 17:31:19 +0000608
609 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
610 // Prefaced with special LLVM marker to indicate that the name
611 // should not be munged.
612 GV->setName("\01" + ALA->getLabel());
613 }
Daniel Dunbar49988882009-01-13 02:25:00 +0000614 }
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000615
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000616 // Make sure the result is of the correct type.
617 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000618}
619
620void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000621 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000622 QualType ASTTy = D->getType();
623 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000624
Chris Lattner8f32f712007-07-14 00:23:28 +0000625 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000626 // This is a tentative definition; tentative definitions are
627 // implicitly initialized with { 0 }
628 const llvm::Type* InitTy;
629 if (ASTTy->isIncompleteArrayType()) {
630 // An incomplete array is normally [ TYPE x 0 ], but we need
631 // to fix it to [ TYPE x 1 ].
632 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
633 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
634 } else {
635 InitTy = VarTy;
636 }
637 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000638 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000639 Init = EmitConstantExpr(D->getInit());
Eli Friedman6e656f42009-02-20 01:18:21 +0000640 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000641 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000642 QualType T = D->getInit()->getType();
643 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
644 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000645 }
646 const llvm::Type* InitType = Init->getType();
647
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000648 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000649 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
650
Eli Friedman77ba7082008-05-30 19:50:47 +0000651 if (!GV) {
652 GV = new llvm::GlobalVariable(InitType, false,
653 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000654 0, getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000655 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar232350d2009-02-19 05:36:41 +0000656
657 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
658 // If we already have this global and it has an initializer, then
659 // we are in the rare situation where we emitted the defining
660 // declaration of the global and are now being asked to emit a
661 // definition which would be common. This occurs, for example, in
662 // the following situation because statics can be emitted out of
663 // order:
664 //
665 // static int x;
666 // static int *y = &x;
667 // static int x = 10;
668 // int **z = &y;
669 //
670 // Bail here so we don't blow away the definition. Note that if we
671 // can't distinguish here if we emitted a definition with a null
672 // initializer, but this case is safe.
673 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
674 return;
675
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000676 } else if (GV->getType() !=
677 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000678 // We have a definition after a prototype with the wrong type.
679 // We must make a new GlobalVariable* and update everything that used OldGV
680 // (a declaration or tentative definition) with the new GlobalVariable*
681 // (which will be a definition).
682 //
683 // This happens if there is a prototype for a global (e.g. "extern int x[];")
684 // and then a definition of a different type (e.g. "int x[10];"). This also
685 // happens when an initializer has a different type from the type of the
686 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000687 //
688 // FIXME: This also ends up happening if there's a definition followed by
689 // a tentative definition! (Although Sema rejects that construct
690 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000691
692 // Save the old global
693 llvm::GlobalVariable *OldGV = GV;
694
695 // Make a new global with the correct type
696 GV = new llvm::GlobalVariable(InitType, false,
697 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000698 0, getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000699 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman77ba7082008-05-30 19:50:47 +0000700 // Steal the name of the old global
701 GV->takeName(OldGV);
702
703 // Replace all uses of the old global with the new global
704 llvm::Constant *NewPtrForOldDecl =
705 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
706 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000707
708 // Erase the old global, since it is no longer used.
709 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000710 }
Devang Patel8e53e722007-10-26 16:31:40 +0000711
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000712 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000713
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000714 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
715 SourceManager &SM = Context.getSourceManager();
716 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000717 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000718 }
719
Chris Lattner88a69ad2007-07-13 05:13:43 +0000720 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000721 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000722 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000723
Chris Lattnerddee4232008-03-03 03:28:21 +0000724 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000725 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000726 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000727
728 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
729 // Prefaced with special LLVM marker to indicate that the name
730 // should not be munged.
731 GV->setName("\01" + ALA->getLabel());
732 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000733
734 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000735 if (D->getStorageClass() == VarDecl::Static)
736 GV->setLinkage(llvm::Function::InternalLinkage);
737 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000738 GV->setLinkage(llvm::Function::DLLImportLinkage);
739 else if (D->getAttr<DLLExportAttr>())
740 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000741 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000742 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000743 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000744 // FIXME: This isn't right. This should handle common linkage and other
745 // stuff.
746 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000747 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000748 case VarDecl::Auto:
749 case VarDecl::Register:
750 assert(0 && "Can't have auto or register globals");
751 case VarDecl::None:
752 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000753 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000754 else
755 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000756 break;
757 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000758 // FIXME: common
759 break;
760
Chris Lattnerddee4232008-03-03 03:28:21 +0000761 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000762 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
763 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000764 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000765 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000766 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000767
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000768 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
769 GV->setSection(SA->getName());
770
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000771 if (D->getAttr<UsedAttr>())
772 AddUsedGlobal(GV);
773
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000774 // Emit global variable debug information.
775 CGDebugInfo *DI = getDebugInfo();
776 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000777 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000778 DI->EmitGlobalVariable(GV, D);
779 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000780}
Reid Spencer5f016e22007-07-11 17:01:13 +0000781
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000782llvm::GlobalValue *
Daniel Dunbard5d31802009-02-19 07:15:39 +0000783CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
784 const llvm::Type *Ty) {
785 if (!Ty)
786 Ty = getTypes().ConvertType(D->getType());
Daniel Dunbar219df662008-09-08 23:44:31 +0000787 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
788 llvm::Function::ExternalLinkage,
Douglas Gregor6ec36682009-02-18 23:53:56 +0000789 getMangledName(D),
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000790 &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000791 SetFunctionAttributes(D, F);
792 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000793}
794
795llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000796 QualType ASTTy = D->getType();
797 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
798 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000799
800 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000801 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000802 if (!Entry)
Daniel Dunbard5d31802009-02-19 07:15:39 +0000803 Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000804
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000805 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000806}
807
808void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000809 const llvm::FunctionType *Ty =
810 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
811
812 // As a special case, make sure that definitions of K&R function
813 // "type foo()" aren't declared as varargs (which forces the backend
814 // to do unnecessary work).
815 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
816 Ty = llvm::FunctionType::get(Ty->getReturnType(),
817 std::vector<const llvm::Type*>(),
818 false);
819
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000820 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000821 if (!Entry) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000822 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000823 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000824 // If the types mismatch then we have to rewrite the definition.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000825 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000826 // Otherwise, we have a definition after a prototype with the
827 // wrong type. F is the Function* for the one with the wrong
828 // type, we must make a new Function* and update everything that
829 // used F (a declaration) with the new Function* (which will be
830 // a definition).
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000831 //
Daniel Dunbard5d31802009-02-19 07:15:39 +0000832 // This happens if there is a prototype for a function
833 // (e.g. "int f()") and then a definition of a different type
834 // (e.g. "int f(int x)"). Start by making a new function of the
835 // correct type, RAUW, then steal the name.
836 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000837 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000838
839 // Replace uses of F with the Function we will endow with a body.
840 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000841 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
842 Entry->replaceAllUsesWith(NewPtrForOldDecl);
843
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000844 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000845 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000846 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000847
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000848 Entry = NewFn;
849 }
850 }
851
Daniel Dunbar219df662008-09-08 23:44:31 +0000852 llvm::Function *Fn = cast<llvm::Function>(Entry);
853 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000854
Daniel Dunbar219df662008-09-08 23:44:31 +0000855 SetFunctionAttributesForDefinition(D, Fn);
856
857 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
858 AddGlobalCtor(Fn, CA->getPriority());
859 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
860 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000861 }
862}
863
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000864llvm::Function *
865CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
866 const std::string &Name) {
867 llvm::Function *Fn = llvm::Function::Create(FTy,
868 llvm::Function::ExternalLinkage,
869 "", &TheModule);
870 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
871 return Fn;
872}
873
Chris Lattnerc5b88062008-02-06 05:08:19 +0000874void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
875 // Make sure that this type is translated.
876 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000877}
878
879
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000880/// getBuiltinLibFunction
Mike Stumpc136e6c2009-02-27 22:42:30 +0000881llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000882 if (BuiltinID > BuiltinFunctions.size())
883 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000884
Chris Lattner1426fec2007-12-13 00:38:03 +0000885 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
886 // a slot for it.
887 assert(BuiltinID && "Invalid Builtin ID");
Mike Stumpc136e6c2009-02-27 22:42:30 +0000888 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000889 if (FunctionSlot)
890 return FunctionSlot;
891
Douglas Gregor3e41d602009-02-13 23:20:09 +0000892 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
893 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
894 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000895
Douglas Gregor3e41d602009-02-13 23:20:09 +0000896 // Get the name, skip over the __builtin_ prefix (if necessary).
897 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
898 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
899 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000900
901 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000902 Builtin::Context::GetBuiltinTypeError Error;
903 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
904 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
905
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000906 const llvm::FunctionType *Ty =
907 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
908
909 // FIXME: This has a serious problem with code like this:
910 // void abs() {}
911 // ... __builtin_abs(x);
912 // The two versions of abs will collide. The fix is for the builtin to win,
913 // and for the existing one to be turned into a constantexpr cast of the
914 // builtin. In the case where the existing one is a static function, it
915 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000916 if (llvm::Function *Existing = getModule().getFunction(Name)) {
917 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
918 return FunctionSlot = Existing;
919 assert(Existing == 0 && "FIXME: Name collision");
920 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000921
Chris Lattner4667c4a2009-03-01 18:47:06 +0000922 llvm::GlobalValue *&ExistingFn =
923 GlobalDeclMap[getContext().Idents.get(Name).getName()];
924 if (ExistingFn)
925 return FunctionSlot = llvm::ConstantExpr::getBitCast(ExistingFn, Ty);
Mike Stumpc136e6c2009-02-27 22:42:30 +0000926
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000927 // FIXME: param attributes for sext/zext etc.
Chris Lattner4667c4a2009-03-01 18:47:06 +0000928 return FunctionSlot = ExistingFn =
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000929 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
930 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000931}
932
Chris Lattner7acda7c2007-12-18 00:25:38 +0000933llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
934 unsigned NumTys) {
935 return llvm::Intrinsic::getDeclaration(&getModule(),
936 (llvm::Intrinsic::ID)IID, Tys, NumTys);
937}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000938
Reid Spencer5f016e22007-07-11 17:01:13 +0000939llvm::Function *CodeGenModule::getMemCpyFn() {
940 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000941 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
942 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000943}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000944
Eli Friedman0c995092008-05-26 12:59:39 +0000945llvm::Function *CodeGenModule::getMemMoveFn() {
946 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000947 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
948 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000949}
950
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000951llvm::Function *CodeGenModule::getMemSetFn() {
952 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000953 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
954 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000955}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000956
Anders Carlssone3daa762008-11-15 18:54:24 +0000957static void appendFieldAndPadding(CodeGenModule &CGM,
958 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000959 FieldDecl *FieldD, FieldDecl *NextFieldD,
960 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000961 RecordDecl* RD, const llvm::StructType *STy)
962{
963 // Append the field.
964 Fields.push_back(Field);
965
Douglas Gregor44b43212008-12-11 16:49:14 +0000966 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000967
968 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000969 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000970 NextStructFieldNo = STy->getNumElements();
971 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000972 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000973 }
974
975 // Append padding
976 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
977 llvm::Constant *C =
978 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
979
980 Fields.push_back(C);
981 }
982}
983
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000984// We still need to work out the details of handling UTF-16.
985// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000986llvm::Constant *CodeGenModule::
987GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000988 llvm::StringMapEntry<llvm::Constant *> &Entry =
989 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
990
991 if (Entry.getValue())
992 return Entry.getValue();
993
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000994 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
995 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000996
997 if (!CFConstantStringClassRef) {
998 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
999 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001000
1001 // FIXME: This is fairly broken if
1002 // __CFConstantStringClassReference is already defined, in that it
1003 // will get renamed and the user will most likely see an opaque
1004 // error message. This is a general issue with relying on
1005 // particular names.
1006 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001007 new llvm::GlobalVariable(Ty, false,
1008 llvm::GlobalVariable::ExternalLinkage, 0,
1009 "__CFConstantStringClassReference",
1010 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001011
1012 // Decay array -> ptr
1013 CFConstantStringClassRef =
1014 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001015 }
1016
Anders Carlssone3daa762008-11-15 18:54:24 +00001017 QualType CFTy = getContext().getCFConstantStringType();
1018 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001019
Anders Carlssone3daa762008-11-15 18:54:24 +00001020 const llvm::StructType *STy =
1021 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1022
1023 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +00001024 RecordDecl::field_iterator Field = CFRD->field_begin();
1025
Anders Carlssonc9e20912007-08-21 00:21:21 +00001026 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001027 FieldDecl *CurField = *Field++;
1028 FieldDecl *NextField = *Field++;
1029 appendFieldAndPadding(*this, Fields, CurField, NextField,
1030 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001031
1032 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001033 CurField = NextField;
1034 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001035 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001036 appendFieldAndPadding(*this, Fields, CurField, NextField,
1037 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001038
1039 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001040 CurField = NextField;
1041 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001042 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001043 C = new llvm::GlobalVariable(C->getType(), true,
1044 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +00001045 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +00001046 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +00001047 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1048 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001049
1050 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001051 CurField = NextField;
1052 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001053 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001054 appendFieldAndPadding(*this, Fields, CurField, NextField,
1055 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001056
1057 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001058 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +00001059 llvm::GlobalVariable *GV =
1060 new llvm::GlobalVariable(C->getType(), true,
1061 llvm::GlobalVariable::InternalLinkage,
1062 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001063
Anders Carlsson0c678292007-11-01 00:41:52 +00001064 GV->setSection("__DATA,__cfstring");
1065 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001066
Anders Carlsson0c678292007-11-01 00:41:52 +00001067 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001068}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001069
Daniel Dunbar61432932008-08-13 23:20:05 +00001070/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001071/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001072std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001073 const char *StrData = E->getStrData();
1074 unsigned Len = E->getByteLength();
1075
1076 const ConstantArrayType *CAT =
1077 getContext().getAsConstantArrayType(E->getType());
1078 assert(CAT && "String isn't pointer or array!");
1079
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001080 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001081 std::string Str(StrData, StrData+Len);
1082 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001083
1084 if (E->isWide())
1085 RealLen *= getContext().Target.getWCharWidth()/8;
1086
Daniel Dunbar1e049762008-08-10 20:25:57 +00001087 Str.resize(RealLen, '\0');
1088
1089 return Str;
1090}
1091
Daniel Dunbar61432932008-08-13 23:20:05 +00001092/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1093/// constant array for the given string literal.
1094llvm::Constant *
1095CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1096 // FIXME: This can be more efficient.
1097 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1098}
1099
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001100/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1101/// array for the given ObjCEncodeExpr node.
1102llvm::Constant *
1103CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1104 std::string Str;
1105 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1106
1107 llvm::Constant *C = llvm::ConstantArray::get(Str);
1108 C = new llvm::GlobalVariable(C->getType(), true,
1109 llvm::GlobalValue::InternalLinkage,
1110 C, ".str", &getModule());
1111 return C;
1112}
1113
1114
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001115/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001116static llvm::Constant *GenerateStringLiteral(const std::string &str,
1117 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001118 CodeGenModule &CGM,
1119 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001120 // Create Constant for this string literal. Don't add a '\0'.
1121 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001122
1123 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001124 return new llvm::GlobalVariable(C->getType(), constant,
1125 llvm::GlobalValue::InternalLinkage,
1126 C, GlobalName ? GlobalName : ".str",
1127 &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001128}
1129
Daniel Dunbar61432932008-08-13 23:20:05 +00001130/// GetAddrOfConstantString - Returns a pointer to a character array
1131/// containing the literal. This contents are exactly that of the
1132/// given string, i.e. it will not be null terminated automatically;
1133/// see GetAddrOfConstantCString. Note that whether the result is
1134/// actually a pointer to an LLVM constant depends on
1135/// Feature.WriteableStrings.
1136///
1137/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001138llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1139 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001140 // Don't share any string literals if writable-strings is turned on.
1141 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001142 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001143
1144 llvm::StringMapEntry<llvm::Constant *> &Entry =
1145 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1146
1147 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001148 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001149
1150 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001151 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001152 Entry.setValue(C);
1153 return C;
1154}
Daniel Dunbar61432932008-08-13 23:20:05 +00001155
1156/// GetAddrOfConstantCString - Returns a pointer to a character
1157/// array containing the literal and a terminating '\-'
1158/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001159llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1160 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001161 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001162}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001163
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001164/// EmitObjCPropertyImplementations - Emit information for synthesized
1165/// properties for an implementation.
1166void CodeGenModule::EmitObjCPropertyImplementations(const
1167 ObjCImplementationDecl *D) {
1168 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1169 e = D->propimpl_end(); i != e; ++i) {
1170 ObjCPropertyImplDecl *PID = *i;
1171
1172 // Dynamic is just for type-checking.
1173 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1174 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1175
1176 // Determine which methods need to be implemented, some may have
1177 // been overridden. Note that ::isSynthesized is not the method
1178 // we want, that just indicates if the decl came from a
1179 // property. What we want to know is if the method is defined in
1180 // this implementation.
1181 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001182 CodeGenFunction(*this).GenerateObjCGetter(
1183 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001184 if (!PD->isReadOnly() &&
1185 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001186 CodeGenFunction(*this).GenerateObjCSetter(
1187 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001188 }
1189 }
1190}
1191
Daniel Dunbar41071de2008-08-15 23:26:23 +00001192/// EmitTopLevelDecl - Emit code for a single top level declaration.
1193void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1194 // If an error has occurred, stop code generation, but continue
1195 // parsing and semantic analysis (to ensure all warnings and errors
1196 // are emitted).
1197 if (Diags.hasErrorOccurred())
1198 return;
1199
1200 switch (D->getKind()) {
1201 case Decl::Function:
1202 case Decl::Var:
1203 EmitGlobal(cast<ValueDecl>(D));
1204 break;
1205
1206 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001207 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001208 break;
1209
1210 // Objective-C Decls
1211
1212 // Forward declarations, no (immediate) code generation.
1213 case Decl::ObjCClass:
1214 case Decl::ObjCCategory:
1215 case Decl::ObjCForwardProtocol:
1216 case Decl::ObjCInterface:
1217 break;
1218
1219 case Decl::ObjCProtocol:
1220 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1221 break;
1222
1223 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001224 // Categories have properties but don't support synthesize so we
1225 // can ignore them here.
1226
Daniel Dunbar41071de2008-08-15 23:26:23 +00001227 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1228 break;
1229
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001230 case Decl::ObjCImplementation: {
1231 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1232 EmitObjCPropertyImplementations(OMD);
1233 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001234 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001235 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001236 case Decl::ObjCMethod: {
1237 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1238 // If this is not a prototype, emit the body.
1239 if (OMD->getBody())
1240 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1241 break;
1242 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001243 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001244 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001245 break;
1246
1247 case Decl::LinkageSpec: {
1248 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1249 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001250 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001251 // FIXME: implement C++ linkage, C linkage works mostly by C
1252 // language reuse already.
1253 break;
1254 }
1255
1256 case Decl::FileScopeAsm: {
1257 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1258 std::string AsmString(AD->getAsmString()->getStrData(),
1259 AD->getAsmString()->getByteLength());
1260
1261 const std::string &S = getModule().getModuleInlineAsm();
1262 if (S.empty())
1263 getModule().setModuleInlineAsm(AsmString);
1264 else
1265 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1266 break;
1267 }
1268
1269 default:
1270 // Make sure we handled everything we should, every other kind is
1271 // a non-top-level decl. FIXME: Would be nice to have an
1272 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1273 // that easily.
1274 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1275 }
1276}