blob: 3de8156fe513e78c5c6fd49ef7645985789999a0 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerf04a7562009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattnerf04a7562009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000027#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000028#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000030#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerf04a7562009-03-26 05:00:52 +000035CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerf04a7562009-03-26 05:00:52 +000037 Diagnostic &diags)
38 : BlockModule(C, M, TD, Types, *this), Context(C),
39 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump1f010b52009-03-04 18:17:45 +000040 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
41 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000042
Chris Lattner08b05eb2009-03-21 07:12:05 +000043 if (!Features.ObjC1)
44 Runtime = 0;
45 else if (!Features.NeXTRuntime)
46 Runtime = CreateGNUObjCRuntime(*this);
47 else if (Features.ObjCNonFragileABI)
48 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
49 else
50 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000051
52 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerf04a7562009-03-26 05:00:52 +000053 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000054}
55
56CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000057 delete Runtime;
58 delete DebugInfo;
59}
60
61void CodeGenModule::Release() {
Chris Lattner13137542009-03-22 21:21:57 +000062 EmitDeferred();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000063 if (Runtime)
64 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
65 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000066 EmitCtorList(GlobalCtors, "llvm.global_ctors");
67 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000068 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000069 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000070}
71
Daniel Dunbar9503b782008-08-16 00:56:44 +000072/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000073/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000074void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
75 bool OmitOnError) {
76 if (OmitOnError && getDiags().hasErrorOccurred())
77 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000078 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000079 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +000080 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000081 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
82 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +000083}
Chris Lattner0e4755d2007-12-02 06:27:33 +000084
Daniel Dunbar9503b782008-08-16 00:56:44 +000085/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000086/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000087void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
88 bool OmitOnError) {
89 if (OmitOnError && getDiags().hasErrorOccurred())
90 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000091 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000092 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +000093 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000094 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +000095}
96
Daniel Dunbar27250d32008-08-15 23:26:23 +000097/// setGlobalVisibility - Set the visibility for the given LLVM
98/// GlobalValue according to the given clang AST visibility value.
99static void setGlobalVisibility(llvm::GlobalValue *GV,
100 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000101 switch (Vis) {
102 default: assert(0 && "Unknown visibility!");
103 case VisibilityAttr::DefaultVisibility:
104 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
105 break;
106 case VisibilityAttr::HiddenVisibility:
107 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
108 break;
109 case VisibilityAttr::ProtectedVisibility:
110 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
111 break;
112 }
113}
114
Douglas Gregor3556bc72009-02-13 00:10:09 +0000115/// \brief Retrieves the mangled name for the given declaration.
116///
117/// If the given declaration requires a mangled name, returns an
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000118/// const char* containing the mangled name. Otherwise, returns
119/// the unmangled name.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000120///
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000121const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000122 // In C, functions with no attributes never need to be mangled. Fastpath them.
123 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
124 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000125 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000126 }
127
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000128 llvm::SmallString<256> Name;
129 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000130 if (!mangleName(ND, Context, Out)) {
131 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000132 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000133 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000134
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000135 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000136 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000137}
138
Chris Lattner753d2592008-03-14 17:18:18 +0000139/// AddGlobalCtor - Add a function to the list that will be called before
140/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000141void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000142 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000143 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000144}
145
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000146/// AddGlobalDtor - Add a function to the list that will be called
147/// when the module is unloaded.
148void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000149 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000150 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
151}
152
153void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
154 // Ctor function type is void()*.
155 llvm::FunctionType* CtorFTy =
156 llvm::FunctionType::get(llvm::Type::VoidTy,
157 std::vector<const llvm::Type*>(),
158 false);
159 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
160
161 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000162 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000163 llvm::StructType::get(llvm::Type::Int32Ty,
164 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000165
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000166 // Construct the constructor and destructor arrays.
167 std::vector<llvm::Constant*> Ctors;
168 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
169 std::vector<llvm::Constant*> S;
170 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
171 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
172 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000173 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000174
175 if (!Ctors.empty()) {
176 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
177 new llvm::GlobalVariable(AT, false,
178 llvm::GlobalValue::AppendingLinkage,
179 llvm::ConstantArray::get(AT, Ctors),
180 GlobalName,
181 &TheModule);
182 }
Chris Lattner753d2592008-03-14 17:18:18 +0000183}
184
Nate Begeman52da5c72008-04-18 23:43:57 +0000185void CodeGenModule::EmitAnnotations() {
186 if (Annotations.empty())
187 return;
188
189 // Create a new global variable for the ConstantStruct in the Module.
190 llvm::Constant *Array =
191 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
192 Annotations.size()),
193 Annotations);
194 llvm::GlobalValue *gv =
195 new llvm::GlobalVariable(Array->getType(), false,
196 llvm::GlobalValue::AppendingLinkage, Array,
197 "llvm.global.annotations", &TheModule);
198 gv->setSection("llvm.metadata");
199}
200
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000201void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
202 bool IsInternal,
203 bool IsInline,
204 llvm::GlobalValue *GV,
205 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000206 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000207 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000208 if (!ForDefinition) {
209 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000210 if (D->getAttr<DLLImportAttr>()) {
211 // The dllimport attribute is overridden by a subsequent declaration as
212 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000213 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000214 // dllimport attribute can be applied only to function decls, not to
215 // definitions.
216 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
217 if (!FD->getBody())
218 GV->setLinkage(llvm::Function::DLLImportLinkage);
219 } else
220 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000221 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000222 } else if (D->getAttr<WeakAttr>() ||
223 D->getAttr<WeakImportAttr>()) {
224 // "extern_weak" is overloaded in LLVM; we probably should have
225 // separate linkage types for this.
Duncan Sands9aa5c262009-03-11 08:40:02 +0000226 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000227 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000228 } else {
229 if (IsInternal) {
230 GV->setLinkage(llvm::Function::InternalLinkage);
231 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000232 if (D->getAttr<DLLExportAttr>()) {
233 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
234 // The dllexport attribute is ignored for undefined symbols.
235 if (FD->getBody())
236 GV->setLinkage(llvm::Function::DLLExportLinkage);
237 } else
238 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000239 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
240 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000241 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000242 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000243 }
Nuno Lopes78534382008-06-08 15:45:52 +0000244
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000245 // FIXME: Figure out the relative priority of the attribute,
246 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000247 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000248 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000249 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000250
Daniel Dunbar97509722009-02-12 17:28:23 +0000251 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
252 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000253
254 // Only add to llvm.used when we see a definition, otherwise we
255 // might add multiple times or risk the value being replaced by a
256 // subsequent RAUW.
257 if (ForDefinition) {
258 if (D->getAttr<UsedAttr>())
259 AddUsedGlobal(GV);
260 }
Nuno Lopes78534382008-06-08 15:45:52 +0000261}
262
Devang Patela85a9ef2008-09-25 21:02:23 +0000263void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000264 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000265 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000266 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000267 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000268
Devang Patela85a9ef2008-09-25 21:02:23 +0000269 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
270 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000271
272 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000273 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000274 F->setCallingConv(llvm::CallingConv::X86_FastCall);
275
276 if (D->getAttr<StdCallAttr>())
277 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Fariborz Jahanian97703432009-03-27 18:38:55 +0000278
279 if (D->getAttr<RegparmAttr>())
280 ErrorUnsupported(D, "regparm attribute");
Daniel Dunbarf2787002008-09-04 23:41:35 +0000281}
282
283/// SetFunctionAttributesForDefinition - Set function attributes
284/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000285void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
286 llvm::Function *F) {
287 if (isa<ObjCMethodDecl>(D)) {
288 SetGlobalValueAttributes(D, true, false, F, true);
289 } else {
290 const FunctionDecl *FD = cast<FunctionDecl>(D);
291 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
292 FD->isInline(), F, true);
293 }
294
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000295 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000296 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000297
298 if (D->getAttr<AlwaysInlineAttr>())
299 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000300
301 if (D->getAttr<NoinlineAttr>())
302 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000303}
304
305void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
306 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000307 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000308
Daniel Dunbar566a6502008-09-08 23:44:31 +0000309 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000310}
311
312void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
313 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000314 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000315
Daniel Dunbar566a6502008-09-08 23:44:31 +0000316 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
317 FD->isInline(), F, false);
318}
319
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000320void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
321 assert(!GV->isDeclaration() &&
322 "Only globals with definition can force usage.");
323 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
324 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
325}
326
327void CodeGenModule::EmitLLVMUsed() {
328 // Don't create llvm.used if there is no need.
329 if (LLVMUsed.empty())
330 return;
331
332 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
333 LLVMUsed.size());
334 llvm::GlobalVariable *GV =
335 new llvm::GlobalVariable(ATy, false,
336 llvm::GlobalValue::AppendingLinkage,
337 llvm::ConstantArray::get(ATy, LLVMUsed),
338 "llvm.used", &getModule());
339
340 GV->setSection("llvm.metadata");
341}
342
343void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000344 // Emit code for any potentially referenced deferred decls. Since a
345 // previously unused static decl may become used during the generation of code
346 // for a static function, iterate until no changes are made.
347 while (!DeferredDeclsToEmit.empty()) {
348 const ValueDecl *D = DeferredDeclsToEmit.back();
349 DeferredDeclsToEmit.pop_back();
350
351 // The mangled name for the decl must have been emitted in GlobalDeclMap.
352 // Look it up to see if it was defined with a stronger definition (e.g. an
353 // extern inline function with a strong function redefinition). If so,
354 // just ignore the deferred decl.
355 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
356 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000357
Chris Lattner38837f92009-03-21 09:44:56 +0000358 if (!CGRef->isDeclaration())
359 continue;
360
361 // Otherwise, emit the definition and move on to the next one.
362 EmitGlobalDefinition(D);
363 }
Chris Lattner4b009652007-07-25 00:24:17 +0000364}
365
Nate Begeman8a704172008-04-19 04:17:09 +0000366/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
367/// annotation information for a given GlobalValue. The annotation struct is
368/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000369/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000370/// created from the AnnotateAttr's annotation. The third field is a constant
371/// string containing the name of the translation unit. The fourth field is
372/// the line number in the file of the annotated value declaration.
373///
374/// FIXME: this does not unique the annotation string constants, as llvm-gcc
375/// appears to.
376///
377llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
378 const AnnotateAttr *AA,
379 unsigned LineNo) {
380 llvm::Module *M = &getModule();
381
382 // get [N x i8] constants for the annotation string, and the filename string
383 // which are the 2nd and 3rd elements of the global annotation structure.
384 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
385 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
386 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
387 true);
388
389 // Get the two global values corresponding to the ConstantArrays we just
390 // created to hold the bytes of the strings.
391 llvm::GlobalValue *annoGV =
392 new llvm::GlobalVariable(anno->getType(), false,
393 llvm::GlobalValue::InternalLinkage, anno,
394 GV->getName() + ".str", M);
395 // translation unit name string, emitted into the llvm.metadata section.
396 llvm::GlobalValue *unitGV =
397 new llvm::GlobalVariable(unit->getType(), false,
398 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
399
400 // Create the ConstantStruct that is the global annotion.
401 llvm::Constant *Fields[4] = {
402 llvm::ConstantExpr::getBitCast(GV, SBP),
403 llvm::ConstantExpr::getBitCast(annoGV, SBP),
404 llvm::ConstantExpr::getBitCast(unitGV, SBP),
405 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
406 };
407 return llvm::ConstantStruct::get(Fields, 4, false);
408}
409
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000410bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000411 // Never defer when EmitAllDecls is specified or the decl has
412 // attribute used.
413 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000414 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000415
416 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000417 // Constructors and destructors should never be deferred.
418 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
419 return false;
420
Chris Lattner7e5888f2009-03-21 08:03:33 +0000421 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000422 if (FD->getStorageClass() != FunctionDecl::Static)
423 return false;
424 } else {
425 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000426 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000427
428 if (VD->getStorageClass() != VarDecl::Static)
429 return false;
430 }
431
432 return true;
433}
434
435void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000436 // If this is an alias definition (which otherwise looks like a declaration)
437 // emit it now.
438 if (Global->getAttr<AliasAttr>())
439 return EmitAliasDefinition(Global);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000440
Chris Lattner38837f92009-03-21 09:44:56 +0000441 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000442 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000443 // Forward declarations are emitted lazily on first use.
444 if (!FD->isThisDeclarationADefinition())
445 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000446 } else {
447 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000448 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
449
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000450 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000451 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000452 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000453 }
454
Chris Lattner38837f92009-03-21 09:44:56 +0000455 // Defer code generation when possible if this is a static definition, inline
456 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000457 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000458 // If the value has already been used, add it directly to the
459 // DeferredDeclsToEmit list.
460 const char *MangledName = getMangledName(Global);
461 if (GlobalDeclMap.count(MangledName))
462 DeferredDeclsToEmit.push_back(Global);
463 else {
464 // Otherwise, remember that we saw a deferred decl with this name. The
465 // first use of the mangled name will cause it to move into
466 // DeferredDeclsToEmit.
467 DeferredDecls[MangledName] = Global;
468 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000469 return;
470 }
471
472 // Otherwise emit the definition.
473 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000474}
475
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000476void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
478 EmitGlobalFunctionDefinition(FD);
479 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
480 EmitGlobalVarDefinition(VD);
481 } else {
482 assert(0 && "Invalid argument to EmitGlobalDefinition()");
483 }
484}
485
Chris Lattneraea1aee2009-03-22 21:03:39 +0000486/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
487/// module, create and return an llvm Function with the specified type. If there
488/// is something in the module with the specified name, return it potentially
489/// bitcasted to the right type.
490///
491/// If D is non-null, it specifies a decl that correspond to this. This is used
492/// to set the attributes on the function when it is first created.
493llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
494 const llvm::Type *Ty,
495 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000496 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000497 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
498 if (Entry) {
499 if (Entry->getType()->getElementType() == Ty)
500 return Entry;
501
502 // Make sure the result is of the correct type.
503 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
504 return llvm::ConstantExpr::getBitCast(Entry, PTy);
505 }
506
Chris Lattner38837f92009-03-21 09:44:56 +0000507 // This is the first use or definition of a mangled name. If there is a
508 // deferred decl with this name, remember that we need to emit it at the end
509 // of the file.
510 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000511 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000512 if (DDI != DeferredDecls.end()) {
513 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
514 // list, and remove it from DeferredDecls (since we don't need it anymore).
515 DeferredDeclsToEmit.push_back(DDI->second);
516 DeferredDecls.erase(DDI);
517 }
518
Chris Lattner5dd030f2009-03-21 09:25:43 +0000519 // This function doesn't have a complete type (for example, the return
520 // type is an incomplete struct). Use a fake type instead, and make
521 // sure not to try to set attributes.
522 bool ShouldSetAttributes = true;
523 if (!isa<llvm::FunctionType>(Ty)) {
524 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
525 std::vector<const llvm::Type*>(), false);
526 ShouldSetAttributes = false;
527 }
528 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
529 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000530 "", &getModule());
531 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000532 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000533 SetFunctionAttributes(D, F);
534 Entry = F;
535 return F;
536}
537
Chris Lattneraea1aee2009-03-22 21:03:39 +0000538/// GetAddrOfFunction - Return the address of the given function. If Ty is
539/// non-null, then this function will use the specified type if it has to
540/// create it (this occurs when we see a definition of the function).
541llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
542 const llvm::Type *Ty) {
543 // If there was no specific requested type, just convert it now.
544 if (!Ty)
545 Ty = getTypes().ConvertType(D->getType());
546 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
547}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000548
Chris Lattneraea1aee2009-03-22 21:03:39 +0000549/// CreateRuntimeFunction - Create a new runtime function with the specified
550/// type and name.
551llvm::Constant *
552CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
553 const char *Name) {
554 // Convert Name to be a uniqued string from the IdentifierInfo table.
555 Name = getContext().Idents.get(Name).getName();
556 return GetOrCreateLLVMFunction(Name, FTy, 0);
557}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000558
Chris Lattneraea1aee2009-03-22 21:03:39 +0000559/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
560/// create and return an llvm GlobalVariable with the specified type. If there
561/// is something in the module with the specified name, return it potentially
562/// bitcasted to the right type.
563///
564/// If D is non-null, it specifies a decl that correspond to this. This is used
565/// to set the attributes on the global when it is first created.
566llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
567 const llvm::PointerType*Ty,
568 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000569 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000570 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000571 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000572 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000573 return Entry;
574
Chris Lattner7e5888f2009-03-21 08:03:33 +0000575 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000576 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000577 }
Chris Lattner38837f92009-03-21 09:44:56 +0000578
579 // This is the first use or definition of a mangled name. If there is a
580 // deferred decl with this name, remember that we need to emit it at the end
581 // of the file.
582 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
583 DeferredDecls.find(MangledName);
584 if (DDI != DeferredDecls.end()) {
585 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
586 // list, and remove it from DeferredDecls (since we don't need it anymore).
587 DeferredDeclsToEmit.push_back(DDI->second);
588 DeferredDecls.erase(DDI);
589 }
590
Chris Lattner7e5888f2009-03-21 08:03:33 +0000591 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000592 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000593 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000594 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000595 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000596 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000597
598 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000599 if (D) {
600 // FIXME: This code is overly simple and should be merged with
601 // other global handling.
602 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000603
Chris Lattneraea1aee2009-03-22 21:03:39 +0000604 // FIXME: Merge with other attribute handling code.
605 if (D->getStorageClass() == VarDecl::PrivateExtern)
606 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000607
Chris Lattneraea1aee2009-03-22 21:03:39 +0000608 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
609 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
610 }
611
Chris Lattner7e5888f2009-03-21 08:03:33 +0000612 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000613}
614
Chris Lattneraea1aee2009-03-22 21:03:39 +0000615
616/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
617/// given global variable. If Ty is non-null and if the global doesn't exist,
618/// then it will be greated with the specified type instead of whatever the
619/// normal requested type would be.
620llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
621 const llvm::Type *Ty) {
622 assert(D->hasGlobalStorage() && "Not a global variable");
623 QualType ASTTy = D->getType();
624 if (Ty == 0)
625 Ty = getTypes().ConvertTypeForMem(ASTTy);
626
627 const llvm::PointerType *PTy =
628 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
629 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
630}
631
632/// CreateRuntimeVariable - Create a new runtime global variable with the
633/// specified type and name.
634llvm::Constant *
635CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
636 const char *Name) {
637 // Convert Name to be a uniqued string from the IdentifierInfo table.
638 Name = getContext().Idents.get(Name).getName();
639 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
640}
641
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000642void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000643 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000644 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000645
Chris Lattner4b009652007-07-25 00:24:17 +0000646 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000647 // This is a tentative definition; tentative definitions are
648 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000649 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000650 if (ASTTy->isIncompleteArrayType()) {
651 // An incomplete array is normally [ TYPE x 0 ], but we need
652 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000653 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000654 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000655 }
656 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000657 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000658 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000659 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000660 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000661 QualType T = D->getInit()->getType();
662 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
663 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000664 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000665
Chris Lattner23afd5b2009-03-21 08:13:05 +0000666 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000667 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000668
Chris Lattnera6984932009-03-21 09:16:30 +0000669 // Strip off a bitcast if we got one back.
670 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
671 assert(CE->getOpcode() == llvm::Instruction::BitCast);
672 Entry = CE->getOperand(0);
673 }
674
675 // Entry is now either a Function or GlobalVariable.
676 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
677
678 // If we already have this global and it has an initializer, then
679 // we are in the rare situation where we emitted the defining
680 // declaration of the global and are now being asked to emit a
681 // definition which would be common. This occurs, for example, in
682 // the following situation because statics can be emitted out of
683 // order:
684 //
685 // static int x;
686 // static int *y = &x;
687 // static int x = 10;
688 // int **z = &y;
689 //
690 // Bail here so we don't blow away the definition. Note that if we
691 // can't distinguish here if we emitted a definition with a null
692 // initializer, but this case is safe.
693 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000694 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
695 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000696 }
697
698 // We have a definition after a declaration with the wrong type.
699 // We must make a new GlobalVariable* and update everything that used OldGV
700 // (a declaration or tentative definition) with the new GlobalVariable*
701 // (which will be a definition).
702 //
703 // This happens if there is a prototype for a global (e.g.
704 // "extern int x[];") and then a definition of a different type (e.g.
705 // "int x[10];"). This also happens when an initializer has a different type
706 // from the type of the global (this happens with unions).
707 //
708 // FIXME: This also ends up happening if there's a definition followed by
709 // a tentative definition! (Although Sema rejects that construct
710 // at the moment.)
711 if (GV == 0 ||
712 GV->getType()->getElementType() != InitType ||
713 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
714
715 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
716 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000717
Chris Lattnera6984932009-03-21 09:16:30 +0000718 // Make a new global with the correct type, this is now guaranteed to work.
719 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000720 GV->takeName(cast<llvm::GlobalValue>(Entry));
721
Eli Friedman43a0ce82008-05-30 19:50:47 +0000722 // Replace all uses of the old global with the new global
723 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000724 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
725 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000726
727 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000728 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattnera6984932009-03-21 09:16:30 +0000729 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000730 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000731
Nate Begeman8a704172008-04-19 04:17:09 +0000732 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
733 SourceManager &SM = Context.getSourceManager();
734 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000735 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000736 }
737
Chris Lattner4b009652007-07-25 00:24:17 +0000738 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000739 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000740 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000741
Chris Lattner402b3372008-03-03 03:28:21 +0000742 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000743 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000744 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000747 if (D->getStorageClass() == VarDecl::Static)
748 GV->setLinkage(llvm::Function::InternalLinkage);
749 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000750 GV->setLinkage(llvm::Function::DLLImportLinkage);
751 else if (D->getAttr<DLLExportAttr>())
752 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000753 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000754 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000755 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000756 // FIXME: This isn't right. This should handle common linkage and other
757 // stuff.
758 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000759 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000760 case VarDecl::Auto:
761 case VarDecl::Register:
762 assert(0 && "Can't have auto or register globals");
763 case VarDecl::None:
Chris Lattnerf04a7562009-03-26 05:00:52 +0000764 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sands78c33cc2009-03-11 20:15:27 +0000765 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000766 else
767 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000768 break;
769 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000770 // FIXME: common
771 break;
772
Chris Lattner402b3372008-03-03 03:28:21 +0000773 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000774 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
775 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000776 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000777 }
Chris Lattner4b009652007-07-25 00:24:17 +0000778 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000779
Daniel Dunbar97509722009-02-12 17:28:23 +0000780 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
781 GV->setSection(SA->getName());
782
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000783 if (D->getAttr<UsedAttr>())
784 AddUsedGlobal(GV);
785
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000786 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000787 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000788 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000789 DI->EmitGlobalVariable(GV, D);
790 }
Chris Lattner4b009652007-07-25 00:24:17 +0000791}
792
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000793
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000794void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000795 const llvm::FunctionType *Ty =
796 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
797
798 // As a special case, make sure that definitions of K&R function
799 // "type foo()" aren't declared as varargs (which forces the backend
800 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000801 if (D->getType()->isFunctionNoProtoType()) {
802 assert(Ty->isVarArg() && "Didn't lower type as expected");
803 // Due to stret, the lowered function could have arguments. Just create the
804 // same type as was lowered by ConvertType but strip off the varargs bit.
805 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
806 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
807 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000808
Chris Lattnerd26784e2009-03-21 08:53:37 +0000809 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000810 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000811
Chris Lattner5dd030f2009-03-21 09:25:43 +0000812 // Strip off a bitcast if we got one back.
813 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
814 assert(CE->getOpcode() == llvm::Instruction::BitCast);
815 Entry = CE->getOperand(0);
816 }
817
818
819 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000820 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000821 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
822 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000823
Chris Lattnere28718c2009-03-21 08:38:50 +0000824 // F is the Function* for the one with the wrong type, we must make a new
825 // Function* and update everything that used F (a declaration) with the new
826 // Function* (which will be a definition).
827 //
828 // This happens if there is a prototype for a function
829 // (e.g. "int f()") and then a definition of a different type
830 // (e.g. "int f(int x)"). Start by making a new function of the
831 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000832 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000833 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
834 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000835
836 // Replace uses of F with the Function we will endow with a body.
837 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000838 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
839 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000840
841 // Ok, delete the old function now, which is dead.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000842 // FIXME: If it was attribute(used) the pointer will dangle from the
843 // LLVMUsed array!
Chris Lattner5dd030f2009-03-21 09:25:43 +0000844 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000845
Chris Lattner5dd030f2009-03-21 09:25:43 +0000846 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000847 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000848
849 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000850
Daniel Dunbar566a6502008-09-08 23:44:31 +0000851 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000852
Daniel Dunbar566a6502008-09-08 23:44:31 +0000853 SetFunctionAttributesForDefinition(D, Fn);
854
Chris Lattnerd26784e2009-03-21 08:53:37 +0000855 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000856 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000857 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000858 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000859}
860
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000861void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
862 const AliasAttr *AA = D->getAttr<AliasAttr>();
863 assert(AA && "Not an alias?");
864
865 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
866
867 // Unique the name through the identifier table.
868 const char *AliaseeName = AA->getAliasee().c_str();
869 AliaseeName = getContext().Idents.get(AliaseeName).getName();
870
871 // Create a reference to the named value. This ensures that it is emitted
872 // if a deferred decl.
873 llvm::Constant *Aliasee;
874 if (isa<llvm::FunctionType>(DeclTy))
875 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
876 else
877 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
878 llvm::PointerType::getUnqual(DeclTy), 0);
879
880 // Create the new alias itself, but don't set a name yet.
881 llvm::GlobalValue *GA =
882 new llvm::GlobalAlias(Aliasee->getType(),
883 llvm::Function::ExternalLinkage,
884 "", Aliasee, &getModule());
885
886 // See if there is already something with the alias' name in the module.
887 const char *MangledName = getMangledName(D);
888 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
889
890 if (Entry && !Entry->isDeclaration()) {
891 // If there is a definition in the module, then it wins over the alias.
892 // This is dubious, but allow it to be safe. Just ignore the alias.
893 GA->eraseFromParent();
894 return;
895 }
896
897 if (Entry) {
898 // If there is a declaration in the module, then we had an extern followed
899 // by the alias, as in:
900 // extern int test6();
901 // ...
902 // int test6() __attribute__((alias("test7")));
903 //
904 // Remove it and replace uses of it with the alias.
905
906 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
907 Entry->getType()));
908 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
909 Entry->eraseFromParent();
910 }
911
912 // Now we know that there is no conflict, set the name.
913 Entry = GA;
914 GA->setName(MangledName);
915
916 // Alias should never be internal or inline.
917 SetGlobalValueAttributes(D, false, false, GA, true);
918}
919
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000920void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
921 // Make sure that this type is translated.
922 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000923}
924
925
Chris Lattnere6247a22009-03-22 21:56:56 +0000926/// getBuiltinLibFunction - Given a builtin id for a function like
927/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stump96b7a152009-02-27 22:42:30 +0000928llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor411889e2009-02-13 23:20:09 +0000929 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
930 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
931 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000932
Douglas Gregor411889e2009-02-13 23:20:09 +0000933 // Get the name, skip over the __builtin_ prefix (if necessary).
934 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
935 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
936 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000937
938 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000939 Builtin::Context::GetBuiltinTypeError Error;
940 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
941 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
942
Chris Lattnerab862cc2007-08-31 04:31:45 +0000943 const llvm::FunctionType *Ty =
944 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
945
Chris Lattnere6247a22009-03-22 21:56:56 +0000946 // Unique the name through the identifier table.
947 Name = getContext().Idents.get(Name).getName();
Chris Lattnerab862cc2007-08-31 04:31:45 +0000948 // FIXME: param attributes for sext/zext etc.
Chris Lattnere6247a22009-03-22 21:56:56 +0000949 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000950}
951
Chris Lattner4b23f942007-12-18 00:25:38 +0000952llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
953 unsigned NumTys) {
954 return llvm::Intrinsic::getDeclaration(&getModule(),
955 (llvm::Intrinsic::ID)IID, Tys, NumTys);
956}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000957
Chris Lattner4b009652007-07-25 00:24:17 +0000958llvm::Function *CodeGenModule::getMemCpyFn() {
959 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000960 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
961 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000962}
Anders Carlsson36a04872007-08-21 00:21:21 +0000963
Eli Friedman8f08a252008-05-26 12:59:39 +0000964llvm::Function *CodeGenModule::getMemMoveFn() {
965 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000966 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
967 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000968}
969
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000970llvm::Function *CodeGenModule::getMemSetFn() {
971 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000972 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
973 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000974}
Chris Lattner4b23f942007-12-18 00:25:38 +0000975
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000976static void appendFieldAndPadding(CodeGenModule &CGM,
977 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000978 FieldDecl *FieldD, FieldDecl *NextFieldD,
979 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +0000980 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000981 // Append the field.
982 Fields.push_back(Field);
983
Douglas Gregor8acb7272008-12-11 16:49:14 +0000984 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000985
986 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000987 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000988 NextStructFieldNo = STy->getNumElements();
989 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000990 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000991 }
992
993 // Append padding
994 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
995 llvm::Constant *C =
996 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
997
998 Fields.push_back(C);
999 }
1000}
1001
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001002// We still need to work out the details of handling UTF-16.
1003// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001004llvm::Constant *CodeGenModule::
1005GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001006 llvm::StringMapEntry<llvm::Constant *> &Entry =
1007 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1008
1009 if (Entry.getValue())
1010 return Entry.getValue();
1011
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001012 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1013 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001014
1015 if (!CFConstantStringClassRef) {
1016 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1017 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001018
1019 // FIXME: This is fairly broken if
1020 // __CFConstantStringClassReference is already defined, in that it
1021 // will get renamed and the user will most likely see an opaque
1022 // error message. This is a general issue with relying on
1023 // particular names.
1024 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001025 new llvm::GlobalVariable(Ty, false,
1026 llvm::GlobalVariable::ExternalLinkage, 0,
1027 "__CFConstantStringClassReference",
1028 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001029
1030 // Decay array -> ptr
1031 CFConstantStringClassRef =
1032 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001033 }
1034
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001035 QualType CFTy = getContext().getCFConstantStringType();
1036 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001037
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001038 const llvm::StructType *STy =
1039 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1040
1041 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001042 RecordDecl::field_iterator Field = CFRD->field_begin();
1043
Anders Carlsson36a04872007-08-21 00:21:21 +00001044 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001045 FieldDecl *CurField = *Field++;
1046 FieldDecl *NextField = *Field++;
1047 appendFieldAndPadding(*this, Fields, CurField, NextField,
1048 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001049
1050 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001051 CurField = NextField;
1052 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001053 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001054 appendFieldAndPadding(*this, Fields, CurField, NextField,
1055 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001056
1057 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001058 CurField = NextField;
1059 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001060 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001061 C = new llvm::GlobalVariable(C->getType(), true,
1062 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001063 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001064 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001065 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1066 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001067
1068 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001069 CurField = NextField;
1070 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001071 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001072 appendFieldAndPadding(*this, Fields, CurField, NextField,
1073 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001074
1075 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001076 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001077 llvm::GlobalVariable *GV =
1078 new llvm::GlobalVariable(C->getType(), true,
1079 llvm::GlobalVariable::InternalLinkage,
1080 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001081
Anders Carlsson9be009e2007-11-01 00:41:52 +00001082 GV->setSection("__DATA,__cfstring");
1083 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001084
Anders Carlsson9be009e2007-11-01 00:41:52 +00001085 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001086}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001087
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001088/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001089/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001090std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001091 const char *StrData = E->getStrData();
1092 unsigned Len = E->getByteLength();
1093
1094 const ConstantArrayType *CAT =
1095 getContext().getAsConstantArrayType(E->getType());
1096 assert(CAT && "String isn't pointer or array!");
1097
Chris Lattner14032222009-02-26 23:01:51 +00001098 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001099 std::string Str(StrData, StrData+Len);
1100 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001101
1102 if (E->isWide())
1103 RealLen *= getContext().Target.getWCharWidth()/8;
1104
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001105 Str.resize(RealLen, '\0');
1106
1107 return Str;
1108}
1109
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001110/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1111/// constant array for the given string literal.
1112llvm::Constant *
1113CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1114 // FIXME: This can be more efficient.
1115 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1116}
1117
Chris Lattnerc5d32632009-02-24 22:18:39 +00001118/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1119/// array for the given ObjCEncodeExpr node.
1120llvm::Constant *
1121CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1122 std::string Str;
1123 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001124
1125 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001126}
1127
1128
Chris Lattnera6dcce32008-02-11 00:02:17 +00001129/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001130static llvm::Constant *GenerateStringLiteral(const std::string &str,
1131 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001132 CodeGenModule &CGM,
1133 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001134 // Create Constant for this string literal. Don't add a '\0'.
1135 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001136
1137 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001138 return new llvm::GlobalVariable(C->getType(), constant,
1139 llvm::GlobalValue::InternalLinkage,
1140 C, GlobalName ? GlobalName : ".str",
1141 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001142}
1143
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001144/// GetAddrOfConstantString - Returns a pointer to a character array
1145/// containing the literal. This contents are exactly that of the
1146/// given string, i.e. it will not be null terminated automatically;
1147/// see GetAddrOfConstantCString. Note that whether the result is
1148/// actually a pointer to an LLVM constant depends on
1149/// Feature.WriteableStrings.
1150///
1151/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001152llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1153 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001154 // Don't share any string literals if writable-strings is turned on.
1155 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001156 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001157
1158 llvm::StringMapEntry<llvm::Constant *> &Entry =
1159 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1160
1161 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001162 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001163
1164 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001165 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001166 Entry.setValue(C);
1167 return C;
1168}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001169
1170/// GetAddrOfConstantCString - Returns a pointer to a character
1171/// array containing the literal and a terminating '\-'
1172/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001173llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1174 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001175 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001176}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001177
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001178/// EmitObjCPropertyImplementations - Emit information for synthesized
1179/// properties for an implementation.
1180void CodeGenModule::EmitObjCPropertyImplementations(const
1181 ObjCImplementationDecl *D) {
1182 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1183 e = D->propimpl_end(); i != e; ++i) {
1184 ObjCPropertyImplDecl *PID = *i;
1185
1186 // Dynamic is just for type-checking.
1187 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1188 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1189
1190 // Determine which methods need to be implemented, some may have
1191 // been overridden. Note that ::isSynthesized is not the method
1192 // we want, that just indicates if the decl came from a
1193 // property. What we want to know is if the method is defined in
1194 // this implementation.
1195 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001196 CodeGenFunction(*this).GenerateObjCGetter(
1197 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001198 if (!PD->isReadOnly() &&
1199 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001200 CodeGenFunction(*this).GenerateObjCSetter(
1201 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001202 }
1203 }
1204}
1205
Daniel Dunbar27250d32008-08-15 23:26:23 +00001206/// EmitTopLevelDecl - Emit code for a single top level declaration.
1207void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1208 // If an error has occurred, stop code generation, but continue
1209 // parsing and semantic analysis (to ensure all warnings and errors
1210 // are emitted).
1211 if (Diags.hasErrorOccurred())
1212 return;
1213
1214 switch (D->getKind()) {
1215 case Decl::Function:
1216 case Decl::Var:
1217 EmitGlobal(cast<ValueDecl>(D));
1218 break;
1219
1220 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001221 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001222 break;
1223
1224 // Objective-C Decls
1225
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001226 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001227 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001228 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001229 case Decl::ObjCCategory:
1230 case Decl::ObjCInterface:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001231 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001232
Daniel Dunbar27250d32008-08-15 23:26:23 +00001233 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001234 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001235 break;
1236
1237 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001238 // Categories have properties but don't support synthesize so we
1239 // can ignore them here.
1240
Daniel Dunbar27250d32008-08-15 23:26:23 +00001241 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1242 break;
1243
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001244 case Decl::ObjCImplementation: {
1245 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1246 EmitObjCPropertyImplementations(OMD);
1247 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001248 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001249 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001250 case Decl::ObjCMethod: {
1251 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1252 // If this is not a prototype, emit the body.
1253 if (OMD->getBody())
1254 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1255 break;
1256 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001257 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001258 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001259 break;
1260
1261 case Decl::LinkageSpec: {
1262 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1263 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001264 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001265 // FIXME: implement C++ linkage, C linkage works mostly by C
1266 // language reuse already.
1267 break;
1268 }
1269
1270 case Decl::FileScopeAsm: {
1271 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1272 std::string AsmString(AD->getAsmString()->getStrData(),
1273 AD->getAsmString()->getByteLength());
1274
1275 const std::string &S = getModule().getModuleInlineAsm();
1276 if (S.empty())
1277 getModule().setModuleInlineAsm(AsmString);
1278 else
1279 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1280 break;
1281 }
1282
1283 default:
1284 // Make sure we handled everything we should, every other kind is
1285 // a non-top-level decl. FIXME: Would be nice to have an
1286 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1287 // that easily.
1288 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1289 }
1290}