blob: b92776face028e072a09b2cb654384ab26292ddc [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
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#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"
Chris Lattnerbd360642009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000027#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000028#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000029#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000031#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33using namespace CodeGen;
34
35
Chris Lattnerbd360642009-03-26 05:00:52 +000036CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattnerfb97b032007-12-02 01:40:18 +000037 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerbd360642009-03-26 05:00:52 +000038 Diagnostic &diags)
39 : BlockModule(C, M, TD, Types, *this), Context(C),
40 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000041 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
42 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000043
Chris Lattner3c8f1532009-03-21 07:12:05 +000044 if (!Features.ObjC1)
45 Runtime = 0;
46 else if (!Features.NeXTRuntime)
47 Runtime = CreateGNUObjCRuntime(*this);
48 else if (Features.ObjCNonFragileABI)
49 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
50 else
51 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000052
53 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerbd360642009-03-26 05:00:52 +000054 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 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() {
Chris Lattner82227ff2009-03-22 21:21:57 +000063 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000064 if (Runtime)
65 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
66 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000067 EmitCtorList(GlobalCtors, "llvm.global_ctors");
68 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000069 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000070 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000071}
72
Daniel Dunbar488e9932008-08-16 00:56:44 +000073/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000074/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000075void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
76 bool OmitOnError) {
77 if (OmitOnError && getDiags().hasErrorOccurred())
78 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000079 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000080 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000081 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000082 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
83 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000084}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000085
Daniel Dunbar488e9932008-08-16 00:56:44 +000086/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000087/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000088void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
89 bool OmitOnError) {
90 if (OmitOnError && getDiags().hasErrorOccurred())
91 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000092 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000093 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000094 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000095 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000096}
97
Daniel Dunbar41071de2008-08-15 23:26:23 +000098/// setGlobalVisibility - Set the visibility for the given LLVM
99/// GlobalValue according to the given clang AST visibility value.
100static void setGlobalVisibility(llvm::GlobalValue *GV,
101 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000102 switch (Vis) {
103 default: assert(0 && "Unknown visibility!");
104 case VisibilityAttr::DefaultVisibility:
105 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
106 break;
107 case VisibilityAttr::HiddenVisibility:
108 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
109 break;
110 case VisibilityAttr::ProtectedVisibility:
111 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
112 break;
113 }
114}
115
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000116static void setGlobalOptionVisibility(llvm::GlobalValue *GV,
117 LangOptions::VisibilityMode Vis) {
118 switch (Vis) {
119 default: assert(0 && "Unknown visibility!");
120 case LangOptions::NonVisibility:
121 break;
122 case LangOptions::DefaultVisibility:
123 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
124 break;
125 case LangOptions::HiddenVisibility:
126 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
127 break;
128 case LangOptions::ProtectedVisibility:
129 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
130 break;
131 }
132}
133
134
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000135/// \brief Retrieves the mangled name for the given declaration.
136///
137/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000138/// const char* containing the mangled name. Otherwise, returns
139/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000140///
Douglas Gregor6ec36682009-02-18 23:53:56 +0000141const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000142 // In C, functions with no attributes never need to be mangled. Fastpath them.
143 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
144 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000145 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000146 }
147
Douglas Gregor6ec36682009-02-18 23:53:56 +0000148 llvm::SmallString<256> Name;
149 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000150 if (!mangleName(ND, Context, Out)) {
151 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000152 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000153 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000154
Douglas Gregor6ec36682009-02-18 23:53:56 +0000155 Name += '\0';
Chris Lattner3c8f1532009-03-21 07:12:05 +0000156 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000157}
158
Chris Lattner6d397602008-03-14 17:18:18 +0000159/// AddGlobalCtor - Add a function to the list that will be called before
160/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000161void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000162 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000163 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000164}
165
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000166/// AddGlobalDtor - Add a function to the list that will be called
167/// when the module is unloaded.
168void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000169 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000170 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
171}
172
173void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
174 // Ctor function type is void()*.
175 llvm::FunctionType* CtorFTy =
176 llvm::FunctionType::get(llvm::Type::VoidTy,
177 std::vector<const llvm::Type*>(),
178 false);
179 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
180
181 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000182 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000183 llvm::StructType::get(llvm::Type::Int32Ty,
184 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000185
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186 // Construct the constructor and destructor arrays.
187 std::vector<llvm::Constant*> Ctors;
188 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
189 std::vector<llvm::Constant*> S;
190 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
191 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
192 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000193 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000194
195 if (!Ctors.empty()) {
196 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
197 new llvm::GlobalVariable(AT, false,
198 llvm::GlobalValue::AppendingLinkage,
199 llvm::ConstantArray::get(AT, Ctors),
200 GlobalName,
201 &TheModule);
202 }
Chris Lattner6d397602008-03-14 17:18:18 +0000203}
204
Nate Begeman532485c2008-04-18 23:43:57 +0000205void CodeGenModule::EmitAnnotations() {
206 if (Annotations.empty())
207 return;
208
209 // Create a new global variable for the ConstantStruct in the Module.
210 llvm::Constant *Array =
211 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
212 Annotations.size()),
213 Annotations);
214 llvm::GlobalValue *gv =
215 new llvm::GlobalVariable(Array->getType(), false,
216 llvm::GlobalValue::AppendingLinkage, Array,
217 "llvm.global.annotations", &TheModule);
218 gv->setSection("llvm.metadata");
219}
220
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000221void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
222 bool IsInternal,
223 bool IsInline,
224 llvm::GlobalValue *GV,
225 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000226 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000227 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000228 if (!ForDefinition) {
229 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000230 if (D->getAttr<DLLImportAttr>()) {
231 // The dllimport attribute is overridden by a subsequent declaration as
232 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000233 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000234 // dllimport attribute can be applied only to function decls, not to
235 // definitions.
236 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
237 if (!FD->getBody())
238 GV->setLinkage(llvm::Function::DLLImportLinkage);
239 } else
240 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000241 }
Daniel Dunbar5e273142009-03-06 16:20:49 +0000242 } else if (D->getAttr<WeakAttr>() ||
243 D->getAttr<WeakImportAttr>()) {
244 // "extern_weak" is overloaded in LLVM; we probably should have
245 // separate linkage types for this.
Duncan Sandse3fedbe2009-03-11 08:40:02 +0000246 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000247 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000248 } else {
249 if (IsInternal) {
250 GV->setLinkage(llvm::Function::InternalLinkage);
251 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000252 if (D->getAttr<DLLExportAttr>()) {
253 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254 // The dllexport attribute is ignored for undefined symbols.
255 if (FD->getBody())
256 GV->setLinkage(llvm::Function::DLLExportLinkage);
257 } else
258 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000259 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
260 IsInline)
Mike Stump286acbd2009-03-07 16:33:28 +0000261 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000262 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000263 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000264
Daniel Dunbar49988882009-01-13 02:25:00 +0000265 // FIXME: Figure out the relative priority of the attribute,
266 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000267 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000268 setGlobalVisibility(GV, attr->getVisibility());
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000269 else
270 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
Daniel Dunbara735ad82008-08-06 00:03:29 +0000271
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000272 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
273 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000274
275 // Only add to llvm.used when we see a definition, otherwise we
276 // might add multiple times or risk the value being replaced by a
277 // subsequent RAUW.
278 if (ForDefinition) {
279 if (D->getAttr<UsedAttr>())
280 AddUsedGlobal(GV);
281 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000282}
283
Devang Patel761d7f72008-09-25 21:02:23 +0000284void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000285 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000286 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000287 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000288 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000289
Devang Patel761d7f72008-09-25 21:02:23 +0000290 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
291 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000292
293 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000294 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000295 F->setCallingConv(llvm::CallingConv::X86_FastCall);
296
297 if (D->getAttr<StdCallAttr>())
298 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Fariborz Jahanianee760332009-03-27 18:38:55 +0000299
300 if (D->getAttr<RegparmAttr>())
301 ErrorUnsupported(D, "regparm attribute");
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000302}
303
304/// SetFunctionAttributesForDefinition - Set function attributes
305/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000306void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
307 llvm::Function *F) {
308 if (isa<ObjCMethodDecl>(D)) {
309 SetGlobalValueAttributes(D, true, false, F, true);
310 } else {
311 const FunctionDecl *FD = cast<FunctionDecl>(D);
312 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
313 FD->isInline(), F, true);
314 }
315
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000316 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000317 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000318
319 if (D->getAttr<AlwaysInlineAttr>())
320 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000321
322 if (D->getAttr<NoinlineAttr>())
323 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000324}
325
326void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
327 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000328 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000329
Daniel Dunbar219df662008-09-08 23:44:31 +0000330 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000331}
332
333void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
334 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000335 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000336
Daniel Dunbar219df662008-09-08 23:44:31 +0000337 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
338 FD->isInline(), F, false);
339}
340
Daniel Dunbar02698712009-02-13 20:29:50 +0000341void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
342 assert(!GV->isDeclaration() &&
343 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000344 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000345}
346
347void CodeGenModule::EmitLLVMUsed() {
348 // Don't create llvm.used if there is no need.
349 if (LLVMUsed.empty())
350 return;
351
Chris Lattner35f38a22009-03-31 22:37:52 +0000352 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
353 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
354
355 // Convert LLVMUsed to what ConstantArray needs.
356 std::vector<llvm::Constant*> UsedArray;
357 UsedArray.resize(LLVMUsed.size());
358 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
359 UsedArray[i] =
360 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
361 }
362
Daniel Dunbar02698712009-02-13 20:29:50 +0000363 llvm::GlobalVariable *GV =
364 new llvm::GlobalVariable(ATy, false,
365 llvm::GlobalValue::AppendingLinkage,
Chris Lattner35f38a22009-03-31 22:37:52 +0000366 llvm::ConstantArray::get(ATy, UsedArray),
Daniel Dunbar02698712009-02-13 20:29:50 +0000367 "llvm.used", &getModule());
368
369 GV->setSection("llvm.metadata");
370}
371
372void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000373 // Emit code for any potentially referenced deferred decls. Since a
374 // previously unused static decl may become used during the generation of code
375 // for a static function, iterate until no changes are made.
376 while (!DeferredDeclsToEmit.empty()) {
377 const ValueDecl *D = DeferredDeclsToEmit.back();
378 DeferredDeclsToEmit.pop_back();
379
380 // The mangled name for the decl must have been emitted in GlobalDeclMap.
381 // Look it up to see if it was defined with a stronger definition (e.g. an
382 // extern inline function with a strong function redefinition). If so,
383 // just ignore the deferred decl.
384 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
385 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000386
Chris Lattner67b00522009-03-21 09:44:56 +0000387 if (!CGRef->isDeclaration())
388 continue;
389
390 // Otherwise, emit the definition and move on to the next one.
391 EmitGlobalDefinition(D);
392 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000393}
394
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000395/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
396/// annotation information for a given GlobalValue. The annotation struct is
397/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000398/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000399/// created from the AnnotateAttr's annotation. The third field is a constant
400/// string containing the name of the translation unit. The fourth field is
401/// the line number in the file of the annotated value declaration.
402///
403/// FIXME: this does not unique the annotation string constants, as llvm-gcc
404/// appears to.
405///
406llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
407 const AnnotateAttr *AA,
408 unsigned LineNo) {
409 llvm::Module *M = &getModule();
410
411 // get [N x i8] constants for the annotation string, and the filename string
412 // which are the 2nd and 3rd elements of the global annotation structure.
413 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
414 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
415 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
416 true);
417
418 // Get the two global values corresponding to the ConstantArrays we just
419 // created to hold the bytes of the strings.
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000420 const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000421 llvm::GlobalValue *annoGV =
422 new llvm::GlobalVariable(anno->getType(), false,
423 llvm::GlobalValue::InternalLinkage, anno,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000424 GV->getName() + StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000425 // translation unit name string, emitted into the llvm.metadata section.
426 llvm::GlobalValue *unitGV =
427 new llvm::GlobalVariable(unit->getType(), false,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000428 llvm::GlobalValue::InternalLinkage, unit,
429 StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000430
431 // Create the ConstantStruct that is the global annotion.
432 llvm::Constant *Fields[4] = {
433 llvm::ConstantExpr::getBitCast(GV, SBP),
434 llvm::ConstantExpr::getBitCast(annoGV, SBP),
435 llvm::ConstantExpr::getBitCast(unitGV, SBP),
436 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
437 };
438 return llvm::ConstantStruct::get(Fields, 4, false);
439}
440
Daniel Dunbar73241df2009-02-13 21:18:01 +0000441bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000442 // Never defer when EmitAllDecls is specified or the decl has
443 // attribute used.
444 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000445 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000446
447 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000448 // Constructors and destructors should never be deferred.
449 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
450 return false;
451
Chris Lattner99b53612009-03-21 08:03:33 +0000452 // FIXME: What about inline, and/or extern inline?
Daniel Dunbar73241df2009-02-13 21:18:01 +0000453 if (FD->getStorageClass() != FunctionDecl::Static)
454 return false;
455 } else {
456 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner99b53612009-03-21 08:03:33 +0000457 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbar73241df2009-02-13 21:18:01 +0000458
459 if (VD->getStorageClass() != VarDecl::Static)
460 return false;
461 }
462
463 return true;
464}
465
466void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattnerbd532712009-03-22 21:47:11 +0000467 // If this is an alias definition (which otherwise looks like a declaration)
468 // emit it now.
469 if (Global->getAttr<AliasAttr>())
470 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000471
Chris Lattner67b00522009-03-21 09:44:56 +0000472 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000473 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000474 // Forward declarations are emitted lazily on first use.
475 if (!FD->isThisDeclarationADefinition())
476 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000477 } else {
478 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000479 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
480
Daniel Dunbar73241df2009-02-13 21:18:01 +0000481 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000482 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000483 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000484 }
485
Chris Lattner67b00522009-03-21 09:44:56 +0000486 // Defer code generation when possible if this is a static definition, inline
487 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000488 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000489 // If the value has already been used, add it directly to the
490 // DeferredDeclsToEmit list.
491 const char *MangledName = getMangledName(Global);
492 if (GlobalDeclMap.count(MangledName))
493 DeferredDeclsToEmit.push_back(Global);
494 else {
495 // Otherwise, remember that we saw a deferred decl with this name. The
496 // first use of the mangled name will cause it to move into
497 // DeferredDeclsToEmit.
498 DeferredDecls[MangledName] = Global;
499 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000500 return;
501 }
502
503 // Otherwise emit the definition.
504 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000505}
506
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000507void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
508 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
509 EmitGlobalFunctionDefinition(FD);
510 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
511 EmitGlobalVarDefinition(VD);
512 } else {
513 assert(0 && "Invalid argument to EmitGlobalDefinition()");
514 }
515}
516
Chris Lattner74391b42009-03-22 21:03:39 +0000517/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
518/// module, create and return an llvm Function with the specified type. If there
519/// is something in the module with the specified name, return it potentially
520/// bitcasted to the right type.
521///
522/// If D is non-null, it specifies a decl that correspond to this. This is used
523/// to set the attributes on the function when it is first created.
524llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
525 const llvm::Type *Ty,
526 const FunctionDecl *D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000527 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000528 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
529 if (Entry) {
530 if (Entry->getType()->getElementType() == Ty)
531 return Entry;
532
533 // Make sure the result is of the correct type.
534 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
535 return llvm::ConstantExpr::getBitCast(Entry, PTy);
536 }
537
Chris Lattner67b00522009-03-21 09:44:56 +0000538 // This is the first use or definition of a mangled name. If there is a
539 // deferred decl with this name, remember that we need to emit it at the end
540 // of the file.
541 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattner74391b42009-03-22 21:03:39 +0000542 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000543 if (DDI != DeferredDecls.end()) {
544 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
545 // list, and remove it from DeferredDecls (since we don't need it anymore).
546 DeferredDeclsToEmit.push_back(DDI->second);
547 DeferredDecls.erase(DDI);
548 }
549
Chris Lattner0558e792009-03-21 09:25:43 +0000550 // This function doesn't have a complete type (for example, the return
551 // type is an incomplete struct). Use a fake type instead, and make
552 // sure not to try to set attributes.
553 bool ShouldSetAttributes = true;
554 if (!isa<llvm::FunctionType>(Ty)) {
555 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
556 std::vector<const llvm::Type*>(), false);
557 ShouldSetAttributes = false;
558 }
559 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
560 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000561 "", &getModule());
562 F->setName(MangledName);
Chris Lattner74391b42009-03-22 21:03:39 +0000563 if (D && ShouldSetAttributes)
Chris Lattner0558e792009-03-21 09:25:43 +0000564 SetFunctionAttributes(D, F);
565 Entry = F;
566 return F;
567}
568
Chris Lattner74391b42009-03-22 21:03:39 +0000569/// GetAddrOfFunction - Return the address of the given function. If Ty is
570/// non-null, then this function will use the specified type if it has to
571/// create it (this occurs when we see a definition of the function).
572llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
573 const llvm::Type *Ty) {
574 // If there was no specific requested type, just convert it now.
575 if (!Ty)
576 Ty = getTypes().ConvertType(D->getType());
577 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
578}
Eli Friedman77ba7082008-05-30 19:50:47 +0000579
Chris Lattner74391b42009-03-22 21:03:39 +0000580/// CreateRuntimeFunction - Create a new runtime function with the specified
581/// type and name.
582llvm::Constant *
583CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
584 const char *Name) {
585 // Convert Name to be a uniqued string from the IdentifierInfo table.
586 Name = getContext().Idents.get(Name).getName();
587 return GetOrCreateLLVMFunction(Name, FTy, 0);
588}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000589
Chris Lattner74391b42009-03-22 21:03:39 +0000590/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
591/// create and return an llvm GlobalVariable with the specified type. If there
592/// is something in the module with the specified name, return it potentially
593/// bitcasted to the right type.
594///
595/// If D is non-null, it specifies a decl that correspond to this. This is used
596/// to set the attributes on the global when it is first created.
597llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
598 const llvm::PointerType*Ty,
599 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000600 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000601 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000602 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000603 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000604 return Entry;
605
Chris Lattner99b53612009-03-21 08:03:33 +0000606 // Make sure the result is of the correct type.
Chris Lattner74391b42009-03-22 21:03:39 +0000607 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000608 }
Chris Lattner67b00522009-03-21 09:44:56 +0000609
610 // This is the first use or definition of a mangled name. If there is a
611 // deferred decl with this name, remember that we need to emit it at the end
612 // of the file.
613 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
614 DeferredDecls.find(MangledName);
615 if (DDI != DeferredDecls.end()) {
616 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
617 // list, and remove it from DeferredDecls (since we don't need it anymore).
618 DeferredDeclsToEmit.push_back(DDI->second);
619 DeferredDecls.erase(DDI);
620 }
621
Chris Lattner99b53612009-03-21 08:03:33 +0000622 llvm::GlobalVariable *GV =
Chris Lattner74391b42009-03-22 21:03:39 +0000623 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000624 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000625 0, "", &getModule(),
Chris Lattner74391b42009-03-22 21:03:39 +0000626 0, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000627 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000628
629 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000630 if (D) {
631 // FIXME: This code is overly simple and should be merged with
632 // other global handling.
633 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000634
Chris Lattner74391b42009-03-22 21:03:39 +0000635 // FIXME: Merge with other attribute handling code.
636 if (D->getStorageClass() == VarDecl::PrivateExtern)
637 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000638
Chris Lattner74391b42009-03-22 21:03:39 +0000639 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
640 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
641 }
642
Chris Lattner99b53612009-03-21 08:03:33 +0000643 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000644}
645
Chris Lattner74391b42009-03-22 21:03:39 +0000646
647/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
648/// given global variable. If Ty is non-null and if the global doesn't exist,
649/// then it will be greated with the specified type instead of whatever the
650/// normal requested type would be.
651llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
652 const llvm::Type *Ty) {
653 assert(D->hasGlobalStorage() && "Not a global variable");
654 QualType ASTTy = D->getType();
655 if (Ty == 0)
656 Ty = getTypes().ConvertTypeForMem(ASTTy);
657
658 const llvm::PointerType *PTy =
659 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
660 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
661}
662
663/// CreateRuntimeVariable - Create a new runtime global variable with the
664/// specified type and name.
665llvm::Constant *
666CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
667 const char *Name) {
668 // Convert Name to be a uniqued string from the IdentifierInfo table.
669 Name = getContext().Idents.get(Name).getName();
670 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
671}
672
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000673void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000674 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000675 QualType ASTTy = D->getType();
Eli Friedman77ba7082008-05-30 19:50:47 +0000676
Chris Lattner8f32f712007-07-14 00:23:28 +0000677 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000678 // This is a tentative definition; tentative definitions are
679 // implicitly initialized with { 0 }
Chris Lattner570585c2009-03-21 09:16:30 +0000680 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000681 if (ASTTy->isIncompleteArrayType()) {
682 // An incomplete array is normally [ TYPE x 0 ], but we need
683 // to fix it to [ TYPE x 1 ].
Chris Lattner570585c2009-03-21 09:16:30 +0000684 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000685 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000686 }
687 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000688 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000689 Init = EmitConstantExpr(D->getInit());
Eli Friedman6e656f42009-02-20 01:18:21 +0000690 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000691 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000692 QualType T = D->getInit()->getType();
693 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
694 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000695 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000696
Chris Lattner2d584062009-03-21 08:13:05 +0000697 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000698 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000699
Chris Lattner570585c2009-03-21 09:16:30 +0000700 // Strip off a bitcast if we got one back.
701 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
702 assert(CE->getOpcode() == llvm::Instruction::BitCast);
703 Entry = CE->getOperand(0);
704 }
705
706 // Entry is now either a Function or GlobalVariable.
707 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
708
709 // If we already have this global and it has an initializer, then
710 // we are in the rare situation where we emitted the defining
711 // declaration of the global and are now being asked to emit a
712 // definition which would be common. This occurs, for example, in
713 // the following situation because statics can be emitted out of
714 // order:
715 //
716 // static int x;
717 // static int *y = &x;
718 // static int x = 10;
719 // int **z = &y;
720 //
721 // Bail here so we don't blow away the definition. Note that if we
722 // can't distinguish here if we emitted a definition with a null
723 // initializer, but this case is safe.
724 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000725 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
726 return;
Chris Lattner570585c2009-03-21 09:16:30 +0000727 }
728
729 // We have a definition after a declaration with the wrong type.
730 // We must make a new GlobalVariable* and update everything that used OldGV
731 // (a declaration or tentative definition) with the new GlobalVariable*
732 // (which will be a definition).
733 //
734 // This happens if there is a prototype for a global (e.g.
735 // "extern int x[];") and then a definition of a different type (e.g.
736 // "int x[10];"). This also happens when an initializer has a different type
737 // from the type of the global (this happens with unions).
738 //
739 // FIXME: This also ends up happening if there's a definition followed by
740 // a tentative definition! (Although Sema rejects that construct
741 // at the moment.)
742 if (GV == 0 ||
743 GV->getType()->getElementType() != InitType ||
744 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
745
746 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
747 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000748
Chris Lattner570585c2009-03-21 09:16:30 +0000749 // Make a new global with the correct type, this is now guaranteed to work.
750 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000751 GV->takeName(cast<llvm::GlobalValue>(Entry));
752
Eli Friedman77ba7082008-05-30 19:50:47 +0000753 // Replace all uses of the old global with the new global
754 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000755 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
756 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000757
758 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +0000759 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000760 }
Devang Patel8e53e722007-10-26 16:31:40 +0000761
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000762 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
763 SourceManager &SM = Context.getSourceManager();
764 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000765 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000766 }
767
Chris Lattner88a69ad2007-07-13 05:13:43 +0000768 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000769 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000770 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000771
Chris Lattnerddee4232008-03-03 03:28:21 +0000772 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000773 setGlobalVisibility(GV, attr->getVisibility());
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000774 else
775 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
Daniel Dunbara735ad82008-08-06 00:03:29 +0000776
Chris Lattner88a69ad2007-07-13 05:13:43 +0000777 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000778 if (D->getStorageClass() == VarDecl::Static)
779 GV->setLinkage(llvm::Function::InternalLinkage);
780 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000781 GV->setLinkage(llvm::Function::DLLImportLinkage);
782 else if (D->getAttr<DLLExportAttr>())
783 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000784 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000785 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000786 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000787 // FIXME: This isn't right. This should handle common linkage and other
788 // stuff.
789 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000790 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000791 case VarDecl::Auto:
792 case VarDecl::Register:
793 assert(0 && "Can't have auto or register globals");
794 case VarDecl::None:
Chris Lattnerbd360642009-03-26 05:00:52 +0000795 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sandsceb77d92009-03-11 20:15:27 +0000796 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000797 else
798 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000799 break;
800 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000801 // FIXME: common
802 break;
803
Chris Lattnerddee4232008-03-03 03:28:21 +0000804 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000805 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
806 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000807 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000808 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000809 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000810
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000811 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
812 GV->setSection(SA->getName());
813
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000814 if (D->getAttr<UsedAttr>())
815 AddUsedGlobal(GV);
816
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000817 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000818 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000819 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000820 DI->EmitGlobalVariable(GV, D);
821 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000822}
Reid Spencer5f016e22007-07-11 17:01:13 +0000823
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000824
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000825void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbard5d31802009-02-19 07:15:39 +0000826 const llvm::FunctionType *Ty =
827 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
828
829 // As a special case, make sure that definitions of K&R function
830 // "type foo()" aren't declared as varargs (which forces the backend
831 // to do unnecessary work).
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000832 if (D->getType()->isFunctionNoProtoType()) {
833 assert(Ty->isVarArg() && "Didn't lower type as expected");
834 // Due to stret, the lowered function could have arguments. Just create the
835 // same type as was lowered by ConvertType but strip off the varargs bit.
836 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
837 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
838 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000839
Chris Lattner34809502009-03-21 08:53:37 +0000840 // Get or create the prototype for teh function.
Chris Lattner0558e792009-03-21 09:25:43 +0000841 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000842
Chris Lattner0558e792009-03-21 09:25:43 +0000843 // Strip off a bitcast if we got one back.
844 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
845 assert(CE->getOpcode() == llvm::Instruction::BitCast);
846 Entry = CE->getOperand(0);
847 }
848
849
850 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +0000851 // If the types mismatch then we have to rewrite the definition.
Chris Lattner0558e792009-03-21 09:25:43 +0000852 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
853 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000854
Chris Lattner62b33ea2009-03-21 08:38:50 +0000855 // F is the Function* for the one with the wrong type, we must make a new
856 // Function* and update everything that used F (a declaration) with the new
857 // Function* (which will be a definition).
858 //
859 // This happens if there is a prototype for a function
860 // (e.g. "int f()") and then a definition of a different type
861 // (e.g. "int f(int x)"). Start by making a new function of the
862 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +0000863 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner0558e792009-03-21 09:25:43 +0000864 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
865 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattner62b33ea2009-03-21 08:38:50 +0000866
867 // Replace uses of F with the Function we will endow with a body.
868 llvm::Constant *NewPtrForOldDecl =
Chris Lattner0558e792009-03-21 09:25:43 +0000869 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
870 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner62b33ea2009-03-21 08:38:50 +0000871
872 // Ok, delete the old function now, which is dead.
Chris Lattner0558e792009-03-21 09:25:43 +0000873 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +0000874
Chris Lattner0558e792009-03-21 09:25:43 +0000875 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000876 }
Chris Lattner0558e792009-03-21 09:25:43 +0000877
878 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000879
Daniel Dunbar219df662008-09-08 23:44:31 +0000880 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000881
Daniel Dunbar219df662008-09-08 23:44:31 +0000882 SetFunctionAttributesForDefinition(D, Fn);
883
Chris Lattner34809502009-03-21 08:53:37 +0000884 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000885 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattner34809502009-03-21 08:53:37 +0000886 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000887 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000888}
889
Chris Lattnerbd532712009-03-22 21:47:11 +0000890void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
891 const AliasAttr *AA = D->getAttr<AliasAttr>();
892 assert(AA && "Not an alias?");
893
894 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
895
896 // Unique the name through the identifier table.
897 const char *AliaseeName = AA->getAliasee().c_str();
898 AliaseeName = getContext().Idents.get(AliaseeName).getName();
899
900 // Create a reference to the named value. This ensures that it is emitted
901 // if a deferred decl.
902 llvm::Constant *Aliasee;
903 if (isa<llvm::FunctionType>(DeclTy))
904 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
905 else
906 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
907 llvm::PointerType::getUnqual(DeclTy), 0);
908
909 // Create the new alias itself, but don't set a name yet.
910 llvm::GlobalValue *GA =
911 new llvm::GlobalAlias(Aliasee->getType(),
912 llvm::Function::ExternalLinkage,
913 "", Aliasee, &getModule());
914
915 // See if there is already something with the alias' name in the module.
916 const char *MangledName = getMangledName(D);
917 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
918
919 if (Entry && !Entry->isDeclaration()) {
920 // If there is a definition in the module, then it wins over the alias.
921 // This is dubious, but allow it to be safe. Just ignore the alias.
922 GA->eraseFromParent();
923 return;
924 }
925
926 if (Entry) {
927 // If there is a declaration in the module, then we had an extern followed
928 // by the alias, as in:
929 // extern int test6();
930 // ...
931 // int test6() __attribute__((alias("test7")));
932 //
933 // Remove it and replace uses of it with the alias.
934
935 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
936 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +0000937 Entry->eraseFromParent();
938 }
939
940 // Now we know that there is no conflict, set the name.
941 Entry = GA;
942 GA->setName(MangledName);
943
944 // Alias should never be internal or inline.
945 SetGlobalValueAttributes(D, false, false, GA, true);
946}
947
Chris Lattnerb808c952009-03-22 21:56:56 +0000948/// getBuiltinLibFunction - Given a builtin id for a function like
949/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +0000950llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +0000951 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
952 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
953 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000954
Douglas Gregor3e41d602009-02-13 23:20:09 +0000955 // Get the name, skip over the __builtin_ prefix (if necessary).
956 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
957 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
958 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000959
960 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000961 Builtin::Context::GetBuiltinTypeError Error;
962 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
963 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
964
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000965 const llvm::FunctionType *Ty =
966 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
967
Chris Lattnerb808c952009-03-22 21:56:56 +0000968 // Unique the name through the identifier table.
969 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000970 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb808c952009-03-22 21:56:56 +0000971 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000972}
973
Chris Lattner7acda7c2007-12-18 00:25:38 +0000974llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
975 unsigned NumTys) {
976 return llvm::Intrinsic::getDeclaration(&getModule(),
977 (llvm::Intrinsic::ID)IID, Tys, NumTys);
978}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000979
Reid Spencer5f016e22007-07-11 17:01:13 +0000980llvm::Function *CodeGenModule::getMemCpyFn() {
981 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000982 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
983 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000984}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000985
Eli Friedman0c995092008-05-26 12:59:39 +0000986llvm::Function *CodeGenModule::getMemMoveFn() {
987 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000988 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
989 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000990}
991
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000992llvm::Function *CodeGenModule::getMemSetFn() {
993 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000994 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
995 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000996}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000997
Anders Carlssone3daa762008-11-15 18:54:24 +0000998static void appendFieldAndPadding(CodeGenModule &CGM,
999 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001000 FieldDecl *FieldD, FieldDecl *NextFieldD,
1001 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001002 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001003 // Append the field.
1004 Fields.push_back(Field);
1005
Douglas Gregor44b43212008-12-11 16:49:14 +00001006 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001007
1008 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001009 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001010 NextStructFieldNo = STy->getNumElements();
1011 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001012 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001013 }
1014
1015 // Append padding
1016 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1017 llvm::Constant *C =
1018 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1019
1020 Fields.push_back(C);
1021 }
1022}
1023
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001024llvm::Constant *CodeGenModule::
Steve Naroff8d4141f2009-04-01 13:55:36 +00001025GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroffb59212a2009-04-01 21:16:31 +00001026 std::string str;
1027 unsigned StringLength;
1028
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001029 bool isUTF16 = false;
1030 if (Literal->containsNonAsciiOrNull()) {
1031 // Convert from UTF-8 to UTF-16.
1032 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1033 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1034 UTF16 *ToPtr = &ToBuf[0];
1035
1036 ConversionResult Result;
1037 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1038 &ToPtr, ToPtr+Literal->getByteLength(),
1039 strictConversion);
1040 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroffb59212a2009-04-01 21:16:31 +00001041
Steve Naroffdb6d4f62009-04-03 09:44:50 +00001042 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1043 // without doing more surgery to this routine. Since we aren't explicitly
1044 // checking for endianness here, it's also a bug (when generating code for
1045 // a target that doesn't match the host endianness). Modeling this as an i16
1046 // array is likely the cleanest solution.
Steve Naroffb59212a2009-04-01 21:16:31 +00001047 StringLength = ToPtr-&ToBuf[0];
1048 str.assign((char *)&ToBuf[0], StringLength*2); // Twice as many UTF8 chars.
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001049 isUTF16 = true;
Steve Naroffb59212a2009-04-01 21:16:31 +00001050 } else {
1051 str.assign(Literal->getStrData(), Literal->getByteLength());
1052 StringLength = str.length();
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001053 }
Anders Carlssonc9e20912007-08-21 00:21:21 +00001054 llvm::StringMapEntry<llvm::Constant *> &Entry =
1055 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1056
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001057 if (llvm::Constant *C = Entry.getValue())
1058 return C;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001059
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001060 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1061 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001062
1063 if (!CFConstantStringClassRef) {
1064 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1065 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001066
1067 // FIXME: This is fairly broken if
1068 // __CFConstantStringClassReference is already defined, in that it
1069 // will get renamed and the user will most likely see an opaque
1070 // error message. This is a general issue with relying on
1071 // particular names.
1072 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001073 new llvm::GlobalVariable(Ty, false,
1074 llvm::GlobalVariable::ExternalLinkage, 0,
1075 "__CFConstantStringClassReference",
1076 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001077
1078 // Decay array -> ptr
1079 CFConstantStringClassRef =
1080 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001081 }
1082
Anders Carlssone3daa762008-11-15 18:54:24 +00001083 QualType CFTy = getContext().getCFConstantStringType();
1084 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001085
Anders Carlssone3daa762008-11-15 18:54:24 +00001086 const llvm::StructType *STy =
1087 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1088
1089 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +00001090 RecordDecl::field_iterator Field = CFRD->field_begin();
1091
Anders Carlssonc9e20912007-08-21 00:21:21 +00001092 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001093 FieldDecl *CurField = *Field++;
1094 FieldDecl *NextField = *Field++;
1095 appendFieldAndPadding(*this, Fields, CurField, NextField,
1096 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001097
1098 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001099 CurField = NextField;
1100 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001101 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001102 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001103 isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1104 : llvm::ConstantInt::get(Ty, 0x07C8),
1105 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001106
1107 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001108 CurField = NextField;
1109 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001110 llvm::Constant *C = llvm::ConstantArray::get(str);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001111
1112 const char *Sect, *Prefix;
1113 bool isConstant;
1114 if (isUTF16) {
1115 Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1116 Sect = getContext().Target.getUnicodeStringSection();
1117 // FIXME: Why does GCC not set constant here?
1118 isConstant = false;
1119 } else {
1120 Prefix = getContext().Target.getStringSymbolPrefix(true);
1121 Sect = getContext().Target.getCFStringDataSection();
1122 // FIXME: -fwritable-strings should probably affect this, but we
1123 // are following gcc here.
1124 isConstant = true;
1125 }
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001126 llvm::GlobalVariable *GV =
Daniel Dunbara9668e02009-04-03 00:57:44 +00001127 new llvm::GlobalVariable(C->getType(), isConstant,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001128 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara9668e02009-04-03 00:57:44 +00001129 C, Prefix, &getModule());
1130 if (Sect)
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001131 GV->setSection(Sect);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001132 if (isUTF16) {
1133 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1134 GV->setAlignment(Align);
1135 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001136 appendFieldAndPadding(*this, Fields, CurField, NextField,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001137 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
Anders Carlssone3daa762008-11-15 18:54:24 +00001138 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001139
1140 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001141 CurField = NextField;
1142 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001143 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001144 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffb59212a2009-04-01 21:16:31 +00001145 llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001146
1147 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001148 C = llvm::ConstantStruct::get(STy, Fields);
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001149 GV = new llvm::GlobalVariable(C->getType(), true,
1150 llvm::GlobalVariable::InternalLinkage, C,
1151 getContext().Target.getCFStringSymbolPrefix(),
1152 &getModule());
1153 if (const char *Sect = getContext().Target.getCFStringSection())
1154 GV->setSection(Sect);
Anders Carlsson0c678292007-11-01 00:41:52 +00001155 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001156
Anders Carlsson0c678292007-11-01 00:41:52 +00001157 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001158}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001159
Daniel Dunbar61432932008-08-13 23:20:05 +00001160/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001161/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001162std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001163 const char *StrData = E->getStrData();
1164 unsigned Len = E->getByteLength();
1165
1166 const ConstantArrayType *CAT =
1167 getContext().getAsConstantArrayType(E->getType());
1168 assert(CAT && "String isn't pointer or array!");
1169
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001170 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001171 std::string Str(StrData, StrData+Len);
1172 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001173
1174 if (E->isWide())
1175 RealLen *= getContext().Target.getWCharWidth()/8;
1176
Daniel Dunbar1e049762008-08-10 20:25:57 +00001177 Str.resize(RealLen, '\0');
1178
1179 return Str;
1180}
1181
Daniel Dunbar61432932008-08-13 23:20:05 +00001182/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1183/// constant array for the given string literal.
1184llvm::Constant *
1185CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1186 // FIXME: This can be more efficient.
1187 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1188}
1189
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001190/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1191/// array for the given ObjCEncodeExpr node.
1192llvm::Constant *
1193CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1194 std::string Str;
1195 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001196
1197 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001198}
1199
1200
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001201/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001202static llvm::Constant *GenerateStringLiteral(const std::string &str,
1203 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001204 CodeGenModule &CGM,
1205 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001206 // Create Constant for this string literal. Don't add a '\0'.
1207 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001208
1209 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001210 return new llvm::GlobalVariable(C->getType(), constant,
1211 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001212 C, GlobalName, &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001213}
1214
Daniel Dunbar61432932008-08-13 23:20:05 +00001215/// GetAddrOfConstantString - Returns a pointer to a character array
1216/// containing the literal. This contents are exactly that of the
1217/// given string, i.e. it will not be null terminated automatically;
1218/// see GetAddrOfConstantCString. Note that whether the result is
1219/// actually a pointer to an LLVM constant depends on
1220/// Feature.WriteableStrings.
1221///
1222/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001223llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1224 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001225 bool IsConstant = !Features.WritableStrings;
1226
1227 // Get the default prefix if a name wasn't specified.
1228 if (!GlobalName)
1229 GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1230
1231 // Don't share any string literals if strings aren't constant.
1232 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001233 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001234
1235 llvm::StringMapEntry<llvm::Constant *> &Entry =
1236 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1237
1238 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001239 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001240
1241 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001242 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001243 Entry.setValue(C);
1244 return C;
1245}
Daniel Dunbar61432932008-08-13 23:20:05 +00001246
1247/// GetAddrOfConstantCString - Returns a pointer to a character
1248/// array containing the literal and a terminating '\-'
1249/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001250llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1251 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001252 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001253}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001254
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001255/// EmitObjCPropertyImplementations - Emit information for synthesized
1256/// properties for an implementation.
1257void CodeGenModule::EmitObjCPropertyImplementations(const
1258 ObjCImplementationDecl *D) {
1259 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1260 e = D->propimpl_end(); i != e; ++i) {
1261 ObjCPropertyImplDecl *PID = *i;
1262
1263 // Dynamic is just for type-checking.
1264 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1265 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1266
1267 // Determine which methods need to be implemented, some may have
1268 // been overridden. Note that ::isSynthesized is not the method
1269 // we want, that just indicates if the decl came from a
1270 // property. What we want to know is if the method is defined in
1271 // this implementation.
1272 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001273 CodeGenFunction(*this).GenerateObjCGetter(
1274 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001275 if (!PD->isReadOnly() &&
1276 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001277 CodeGenFunction(*this).GenerateObjCSetter(
1278 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001279 }
1280 }
1281}
1282
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001283/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001284void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1285 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1286 I != E; ++I)
1287 EmitTopLevelDecl(*I);
1288}
1289
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001290// EmitLinkageSpec - Emit all declarations in a linkage spec.
1291void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1292 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1293 ErrorUnsupported(LSD, "linkage spec");
1294 return;
1295 }
1296
1297 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1298 I != E; ++I)
1299 EmitTopLevelDecl(*I);
1300}
1301
Daniel Dunbar41071de2008-08-15 23:26:23 +00001302/// EmitTopLevelDecl - Emit code for a single top level declaration.
1303void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1304 // If an error has occurred, stop code generation, but continue
1305 // parsing and semantic analysis (to ensure all warnings and errors
1306 // are emitted).
1307 if (Diags.hasErrorOccurred())
1308 return;
1309
1310 switch (D->getKind()) {
1311 case Decl::Function:
1312 case Decl::Var:
1313 EmitGlobal(cast<ValueDecl>(D));
1314 break;
1315
1316 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001317 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001318 break;
1319
1320 // Objective-C Decls
1321
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001322 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001323 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001324 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001325 case Decl::ObjCCategory:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001326 break;
Chris Lattner285d0db2009-04-01 02:36:43 +00001327 case Decl::ObjCInterface:
1328 // If we already laid out this interface due to an @class, and if we
1329 // codegen'd a reference it, update the 'opaque' type to be a real type now.
1330 Types.UpdateCompletedType(cast<ObjCInterfaceDecl>(D));
1331 break;
1332
Daniel Dunbar41071de2008-08-15 23:26:23 +00001333 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001334 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001335 break;
1336
1337 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001338 // Categories have properties but don't support synthesize so we
1339 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001340 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1341 break;
1342
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001343 case Decl::ObjCImplementation: {
1344 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1345 EmitObjCPropertyImplementations(OMD);
1346 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001347 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001348 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001349 case Decl::ObjCMethod: {
1350 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1351 // If this is not a prototype, emit the body.
1352 if (OMD->getBody())
1353 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1354 break;
1355 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001356 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001357 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001358 break;
1359
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001360 case Decl::LinkageSpec:
1361 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001362 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001363
1364 case Decl::FileScopeAsm: {
1365 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1366 std::string AsmString(AD->getAsmString()->getStrData(),
1367 AD->getAsmString()->getByteLength());
1368
1369 const std::string &S = getModule().getModuleInlineAsm();
1370 if (S.empty())
1371 getModule().setModuleInlineAsm(AsmString);
1372 else
1373 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1374 break;
1375 }
1376
1377 default:
1378 // Make sure we handled everything we should, every other kind is
1379 // a non-top-level decl. FIXME: Would be nice to have an
1380 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1381 // that easily.
1382 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1383 }
1384}