blob: a0024aa9bb5f4cdbb14672418d4d9dc0486203a3 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Mike Stumpd6d0ebe2009-03-04 18:47:42 +000037 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
Mike Stump1f010b52009-03-04 18:17:45 +000038 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000040
41 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000042 if (Features.NeXTRuntime) {
Fariborz Jahaniand0374812009-01-22 23:02:58 +000043 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanian48543f52009-01-21 22:04:16 +000044 : CreateMacObjCRuntime(*this);
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000045 } else {
46 Runtime = CreateGNUObjCRuntime(*this);
47 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000048 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stumpef2c82f2009-02-13 18:36:05 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000060 EmitDeferred();
Daniel Dunbar566a6502008-09-08 23:44:31 +000061 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000062 if (Runtime)
63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000065 EmitCtorList(GlobalCtors, "llvm.global_ctors");
66 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000067 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000068 EmitLLVMUsed();
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000069 BindRuntimeGlobals();
Chris Lattnercbfb5512008-03-01 08:45:05 +000070}
Chris Lattner4b009652007-07-25 00:24:17 +000071
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000072void CodeGenModule::BindRuntimeGlobals() {
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000073 // Deal with protecting runtime function names.
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000074 for (unsigned i = 0, e = RuntimeGlobals.size(); i < e; ++i) {
75 llvm::GlobalValue *GV = RuntimeGlobals[i].first;
76 const std::string &Name = RuntimeGlobals[i].second;
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000077
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000078 // Discard unused runtime declarations.
79 if (GV->isDeclaration() && GV->use_empty()) {
80 GV->eraseFromParent();
Daniel Dunbarfc1543e2008-11-19 06:15:35 +000081 continue;
82 }
83
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000084 // See if there is a conflict against a function.
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000085 llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name);
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000086 if (Conflict) {
87 // Decide which version to take. If the conflict is a definition
88 // we are forced to take that, otherwise assume the runtime
89 // knows best.
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000090
91 // FIXME: This will fail phenomenally when the conflict is the
92 // wrong type of value. Just bail on it for now. This should
93 // really reuse something inside the LLVM Linker code.
94 assert(GV->getValueID() == Conflict->getValueID() &&
95 "Unable to resolve conflict between globals of different types.");
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000096 if (!Conflict->isDeclaration()) {
97 llvm::Value *Casted =
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +000098 llvm::ConstantExpr::getBitCast(Conflict, GV->getType());
99 GV->replaceAllUsesWith(Casted);
100 GV->eraseFromParent();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000101 } else {
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000102 GV->takeName(Conflict);
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000103 llvm::Value *Casted =
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000104 llvm::ConstantExpr::getBitCast(GV, Conflict->getType());
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000105 Conflict->replaceAllUsesWith(Casted);
106 Conflict->eraseFromParent();
107 }
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000108 } else
109 GV->setName(Name);
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000110 }
111}
112
Daniel Dunbar9503b782008-08-16 00:56:44 +0000113/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000114/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000115void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116 bool OmitOnError) {
117 if (OmitOnError && getDiags().hasErrorOccurred())
118 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000119 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000120 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000121 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000122 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000124}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000125
Daniel Dunbar9503b782008-08-16 00:56:44 +0000126/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000127/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000128void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129 bool OmitOnError) {
130 if (OmitOnError && getDiags().hasErrorOccurred())
131 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000132 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000133 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +0000134 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000135 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000136}
137
Daniel Dunbar27250d32008-08-15 23:26:23 +0000138/// setGlobalVisibility - Set the visibility for the given LLVM
139/// GlobalValue according to the given clang AST visibility value.
140static void setGlobalVisibility(llvm::GlobalValue *GV,
141 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000142 switch (Vis) {
143 default: assert(0 && "Unknown visibility!");
144 case VisibilityAttr::DefaultVisibility:
145 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146 break;
147 case VisibilityAttr::HiddenVisibility:
148 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149 break;
150 case VisibilityAttr::ProtectedVisibility:
151 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152 break;
153 }
154}
155
Douglas Gregor3556bc72009-02-13 00:10:09 +0000156/// \brief Retrieves the mangled name for the given declaration.
157///
158/// If the given declaration requires a mangled name, returns an
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000159/// const char* containing the mangled name. Otherwise, returns
160/// the unmangled name.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000161///
162/// FIXME: Returning an IdentifierInfo* here is a total hack. We
163/// really need some kind of string abstraction that either stores a
164/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbar7b7f4f42009-02-18 22:52:09 +0000165/// changes to the GlobalDeclMap, too. (I disagree, I think what we
166/// actually need is for Sema to provide some notion of which Decls
167/// refer to the same semantic decl. We shouldn't need to mangle the
168/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor3556bc72009-02-13 00:10:09 +0000169///
170/// FIXME: Performance here is going to be terribly until we start
171/// caching mangled names. However, we should fix the problem above
172/// first.
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000173const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000174 // In C, functions with no attributes never need to be mangled. Fastpath them.
175 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
176 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
177 return ND->getIdentifier()->getName();
178 }
179
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000180 llvm::SmallString<256> Name;
181 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000182 if (!mangleName(ND, Context, Out)) {
183 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000184 return ND->getIdentifier()->getName();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000185 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000186
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000187 Name += '\0';
188 return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
189 .getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000190}
191
Chris Lattner753d2592008-03-14 17:18:18 +0000192/// AddGlobalCtor - Add a function to the list that will be called before
193/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000194void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000195 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000196 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000197}
198
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000199/// AddGlobalDtor - Add a function to the list that will be called
200/// when the module is unloaded.
201void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000202 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000203 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
204}
205
206void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
207 // Ctor function type is void()*.
208 llvm::FunctionType* CtorFTy =
209 llvm::FunctionType::get(llvm::Type::VoidTy,
210 std::vector<const llvm::Type*>(),
211 false);
212 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
213
214 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000215 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000216 llvm::StructType::get(llvm::Type::Int32Ty,
217 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000218
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000219 // Construct the constructor and destructor arrays.
220 std::vector<llvm::Constant*> Ctors;
221 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
222 std::vector<llvm::Constant*> S;
223 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
224 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
225 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000226 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000227
228 if (!Ctors.empty()) {
229 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
230 new llvm::GlobalVariable(AT, false,
231 llvm::GlobalValue::AppendingLinkage,
232 llvm::ConstantArray::get(AT, Ctors),
233 GlobalName,
234 &TheModule);
235 }
Chris Lattner753d2592008-03-14 17:18:18 +0000236}
237
Nate Begeman52da5c72008-04-18 23:43:57 +0000238void CodeGenModule::EmitAnnotations() {
239 if (Annotations.empty())
240 return;
241
242 // Create a new global variable for the ConstantStruct in the Module.
243 llvm::Constant *Array =
244 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
245 Annotations.size()),
246 Annotations);
247 llvm::GlobalValue *gv =
248 new llvm::GlobalVariable(Array->getType(), false,
249 llvm::GlobalValue::AppendingLinkage, Array,
250 "llvm.global.annotations", &TheModule);
251 gv->setSection("llvm.metadata");
252}
253
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000254void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
255 bool IsInternal,
256 bool IsInline,
257 llvm::GlobalValue *GV,
258 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000259 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000260 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000261 if (!ForDefinition) {
262 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000263 if (D->getAttr<DLLImportAttr>()) {
264 // The dllimport attribute is overridden by a subsequent declaration as
265 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000266 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000267 // dllimport attribute can be applied only to function decls, not to
268 // definitions.
269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270 if (!FD->getBody())
271 GV->setLinkage(llvm::Function::DLLImportLinkage);
272 } else
273 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000274 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000275 } else if (D->getAttr<WeakAttr>() ||
276 D->getAttr<WeakImportAttr>()) {
277 // "extern_weak" is overloaded in LLVM; we probably should have
278 // separate linkage types for this.
Duncan Sands9aa5c262009-03-11 08:40:02 +0000279 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000280 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000281 } else {
282 if (IsInternal) {
283 GV->setLinkage(llvm::Function::InternalLinkage);
284 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000285 if (D->getAttr<DLLExportAttr>()) {
286 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
287 // The dllexport attribute is ignored for undefined symbols.
288 if (FD->getBody())
289 GV->setLinkage(llvm::Function::DLLExportLinkage);
290 } else
291 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000292 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
293 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000294 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000295 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000296 }
Nuno Lopes78534382008-06-08 15:45:52 +0000297
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000298 // FIXME: Figure out the relative priority of the attribute,
299 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000300 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000301 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000302 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000303
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000304 // Prefaced with special LLVM marker to indicate that the name
305 // should not be munged.
306 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
Daniel Dunbarced89142008-08-06 00:03:29 +0000307 GV->setName("\01" + ALA->getLabel());
Daniel Dunbar97509722009-02-12 17:28:23 +0000308
309 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
310 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000311
312 // Only add to llvm.used when we see a definition, otherwise we
313 // might add multiple times or risk the value being replaced by a
314 // subsequent RAUW.
315 if (ForDefinition) {
316 if (D->getAttr<UsedAttr>())
317 AddUsedGlobal(GV);
318 }
Nuno Lopes78534382008-06-08 15:45:52 +0000319}
320
Devang Patela85a9ef2008-09-25 21:02:23 +0000321void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000322 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000323 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000324 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000325 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000326
Devang Patela85a9ef2008-09-25 21:02:23 +0000327 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
328 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000329
330 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000331 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000332 F->setCallingConv(llvm::CallingConv::X86_FastCall);
333
334 if (D->getAttr<StdCallAttr>())
335 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000336}
337
338/// SetFunctionAttributesForDefinition - Set function attributes
339/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000340void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
341 llvm::Function *F) {
342 if (isa<ObjCMethodDecl>(D)) {
343 SetGlobalValueAttributes(D, true, false, F, true);
344 } else {
345 const FunctionDecl *FD = cast<FunctionDecl>(D);
346 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
347 FD->isInline(), F, true);
348 }
349
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000350 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000351 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000352
353 if (D->getAttr<AlwaysInlineAttr>())
354 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000355
356 if (D->getAttr<NoinlineAttr>())
357 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000358}
359
360void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
361 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000362 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000363
Daniel Dunbar566a6502008-09-08 23:44:31 +0000364 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000365}
366
367void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
368 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000369 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000370
Daniel Dunbar566a6502008-09-08 23:44:31 +0000371 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
372 FD->isInline(), F, false);
373}
374
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000375
Daniel Dunbar566a6502008-09-08 23:44:31 +0000376void CodeGenModule::EmitAliases() {
377 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000378 const ValueDecl *D = Aliases[i];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000379 const AliasAttr *AA = D->getAttr<AliasAttr>();
380
381 // This is something of a hack, if the FunctionDecl got overridden
382 // then its attributes will be moved to the new declaration. In
383 // this case the current decl has no alias attribute, but we will
384 // eventually see it.
385 if (!AA)
386 continue;
387
388 const std::string& aliaseeName = AA->getAliasee();
Daniel Dunbar36acae42009-03-19 08:27:24 +0000389 llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000390 if (!aliasee) {
391 // FIXME: This isn't unsupported, this is just an error, which
392 // sema should catch, but...
393 ErrorUnsupported(D, "alias referencing a missing function");
394 continue;
395 }
396
397 llvm::GlobalValue *GA =
398 new llvm::GlobalAlias(aliasee->getType(),
399 llvm::Function::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000400 getMangledName(D), aliasee,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000401 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000402
Douglas Gregor3556bc72009-02-13 00:10:09 +0000403 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000404 if (Entry) {
405 // If we created a dummy function for this then replace it.
406 GA->takeName(Entry);
407
408 llvm::Value *Casted =
409 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
410 Entry->replaceAllUsesWith(Casted);
411 Entry->eraseFromParent();
412
413 Entry = GA;
414 }
415
416 // Alias should never be internal or inline.
417 SetGlobalValueAttributes(D, false, false, GA, true);
418 }
Eli Friedman9be42212008-06-01 15:54:49 +0000419}
420
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000421void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
422 assert(!GV->isDeclaration() &&
423 "Only globals with definition can force usage.");
424 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
425 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
426}
427
428void CodeGenModule::EmitLLVMUsed() {
429 // Don't create llvm.used if there is no need.
430 if (LLVMUsed.empty())
431 return;
432
433 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
434 LLVMUsed.size());
435 llvm::GlobalVariable *GV =
436 new llvm::GlobalVariable(ATy, false,
437 llvm::GlobalValue::AppendingLinkage,
438 llvm::ConstantArray::get(ATy, LLVMUsed),
439 "llvm.used", &getModule());
440
441 GV->setSection("llvm.metadata");
442}
443
444void CodeGenModule::EmitDeferred() {
445 // Emit code for any deferred decl which was used. Since a
446 // previously unused static decl may become used during the
447 // generation of code for a static function, iterate until no
448 // changes are made.
Nate Begemanad320b62008-04-20 06:29:50 +0000449 bool Changed;
450 do {
451 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000452
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000453 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
454 e = DeferredDecls.end(); i != e; ) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000455 const ValueDecl *D = *i;
456
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000457 // Check if we have used a decl with the same name
458 // FIXME: The AST should have some sort of aggregate decls or
459 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000460 // FIXME: This is missing some important cases. For example, we
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000461 // need to check for uses in an alias.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000462 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000463 ++i;
Daniel Dunbarced89142008-08-06 00:03:29 +0000464 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000465 }
466
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000467 // Emit the definition.
468 EmitGlobalDefinition(D);
469
Nate Begemanad320b62008-04-20 06:29:50 +0000470 // Erase the used decl from the list.
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000471 i = DeferredDecls.erase(i);
Anders Carlsson2e427d52009-01-04 02:08:04 +0000472
Nate Begemanad320b62008-04-20 06:29:50 +0000473 // Remember that we made a change.
474 Changed = true;
475 }
476 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000477}
478
Nate Begeman8a704172008-04-19 04:17:09 +0000479/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
480/// annotation information for a given GlobalValue. The annotation struct is
481/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000482/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000483/// created from the AnnotateAttr's annotation. The third field is a constant
484/// string containing the name of the translation unit. The fourth field is
485/// the line number in the file of the annotated value declaration.
486///
487/// FIXME: this does not unique the annotation string constants, as llvm-gcc
488/// appears to.
489///
490llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
491 const AnnotateAttr *AA,
492 unsigned LineNo) {
493 llvm::Module *M = &getModule();
494
495 // get [N x i8] constants for the annotation string, and the filename string
496 // which are the 2nd and 3rd elements of the global annotation structure.
497 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
498 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
499 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
500 true);
501
502 // Get the two global values corresponding to the ConstantArrays we just
503 // created to hold the bytes of the strings.
504 llvm::GlobalValue *annoGV =
505 new llvm::GlobalVariable(anno->getType(), false,
506 llvm::GlobalValue::InternalLinkage, anno,
507 GV->getName() + ".str", M);
508 // translation unit name string, emitted into the llvm.metadata section.
509 llvm::GlobalValue *unitGV =
510 new llvm::GlobalVariable(unit->getType(), false,
511 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
512
513 // Create the ConstantStruct that is the global annotion.
514 llvm::Constant *Fields[4] = {
515 llvm::ConstantExpr::getBitCast(GV, SBP),
516 llvm::ConstantExpr::getBitCast(annoGV, SBP),
517 llvm::ConstantExpr::getBitCast(unitGV, SBP),
518 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
519 };
520 return llvm::ConstantStruct::get(Fields, 4, false);
521}
522
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000523bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000524 // Never defer when EmitAllDecls is specified or the decl has
525 // attribute used.
526 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000527 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000528
529 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000530 // Constructors and destructors should never be deferred.
531 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
532 return false;
533
534 if (FD->getStorageClass() != FunctionDecl::Static)
535 return false;
536 } else {
537 const VarDecl *VD = cast<VarDecl>(Global);
538 assert(VD->isFileVarDecl() && "Invalid decl.");
539
540 if (VD->getStorageClass() != VarDecl::Static)
541 return false;
542 }
543
544 return true;
545}
546
547void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000548 // Aliases are deferred until code for everything else has been
549 // emitted.
550 if (Global->getAttr<AliasAttr>()) {
551 Aliases.push_back(Global);
552 return;
553 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000554
Daniel Dunbar36acae42009-03-19 08:27:24 +0000555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000556 // Forward declarations are emitted lazily on first use.
557 if (!FD->isThisDeclarationADefinition())
558 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000559 } else {
560 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000561 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
562
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000563 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000564 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000565 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000566 }
567
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000568 // Defer code generation when possible.
569 if (MayDeferGeneration(Global)) {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000570 DeferredDecls.push_back(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000571 return;
572 }
573
574 // Otherwise emit the definition.
575 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000576}
577
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000578void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
579 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
580 EmitGlobalFunctionDefinition(FD);
581 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
582 EmitGlobalVarDefinition(VD);
583 } else {
584 assert(0 && "Invalid argument to EmitGlobalDefinition()");
585 }
586}
587
Daniel Dunbar2188c532008-07-30 16:32:24 +0000588 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000589 assert(D->hasGlobalStorage() && "Not a global variable");
590
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000591 QualType ASTTy = D->getType();
592 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000593 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000594
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000595 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000596 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000597 if (!Entry) {
598 llvm::GlobalVariable *GV =
599 new llvm::GlobalVariable(Ty, false,
600 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000601 0, getMangledName(D), &getModule(),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000602 0, ASTTy.getAddressSpace());
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000603 Entry = GV;
604
605 // Handle things which are present even on external declarations.
606
607 // FIXME: This code is overly simple and should be merged with
608 // other global handling.
609
610 GV->setConstant(D->getType().isConstant(Context));
611
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000612 // FIXME: Merge with other attribute handling code.
613
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000614 if (D->getStorageClass() == VarDecl::PrivateExtern)
615 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000616
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000617 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Duncan Sands9aa5c262009-03-11 08:40:02 +0000618 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Daniel Dunbar7cbac842009-03-04 17:31:19 +0000619
620 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
621 // Prefaced with special LLVM marker to indicate that the name
622 // should not be munged.
623 GV->setName("\01" + ALA->getLabel());
624 }
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000625 }
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000626
Daniel Dunbar2188c532008-07-30 16:32:24 +0000627 // Make sure the result is of the correct type.
628 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000629}
630
631void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000632 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000633 QualType ASTTy = D->getType();
634 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000635
Chris Lattner4b009652007-07-25 00:24:17 +0000636 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000637 // This is a tentative definition; tentative definitions are
638 // implicitly initialized with { 0 }
639 const llvm::Type* InitTy;
640 if (ASTTy->isIncompleteArrayType()) {
641 // An incomplete array is normally [ TYPE x 0 ], but we need
642 // to fix it to [ TYPE x 1 ].
643 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
644 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
645 } else {
646 InitTy = VarTy;
647 }
648 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000649 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000650 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000651 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000652 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000653 QualType T = D->getInit()->getType();
654 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
655 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000656 }
657 const llvm::Type* InitType = Init->getType();
658
Douglas Gregor3556bc72009-02-13 00:10:09 +0000659 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000660 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
661
Eli Friedman43a0ce82008-05-30 19:50:47 +0000662 if (!GV) {
663 GV = new llvm::GlobalVariable(InitType, false,
664 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000665 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000666 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000667
668 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
669 // If we already have this global and it has an initializer, then
670 // we are in the rare situation where we emitted the defining
671 // declaration of the global and are now being asked to emit a
672 // definition which would be common. This occurs, for example, in
673 // the following situation because statics can be emitted out of
674 // order:
675 //
676 // static int x;
677 // static int *y = &x;
678 // static int x = 10;
679 // int **z = &y;
680 //
681 // Bail here so we don't blow away the definition. Note that if we
682 // can't distinguish here if we emitted a definition with a null
683 // initializer, but this case is safe.
684 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
685 return;
686
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000687 } else if (GV->getType() !=
688 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000689 // We have a definition after a prototype with the wrong type.
690 // We must make a new GlobalVariable* and update everything that used OldGV
691 // (a declaration or tentative definition) with the new GlobalVariable*
692 // (which will be a definition).
693 //
694 // This happens if there is a prototype for a global (e.g. "extern int x[];")
695 // and then a definition of a different type (e.g. "int x[10];"). This also
696 // happens when an initializer has a different type from the type of the
697 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000698 //
699 // FIXME: This also ends up happening if there's a definition followed by
700 // a tentative definition! (Although Sema rejects that construct
701 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000702
703 // Save the old global
704 llvm::GlobalVariable *OldGV = GV;
705
706 // Make a new global with the correct type
707 GV = new llvm::GlobalVariable(InitType, false,
708 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000709 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000710 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000711 // Steal the name of the old global
712 GV->takeName(OldGV);
713
714 // Replace all uses of the old global with the new global
715 llvm::Constant *NewPtrForOldDecl =
716 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
717 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000718
719 // Erase the old global, since it is no longer used.
720 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000721 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000722
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000723 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000724
Nate Begeman8a704172008-04-19 04:17:09 +0000725 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
726 SourceManager &SM = Context.getSourceManager();
727 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000728 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000729 }
730
Chris Lattner4b009652007-07-25 00:24:17 +0000731 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000732 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000733 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000734
Chris Lattner402b3372008-03-03 03:28:21 +0000735 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000736 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000737 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000738
739 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
740 // Prefaced with special LLVM marker to indicate that the name
741 // should not be munged.
742 GV->setName("\01" + ALA->getLabel());
743 }
Chris Lattner4b009652007-07-25 00:24:17 +0000744
745 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000746 if (D->getStorageClass() == VarDecl::Static)
747 GV->setLinkage(llvm::Function::InternalLinkage);
748 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000749 GV->setLinkage(llvm::Function::DLLImportLinkage);
750 else if (D->getAttr<DLLExportAttr>())
751 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000752 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000753 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000754 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000755 // FIXME: This isn't right. This should handle common linkage and other
756 // stuff.
757 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000758 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000759 case VarDecl::Auto:
760 case VarDecl::Register:
761 assert(0 && "Can't have auto or register globals");
762 case VarDecl::None:
763 if (!D->getInit())
Duncan Sands78c33cc2009-03-11 20:15:27 +0000764 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000765 else
766 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000767 break;
768 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000769 // FIXME: common
770 break;
771
Chris Lattner402b3372008-03-03 03:28:21 +0000772 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000773 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
774 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000775 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000776 }
Chris Lattner4b009652007-07-25 00:24:17 +0000777 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000778
Daniel Dunbar97509722009-02-12 17:28:23 +0000779 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
780 GV->setSection(SA->getName());
781
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000782 if (D->getAttr<UsedAttr>())
783 AddUsedGlobal(GV);
784
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000785 // Emit global variable debug information.
786 CGDebugInfo *DI = getDebugInfo();
787 if(DI) {
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 +0000793llvm::GlobalValue *
Daniel Dunbar3f197842009-02-19 07:15:39 +0000794CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000795 const llvm::Type *Ty) {
Eli Friedman040f4db2009-03-05 04:18:07 +0000796 bool DoSetAttributes = true;
797 if (!Ty) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000798 Ty = getTypes().ConvertType(D->getType());
Eli Friedman040f4db2009-03-05 04:18:07 +0000799 if (!isa<llvm::FunctionType>(Ty)) {
800 // This function doesn't have a complete type (for example, the return
801 // type is an incomplete struct). Use a fake type instead, and make
802 // sure not to try to set attributes.
803 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
804 std::vector<const llvm::Type*>(), false);
805 DoSetAttributes = false;
806 }
807 }
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000808 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
809 llvm::Function::ExternalLinkage,
810 getMangledName(D),
811 &getModule());
Eli Friedman040f4db2009-03-05 04:18:07 +0000812 if (DoSetAttributes)
813 SetFunctionAttributes(D, F);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000814 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000815}
816
817llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000818 QualType ASTTy = D->getType();
819 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
820 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000821
822 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000823 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000824 if (!Entry)
Daniel Dunbar3f197842009-02-19 07:15:39 +0000825 Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000826
Chris Lattnerc3a26482009-03-21 06:53:34 +0000827 if (Entry->getType() != PTy)
828 return llvm::ConstantExpr::getBitCast(Entry, PTy);
829 return Entry;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000830}
831
832void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000833 const llvm::FunctionType *Ty =
834 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
835
836 // As a special case, make sure that definitions of K&R function
837 // "type foo()" aren't declared as varargs (which forces the backend
838 // to do unnecessary work).
839 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
840 Ty = llvm::FunctionType::get(Ty->getReturnType(),
841 std::vector<const llvm::Type*>(),
842 false);
843
Douglas Gregor3556bc72009-02-13 00:10:09 +0000844 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000845 if (!Entry) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000846 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000847 } else {
848 // If the types mismatch then we have to rewrite the definition.
849 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
850 // Otherwise, we have a definition after a prototype with the
851 // wrong type. F is the Function* for the one with the wrong
852 // type, we must make a new Function* and update everything that
853 // used F (a declaration) with the new Function* (which will be
854 // a definition).
855 //
856 // This happens if there is a prototype for a function
857 // (e.g. "int f()") and then a definition of a different type
858 // (e.g. "int f(int x)"). Start by making a new function of the
859 // correct type, RAUW, then steal the name.
860 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
861 NewFn->takeName(Entry);
862
863 // Replace uses of F with the Function we will endow with a body.
864 llvm::Constant *NewPtrForOldDecl =
865 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
866 Entry->replaceAllUsesWith(NewPtrForOldDecl);
867
868 // Ok, delete the old function now, which is dead.
869 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
870 Entry->eraseFromParent();
871
872 Entry = NewFn;
873 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000874 }
875
Daniel Dunbar566a6502008-09-08 23:44:31 +0000876 llvm::Function *Fn = cast<llvm::Function>(Entry);
877 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000878
Daniel Dunbar566a6502008-09-08 23:44:31 +0000879 SetFunctionAttributesForDefinition(D, Fn);
880
881 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
882 AddGlobalCtor(Fn, CA->getPriority());
883 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
884 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000885 }
886}
887
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000888llvm::Function *
889CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
890 const std::string &Name) {
891 llvm::Function *Fn = llvm::Function::Create(FTy,
892 llvm::Function::ExternalLinkage,
893 "", &TheModule);
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000894 RuntimeGlobals.push_back(std::make_pair(Fn, Name));
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000895 return Fn;
896}
897
Daniel Dunbarf8fa6e12009-03-06 22:13:30 +0000898llvm::GlobalVariable *
899CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
900 const std::string &Name) {
901 llvm::GlobalVariable *GV =
902 new llvm::GlobalVariable(Ty, /*Constant=*/false,
903 llvm::GlobalValue::ExternalLinkage,
904 0, "", &TheModule);
905 RuntimeGlobals.push_back(std::make_pair(GV, Name));
906 return GV;
907}
908
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000909void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
910 // Make sure that this type is translated.
911 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000912}
913
914
Chris Lattnerab862cc2007-08-31 04:31:45 +0000915/// getBuiltinLibFunction
Mike Stump96b7a152009-02-27 22:42:30 +0000916llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000917 if (BuiltinID > BuiltinFunctions.size())
918 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000919
Chris Lattner9f2d6892007-12-13 00:38:03 +0000920 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
921 // a slot for it.
922 assert(BuiltinID && "Invalid Builtin ID");
Mike Stump96b7a152009-02-27 22:42:30 +0000923 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000924 if (FunctionSlot)
925 return FunctionSlot;
926
Douglas Gregor411889e2009-02-13 23:20:09 +0000927 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
928 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
929 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000930
Douglas Gregor411889e2009-02-13 23:20:09 +0000931 // Get the name, skip over the __builtin_ prefix (if necessary).
932 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
933 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
934 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000935
936 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000937 Builtin::Context::GetBuiltinTypeError Error;
938 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
939 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
940
Chris Lattnerab862cc2007-08-31 04:31:45 +0000941 const llvm::FunctionType *Ty =
942 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
943
944 // FIXME: This has a serious problem with code like this:
945 // void abs() {}
946 // ... __builtin_abs(x);
947 // The two versions of abs will collide. The fix is for the builtin to win,
948 // and for the existing one to be turned into a constantexpr cast of the
949 // builtin. In the case where the existing one is a static function, it
950 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000951 if (llvm::Function *Existing = getModule().getFunction(Name)) {
952 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
953 return FunctionSlot = Existing;
954 assert(Existing == 0 && "FIXME: Name collision");
955 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000956
Chris Lattner72cdb962009-03-01 18:47:06 +0000957 llvm::GlobalValue *&ExistingFn =
958 GlobalDeclMap[getContext().Idents.get(Name).getName()];
Chris Lattnerc3a26482009-03-21 06:53:34 +0000959 if (ExistingFn) {
960 if (ExistingFn->getType() == Ty)
961 return FunctionSlot = ExistingFn;
Chris Lattner72cdb962009-03-01 18:47:06 +0000962 return FunctionSlot = llvm::ConstantExpr::getBitCast(ExistingFn, Ty);
Chris Lattnerc3a26482009-03-21 06:53:34 +0000963 }
Mike Stump96b7a152009-02-27 22:42:30 +0000964
Chris Lattnerab862cc2007-08-31 04:31:45 +0000965 // FIXME: param attributes for sext/zext etc.
Chris Lattner72cdb962009-03-01 18:47:06 +0000966 return FunctionSlot = ExistingFn =
Nate Begemanad320b62008-04-20 06:29:50 +0000967 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
968 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000969}
970
Chris Lattner4b23f942007-12-18 00:25:38 +0000971llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
972 unsigned NumTys) {
973 return llvm::Intrinsic::getDeclaration(&getModule(),
974 (llvm::Intrinsic::ID)IID, Tys, NumTys);
975}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000976
Chris Lattner4b009652007-07-25 00:24:17 +0000977llvm::Function *CodeGenModule::getMemCpyFn() {
978 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000979 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
980 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000981}
Anders Carlsson36a04872007-08-21 00:21:21 +0000982
Eli Friedman8f08a252008-05-26 12:59:39 +0000983llvm::Function *CodeGenModule::getMemMoveFn() {
984 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000985 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
986 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000987}
988
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000989llvm::Function *CodeGenModule::getMemSetFn() {
990 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000991 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
992 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000993}
Chris Lattner4b23f942007-12-18 00:25:38 +0000994
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000995static void appendFieldAndPadding(CodeGenModule &CGM,
996 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000997 FieldDecl *FieldD, FieldDecl *NextFieldD,
998 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000999 RecordDecl* RD, const llvm::StructType *STy)
1000{
1001 // Append the field.
1002 Fields.push_back(Field);
1003
Douglas Gregor8acb7272008-12-11 16:49:14 +00001004 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001005
1006 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001007 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001008 NextStructFieldNo = STy->getNumElements();
1009 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001010 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001011 }
1012
1013 // Append padding
1014 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1015 llvm::Constant *C =
1016 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1017
1018 Fields.push_back(C);
1019 }
1020}
1021
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001022// We still need to work out the details of handling UTF-16.
1023// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001024llvm::Constant *CodeGenModule::
1025GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001026 llvm::StringMapEntry<llvm::Constant *> &Entry =
1027 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1028
1029 if (Entry.getValue())
1030 return Entry.getValue();
1031
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001032 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1033 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001034
1035 if (!CFConstantStringClassRef) {
1036 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1037 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001038
1039 // FIXME: This is fairly broken if
1040 // __CFConstantStringClassReference is already defined, in that it
1041 // will get renamed and the user will most likely see an opaque
1042 // error message. This is a general issue with relying on
1043 // particular names.
1044 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001045 new llvm::GlobalVariable(Ty, false,
1046 llvm::GlobalVariable::ExternalLinkage, 0,
1047 "__CFConstantStringClassReference",
1048 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001049
1050 // Decay array -> ptr
1051 CFConstantStringClassRef =
1052 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001053 }
1054
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001055 QualType CFTy = getContext().getCFConstantStringType();
1056 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001057
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001058 const llvm::StructType *STy =
1059 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1060
1061 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001062 RecordDecl::field_iterator Field = CFRD->field_begin();
1063
Anders Carlsson36a04872007-08-21 00:21:21 +00001064 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001065 FieldDecl *CurField = *Field++;
1066 FieldDecl *NextField = *Field++;
1067 appendFieldAndPadding(*this, Fields, CurField, NextField,
1068 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001069
1070 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001071 CurField = NextField;
1072 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001073 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001074 appendFieldAndPadding(*this, Fields, CurField, NextField,
1075 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001076
1077 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001078 CurField = NextField;
1079 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001080 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001081 C = new llvm::GlobalVariable(C->getType(), true,
1082 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001083 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001084 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001085 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1086 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001087
1088 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001089 CurField = NextField;
1090 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001091 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001092 appendFieldAndPadding(*this, Fields, CurField, NextField,
1093 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001094
1095 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001096 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001097 llvm::GlobalVariable *GV =
1098 new llvm::GlobalVariable(C->getType(), true,
1099 llvm::GlobalVariable::InternalLinkage,
1100 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001101
Anders Carlsson9be009e2007-11-01 00:41:52 +00001102 GV->setSection("__DATA,__cfstring");
1103 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001104
Anders Carlsson9be009e2007-11-01 00:41:52 +00001105 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001106}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001107
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001108/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001109/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001110std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001111 const char *StrData = E->getStrData();
1112 unsigned Len = E->getByteLength();
1113
1114 const ConstantArrayType *CAT =
1115 getContext().getAsConstantArrayType(E->getType());
1116 assert(CAT && "String isn't pointer or array!");
1117
Chris Lattner14032222009-02-26 23:01:51 +00001118 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001119 std::string Str(StrData, StrData+Len);
1120 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001121
1122 if (E->isWide())
1123 RealLen *= getContext().Target.getWCharWidth()/8;
1124
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001125 Str.resize(RealLen, '\0');
1126
1127 return Str;
1128}
1129
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001130/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1131/// constant array for the given string literal.
1132llvm::Constant *
1133CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1134 // FIXME: This can be more efficient.
1135 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1136}
1137
Chris Lattnerc5d32632009-02-24 22:18:39 +00001138/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1139/// array for the given ObjCEncodeExpr node.
1140llvm::Constant *
1141CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1142 std::string Str;
1143 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001144
1145 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001146}
1147
1148
Chris Lattnera6dcce32008-02-11 00:02:17 +00001149/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001150static llvm::Constant *GenerateStringLiteral(const std::string &str,
1151 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001152 CodeGenModule &CGM,
1153 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001154 // Create Constant for this string literal. Don't add a '\0'.
1155 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001156
1157 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001158 return new llvm::GlobalVariable(C->getType(), constant,
1159 llvm::GlobalValue::InternalLinkage,
1160 C, GlobalName ? GlobalName : ".str",
1161 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001162}
1163
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001164/// GetAddrOfConstantString - Returns a pointer to a character array
1165/// containing the literal. This contents are exactly that of the
1166/// given string, i.e. it will not be null terminated automatically;
1167/// see GetAddrOfConstantCString. Note that whether the result is
1168/// actually a pointer to an LLVM constant depends on
1169/// Feature.WriteableStrings.
1170///
1171/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001172llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1173 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001174 // Don't share any string literals if writable-strings is turned on.
1175 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001176 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001177
1178 llvm::StringMapEntry<llvm::Constant *> &Entry =
1179 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1180
1181 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001182 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001183
1184 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001185 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001186 Entry.setValue(C);
1187 return C;
1188}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001189
1190/// GetAddrOfConstantCString - Returns a pointer to a character
1191/// array containing the literal and a terminating '\-'
1192/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001193llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1194 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001195 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001196}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001197
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001198/// EmitObjCPropertyImplementations - Emit information for synthesized
1199/// properties for an implementation.
1200void CodeGenModule::EmitObjCPropertyImplementations(const
1201 ObjCImplementationDecl *D) {
1202 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1203 e = D->propimpl_end(); i != e; ++i) {
1204 ObjCPropertyImplDecl *PID = *i;
1205
1206 // Dynamic is just for type-checking.
1207 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1208 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1209
1210 // Determine which methods need to be implemented, some may have
1211 // been overridden. Note that ::isSynthesized is not the method
1212 // we want, that just indicates if the decl came from a
1213 // property. What we want to know is if the method is defined in
1214 // this implementation.
1215 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001216 CodeGenFunction(*this).GenerateObjCGetter(
1217 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001218 if (!PD->isReadOnly() &&
1219 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001220 CodeGenFunction(*this).GenerateObjCSetter(
1221 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001222 }
1223 }
1224}
1225
Daniel Dunbar27250d32008-08-15 23:26:23 +00001226/// EmitTopLevelDecl - Emit code for a single top level declaration.
1227void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1228 // If an error has occurred, stop code generation, but continue
1229 // parsing and semantic analysis (to ensure all warnings and errors
1230 // are emitted).
1231 if (Diags.hasErrorOccurred())
1232 return;
1233
1234 switch (D->getKind()) {
1235 case Decl::Function:
1236 case Decl::Var:
1237 EmitGlobal(cast<ValueDecl>(D));
1238 break;
1239
1240 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001241 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001242 break;
1243
1244 // Objective-C Decls
1245
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001246 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001247 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001248 case Decl::ObjCForwardProtocol:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001249 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001250
Daniel Dunbar27250d32008-08-15 23:26:23 +00001251 case Decl::ObjCProtocol:
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001252 case Decl::ObjCCategory:
1253 case Decl::ObjCInterface: {
1254 ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D);
1255 for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(),
1256 e = OCD->tuvar_end(); i != e; ++i) {
1257 VarDecl *VD = *i;
1258 EmitGlobal(VD);
1259 }
1260 if (D->getKind() == Decl::ObjCProtocol)
1261 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001262 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001263 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001264
1265 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001266 // Categories have properties but don't support synthesize so we
1267 // can ignore them here.
1268
Daniel Dunbar27250d32008-08-15 23:26:23 +00001269 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1270 break;
1271
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001272 case Decl::ObjCImplementation: {
1273 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1274 EmitObjCPropertyImplementations(OMD);
1275 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001276 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001277 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001278 case Decl::ObjCMethod: {
1279 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1280 // If this is not a prototype, emit the body.
1281 if (OMD->getBody())
1282 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1283 break;
1284 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001285 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001286 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001287 break;
1288
1289 case Decl::LinkageSpec: {
1290 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1291 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001292 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001293 // FIXME: implement C++ linkage, C linkage works mostly by C
1294 // language reuse already.
1295 break;
1296 }
1297
1298 case Decl::FileScopeAsm: {
1299 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1300 std::string AsmString(AD->getAsmString()->getStrData(),
1301 AD->getAsmString()->getByteLength());
1302
1303 const std::string &S = getModule().getModuleInlineAsm();
1304 if (S.empty())
1305 getModule().setModuleInlineAsm(AsmString);
1306 else
1307 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1308 break;
1309 }
1310
1311 default:
1312 // Make sure we handled everything we should, every other kind is
1313 // a non-top-level decl. FIXME: Would be nice to have an
1314 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1315 // that easily.
1316 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1317 }
1318}