blob: d502d79d2945157841d4294ca9805e6acb4d1371 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000025#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000026#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000028#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000029#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000030#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000032#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34using namespace CodeGen;
35
36
Chris Lattnerbd360642009-03-26 05:00:52 +000037CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattnerfb97b032007-12-02 01:40:18 +000038 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerbd360642009-03-26 05:00:52 +000039 Diagnostic &diags)
40 : BlockModule(C, M, TD, Types, *this), Context(C),
41 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000042 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
Owen Andersona1cf15f2009-07-14 23:10:40 +000043 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0),
44 VMContext(M.getContext()) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000045
Chris Lattner3c8f1532009-03-21 07:12:05 +000046 if (!Features.ObjC1)
47 Runtime = 0;
48 else if (!Features.NeXTRuntime)
49 Runtime = CreateGNUObjCRuntime(*this);
50 else if (Features.ObjCNonFragileABI)
51 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
52 else
53 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000054
55 // If debug info generation is enabled, create the CGDebugInfo object.
Devang Patel6dba4322009-07-14 21:31:22 +000056 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000057}
58
59CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000060 delete Runtime;
61 delete DebugInfo;
62}
63
64void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +000065 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000066 if (Runtime)
67 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
68 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000069 EmitCtorList(GlobalCtors, "llvm.global_ctors");
70 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000071 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000072 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000073}
74
Daniel Dunbar488e9932008-08-16 00:56:44 +000075/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000076/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000077void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
78 bool OmitOnError) {
79 if (OmitOnError && getDiags().hasErrorOccurred())
80 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000081 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000082 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000083 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000084 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
85 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000086}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000087
Daniel Dunbar488e9932008-08-16 00:56:44 +000088/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000089/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000090void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
91 bool OmitOnError) {
92 if (OmitOnError && getDiags().hasErrorOccurred())
93 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000094 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000095 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000096 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000097 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000098}
99
Daniel Dunbar04d40782009-04-14 06:00:08 +0000100LangOptions::VisibilityMode
101CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
102 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
103 if (VD->getStorageClass() == VarDecl::PrivateExtern)
104 return LangOptions::Hidden;
105
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000106 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000107 switch (attr->getVisibility()) {
108 default: assert(0 && "Unknown visibility!");
109 case VisibilityAttr::DefaultVisibility:
110 return LangOptions::Default;
111 case VisibilityAttr::HiddenVisibility:
112 return LangOptions::Hidden;
113 case VisibilityAttr::ProtectedVisibility:
114 return LangOptions::Protected;
115 }
116 }
117
118 return getLangOptions().getVisibilityMode();
119}
120
121void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
122 const Decl *D) const {
123 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000124 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000125 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000126 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000127 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000128
Daniel Dunbar04d40782009-04-14 06:00:08 +0000129 switch (getDeclVisibilityMode(D)) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000130 default: assert(0 && "Unknown visibility!");
Daniel Dunbar04d40782009-04-14 06:00:08 +0000131 case LangOptions::Default:
132 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
133 case LangOptions::Hidden:
134 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
135 case LangOptions::Protected:
136 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman4f8d1232008-05-22 00:50:06 +0000137 }
138}
139
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000140const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
141 const NamedDecl *ND = GD.getDecl();
142
143 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
144 return getMangledCXXCtorName(D, GD.getCtorType());
145 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
146 return getMangledCXXDtorName(D, GD.getDtorType());
147
148 return getMangledName(ND);
149}
150
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000151/// \brief Retrieves the mangled name for the given declaration.
152///
153/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000154/// const char* containing the mangled name. Otherwise, returns
155/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000156///
Douglas Gregor6ec36682009-02-18 23:53:56 +0000157const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000158 // In C, functions with no attributes never need to be mangled. Fastpath them.
159 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
160 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000161 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000162 }
163
Douglas Gregor6ec36682009-02-18 23:53:56 +0000164 llvm::SmallString<256> Name;
165 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000166 if (!mangleName(ND, Context, Out)) {
167 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000168 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000169 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000170
Douglas Gregor6ec36682009-02-18 23:53:56 +0000171 Name += '\0';
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000172 return UniqueMangledName(Name.begin(), Name.end());
173}
174
175const char *CodeGenModule::UniqueMangledName(const char *NameStart,
176 const char *NameEnd) {
177 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
178
179 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000180}
181
Chris Lattner6d397602008-03-14 17:18:18 +0000182/// AddGlobalCtor - Add a function to the list that will be called before
183/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000184void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000185 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000187}
188
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000189/// AddGlobalDtor - Add a function to the list that will be called
190/// when the module is unloaded.
191void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000192 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000193 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
194}
195
196void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
197 // Ctor function type is void()*.
198 llvm::FunctionType* CtorFTy =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000199 VMContext.getFunctionType(llvm::Type::VoidTy,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000200 std::vector<const llvm::Type*>(),
201 false);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000202 llvm::Type *CtorPFTy = VMContext.getPointerTypeUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000203
204 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000205 llvm::StructType* CtorStructTy =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000206 VMContext.getStructType(llvm::Type::Int32Ty,
207 VMContext.getPointerTypeUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000208
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000209 // Construct the constructor and destructor arrays.
210 std::vector<llvm::Constant*> Ctors;
211 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
212 std::vector<llvm::Constant*> S;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000213 S.push_back(
214 VMContext.getConstantInt(llvm::Type::Int32Ty, I->second, false));
215 S.push_back(VMContext.getConstantExprBitCast(I->first, CtorPFTy));
216 Ctors.push_back(VMContext.getConstantStruct(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000217 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000218
219 if (!Ctors.empty()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000220 llvm::ArrayType *AT = VMContext.getArrayType(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000221 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000222 llvm::GlobalValue::AppendingLinkage,
Owen Andersona1cf15f2009-07-14 23:10:40 +0000223 VMContext.getConstantArray(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000224 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000225 }
Chris Lattner6d397602008-03-14 17:18:18 +0000226}
227
Nate Begeman532485c2008-04-18 23:43:57 +0000228void CodeGenModule::EmitAnnotations() {
229 if (Annotations.empty())
230 return;
231
232 // Create a new global variable for the ConstantStruct in the Module.
233 llvm::Constant *Array =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000234 VMContext.getConstantArray(VMContext.getArrayType(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000235 Annotations.size()),
236 Annotations);
237 llvm::GlobalValue *gv =
Owen Anderson1c431b32009-07-08 19:05:04 +0000238 new llvm::GlobalVariable(TheModule, Array->getType(), false,
Nate Begeman532485c2008-04-18 23:43:57 +0000239 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000240 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000241 gv->setSection("llvm.metadata");
242}
243
Chris Lattner86daeee2009-04-14 16:44:36 +0000244static CodeGenModule::GVALinkage
Douglas Gregor68584ed2009-06-18 16:11:24 +0000245GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
246 const LangOptions &Features) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000247 // The kind of external linkage this function will have, if it is not
248 // inline or static.
249 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
250 if (Context.getLangOptions().CPlusPlus &&
251 (FD->getPrimaryTemplate() || FD->getInstantiatedFromMemberFunction()) &&
252 !FD->isExplicitSpecialization())
253 External = CodeGenModule::GVA_TemplateInstantiation;
254
Anders Carlsson167b8242009-05-15 18:35:39 +0000255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
256 // C++ member functions defined inside the class are always inline.
Argyrios Kyrtzidisf5cecfb2009-06-17 22:49:50 +0000257 if (MD->isInline() || !MD->isOutOfLine())
Anders Carlsson167b8242009-05-15 18:35:39 +0000258 return CodeGenModule::GVA_CXXInline;
259
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000260 return External;
Anders Carlsson167b8242009-05-15 18:35:39 +0000261 }
262
Eli Friedman43907e82009-05-03 19:01:39 +0000263 // "static" functions get internal linkage.
Eli Friedman5e222132009-05-03 18:13:43 +0000264 if (FD->getStorageClass() == FunctionDecl::Static)
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000265 return CodeGenModule::GVA_Internal;
266
Chris Lattner005eedc2009-05-12 20:26:52 +0000267 if (!FD->isInline())
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000268 return External;
Chris Lattner86daeee2009-04-14 16:44:36 +0000269
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000270 // If the inline function explicitly has the GNU inline attribute on it, or if
271 // this is C89 mode, we use to GNU semantics.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000272 if (!Features.C99 && !Features.CPlusPlus) {
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000273 // extern inline in GNU mode is like C99 inline.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000274 if (FD->getStorageClass() == FunctionDecl::Extern)
275 return CodeGenModule::GVA_C99Inline;
276 // Normal inline is a strong symbol.
277 return CodeGenModule::GVA_StrongExternal;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000278 } else if (FD->hasActiveGNUInlineAttribute(Context)) {
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000279 // GCC in C99 mode seems to use a different decision-making
280 // process for extern inline, which factors in previous
281 // declarations.
Douglas Gregor68584ed2009-06-18 16:11:24 +0000282 if (FD->isExternGNUInline(Context))
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000283 return CodeGenModule::GVA_C99Inline;
284 // Normal inline is a strong symbol.
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000285 return External;
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000286 }
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000287
Chris Lattner86daeee2009-04-14 16:44:36 +0000288 // The definition of inline changes based on the language. Note that we
289 // have already handled "static inline" above, with the GVA_Internal case.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000290 if (Features.CPlusPlus) // inline and extern inline.
Chris Lattner86daeee2009-04-14 16:44:36 +0000291 return CodeGenModule::GVA_CXXInline;
292
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000293 assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
Douglas Gregorb3efa982009-04-23 18:22:55 +0000294 if (FD->isC99InlineDefinition())
295 return CodeGenModule::GVA_C99Inline;
296
297 return CodeGenModule::GVA_StrongExternal;
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000298}
299
300/// SetFunctionDefinitionAttributes - Set attributes for a global.
Daniel Dunbarb97b6922009-04-14 06:19:49 +0000301///
Mike Stumpf5408fe2009-05-16 07:57:57 +0000302/// FIXME: This is currently only done for aliases and functions, but not for
303/// variables (these details are set in EmitGlobalVarDefinition for variables).
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000304void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
305 llvm::GlobalValue *GV) {
Douglas Gregor68584ed2009-06-18 16:11:24 +0000306 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000307
Daniel Dunbar55d6f502009-04-14 07:19:20 +0000308 if (Linkage == GVA_Internal) {
Chris Lattner9f942792009-04-14 05:33:52 +0000309 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000310 } else if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000311 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000312 } else if (D->hasAttr<WeakAttr>()) {
Chris Lattner44b0bc02009-04-14 06:04:17 +0000313 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000314 } else if (Linkage == GVA_C99Inline) {
315 // In C99 mode, 'inline' functions are guaranteed to have a strong
316 // definition somewhere else, so we can use available_externally linkage.
Chris Lattnerd9d049a2009-04-14 06:27:57 +0000317 GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000318 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
Chris Lattner86daeee2009-04-14 16:44:36 +0000319 // In C++, the compiler has to emit a definition in every translation unit
320 // that references the function. We should use linkonce_odr because
321 // a) if all references in this translation unit are optimized away, we
322 // don't need to codegen it. b) if the function persists, it needs to be
323 // merged with other definitions. c) C++ has the ODR, so we know the
324 // definition is dependable.
325 GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000326 } else {
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000327 assert(Linkage == GVA_StrongExternal);
328 // Otherwise, we have strong external linkage.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000329 GV->setLinkage(llvm::Function::ExternalLinkage);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000330 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000331
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000332 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000333}
334
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000335void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
336 const CGFunctionInfo &Info,
337 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000338 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000339 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000340
Devang Patel761d7f72008-09-25 21:02:23 +0000341 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
342 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000343
344 // Set the appropriate calling convention for the Function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000345 if (D->hasAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000346 F->setCallingConv(llvm::CallingConv::X86_FastCall);
347
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000348 if (D->hasAttr<StdCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000349 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000350}
351
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000352void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
353 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000354 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000355 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000356
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000357 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000358 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000359
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000360 if (D->hasAttr<NoinlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000361 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000362}
363
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000364void CodeGenModule::SetCommonAttributes(const Decl *D,
365 llvm::GlobalValue *GV) {
366 setGlobalVisibility(GV, D);
367
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000368 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000369 AddUsedGlobal(GV);
370
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000371 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000372 GV->setSection(SA->getName());
373}
374
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000375void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
376 llvm::Function *F,
377 const CGFunctionInfo &FI) {
378 SetLLVMFunctionAttributes(D, FI, F);
379 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000380
381 F->setLinkage(llvm::Function::InternalLinkage);
382
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000383 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000384}
385
386void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000387 llvm::Function *F,
388 bool IsIncompleteFunction) {
389 if (!IsIncompleteFunction)
390 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000391
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000392 // Only a few attributes are set on declarations; these may later be
393 // overridden by a definition.
394
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000395 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000396 F->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000397 } else if (FD->hasAttr<WeakAttr>() ||
398 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000399 // "extern_weak" is overloaded in LLVM; we probably should have
400 // separate linkage types for this.
401 F->setLinkage(llvm::Function::ExternalWeakLinkage);
402 } else {
403 F->setLinkage(llvm::Function::ExternalLinkage);
404 }
405
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000406 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000407 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000408}
409
Daniel Dunbar02698712009-02-13 20:29:50 +0000410void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
411 assert(!GV->isDeclaration() &&
412 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000413 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000414}
415
416void CodeGenModule::EmitLLVMUsed() {
417 // Don't create llvm.used if there is no need.
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000418 // FIXME. Runtime indicates that there might be more 'used' symbols; but not
419 // necessariy. So, this test is not accurate for emptiness.
420 if (LLVMUsed.empty() && !Runtime)
Daniel Dunbar02698712009-02-13 20:29:50 +0000421 return;
422
Owen Andersona1cf15f2009-07-14 23:10:40 +0000423 llvm::Type *i8PTy = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Chris Lattner35f38a22009-03-31 22:37:52 +0000424
425 // Convert LLVMUsed to what ConstantArray needs.
426 std::vector<llvm::Constant*> UsedArray;
427 UsedArray.resize(LLVMUsed.size());
428 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
429 UsedArray[i] =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000430 VMContext.getConstantExprBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
431 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000432 }
433
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000434 if (Runtime)
435 Runtime->MergeMetadataGlobals(UsedArray);
436 if (UsedArray.empty())
437 return;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000438 llvm::ArrayType *ATy = VMContext.getArrayType(i8PTy, UsedArray.size());
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000439
Daniel Dunbar02698712009-02-13 20:29:50 +0000440 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000441 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000442 llvm::GlobalValue::AppendingLinkage,
Owen Andersona1cf15f2009-07-14 23:10:40 +0000443 VMContext.getConstantArray(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000444 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000445
446 GV->setSection("llvm.metadata");
447}
448
449void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000450 // Emit code for any potentially referenced deferred decls. Since a
451 // previously unused static decl may become used during the generation of code
452 // for a static function, iterate until no changes are made.
453 while (!DeferredDeclsToEmit.empty()) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000454 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000455 DeferredDeclsToEmit.pop_back();
456
457 // The mangled name for the decl must have been emitted in GlobalDeclMap.
458 // Look it up to see if it was defined with a stronger definition (e.g. an
459 // extern inline function with a strong function redefinition). If so,
460 // just ignore the deferred decl.
461 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
462 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000463
Chris Lattner67b00522009-03-21 09:44:56 +0000464 if (!CGRef->isDeclaration())
465 continue;
466
467 // Otherwise, emit the definition and move on to the next one.
468 EmitGlobalDefinition(D);
469 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
471
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000472/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
473/// annotation information for a given GlobalValue. The annotation struct is
474/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000475/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000476/// created from the AnnotateAttr's annotation. The third field is a constant
477/// string containing the name of the translation unit. The fourth field is
478/// the line number in the file of the annotated value declaration.
479///
480/// FIXME: this does not unique the annotation string constants, as llvm-gcc
481/// appears to.
482///
483llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
484 const AnnotateAttr *AA,
485 unsigned LineNo) {
486 llvm::Module *M = &getModule();
487
488 // get [N x i8] constants for the annotation string, and the filename string
489 // which are the 2nd and 3rd elements of the global annotation structure.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000490 const llvm::Type *SBP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
491 llvm::Constant *anno = VMContext.getConstantArray(AA->getAnnotation(), true);
492 llvm::Constant *unit = VMContext.getConstantArray(M->getModuleIdentifier(),
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000493 true);
494
495 // Get the two global values corresponding to the ConstantArrays we just
496 // created to hold the bytes of the strings.
497 llvm::GlobalValue *annoGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000498 new llvm::GlobalVariable(*M, anno->getType(), false,
499 llvm::GlobalValue::PrivateLinkage, anno,
500 GV->getName());
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000501 // translation unit name string, emitted into the llvm.metadata section.
502 llvm::GlobalValue *unitGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000503 new llvm::GlobalVariable(*M, unit->getType(), false,
504 llvm::GlobalValue::PrivateLinkage, unit,
505 ".str");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000506
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000507 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000508 llvm::Constant *Fields[4] = {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000509 VMContext.getConstantExprBitCast(GV, SBP),
510 VMContext.getConstantExprBitCast(annoGV, SBP),
511 VMContext.getConstantExprBitCast(unitGV, SBP),
512 VMContext.getConstantInt(llvm::Type::Int32Ty, LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000513 };
Owen Andersona1cf15f2009-07-14 23:10:40 +0000514 return VMContext.getConstantStruct(Fields, 4, false);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000515}
516
Daniel Dunbar73241df2009-02-13 21:18:01 +0000517bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000518 // Never defer when EmitAllDecls is specified or the decl has
519 // attribute used.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000520 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000521 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000522
523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000524 // Constructors and destructors should never be deferred.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000525 if (FD->hasAttr<ConstructorAttr>() ||
526 FD->hasAttr<DestructorAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000527 return false;
528
Douglas Gregor68584ed2009-06-18 16:11:24 +0000529 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000530
531 // static, static inline, always_inline, and extern inline functions can
Chris Lattner86daeee2009-04-14 16:44:36 +0000532 // always be deferred. Normal inline functions can be deferred in C99/C++.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000533 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
534 Linkage == GVA_CXXInline)
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000535 return true;
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000536 return false;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000537 }
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000538
539 const VarDecl *VD = cast<VarDecl>(Global);
540 assert(VD->isFileVarDecl() && "Invalid decl");
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000541
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000542 return VD->getStorageClass() == VarDecl::Static;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000543}
544
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000545void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000546 const ValueDecl *Global = GD.getDecl();
547
Chris Lattnerbd532712009-03-22 21:47:11 +0000548 // If this is an alias definition (which otherwise looks like a declaration)
549 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000550 if (Global->hasAttr<AliasAttr>())
Chris Lattnerbd532712009-03-22 21:47:11 +0000551 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000552
Chris Lattner67b00522009-03-21 09:44:56 +0000553 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000555 // Forward declarations are emitted lazily on first use.
556 if (!FD->isThisDeclarationADefinition())
557 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000558 } else {
559 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000560 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
561
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000562 // In C++, if this is marked "extern", defer code generation.
Anders Carlsson2928c212009-05-16 21:02:39 +0000563 if (getLangOptions().CPlusPlus && !VD->getInit() &&
564 (VD->getStorageClass() == VarDecl::Extern ||
565 VD->isExternC(getContext())))
Daniel Dunbar73241df2009-02-13 21:18:01 +0000566 return;
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000567
568 // In C, if this isn't a definition, defer code generation.
569 if (!getLangOptions().CPlusPlus && !VD->getInit())
570 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000571 }
572
Chris Lattner67b00522009-03-21 09:44:56 +0000573 // Defer code generation when possible if this is a static definition, inline
574 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000575 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000576 // If the value has already been used, add it directly to the
577 // DeferredDeclsToEmit list.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000578 const char *MangledName = getMangledName(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000579 if (GlobalDeclMap.count(MangledName))
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000580 DeferredDeclsToEmit.push_back(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000581 else {
582 // Otherwise, remember that we saw a deferred decl with this name. The
583 // first use of the mangled name will cause it to move into
584 // DeferredDeclsToEmit.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000585 DeferredDecls[MangledName] = GD;
Chris Lattner67b00522009-03-21 09:44:56 +0000586 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000587 return;
588 }
589
590 // Otherwise emit the definition.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000591 EmitGlobalDefinition(GD);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000592}
593
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000594void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000595 const ValueDecl *D = GD.getDecl();
596
597 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
598 EmitCXXConstructor(CD, GD.getCtorType());
Anders Carlsson7267c162009-05-29 21:03:38 +0000599 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
600 EmitCXXDestructor(DD, GD.getDtorType());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000601 else if (isa<FunctionDecl>(D))
602 EmitGlobalFunctionDefinition(GD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000603 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000604 EmitGlobalVarDefinition(VD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000605 else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000606 assert(0 && "Invalid argument to EmitGlobalDefinition()");
607 }
608}
609
Chris Lattner74391b42009-03-22 21:03:39 +0000610/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
611/// module, create and return an llvm Function with the specified type. If there
612/// is something in the module with the specified name, return it potentially
613/// bitcasted to the right type.
614///
615/// If D is non-null, it specifies a decl that correspond to this. This is used
616/// to set the attributes on the function when it is first created.
617llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
618 const llvm::Type *Ty,
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000619 GlobalDecl D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000620 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000621 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
622 if (Entry) {
623 if (Entry->getType()->getElementType() == Ty)
624 return Entry;
625
626 // Make sure the result is of the correct type.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000627 const llvm::Type *PTy = VMContext.getPointerTypeUnqual(Ty);
628 return VMContext.getConstantExprBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000629 }
630
Chris Lattner67b00522009-03-21 09:44:56 +0000631 // This is the first use or definition of a mangled name. If there is a
632 // deferred decl with this name, remember that we need to emit it at the end
633 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000634 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner9fa959d2009-05-12 20:58:15 +0000635 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000636 if (DDI != DeferredDecls.end()) {
637 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
638 // list, and remove it from DeferredDecls (since we don't need it anymore).
639 DeferredDeclsToEmit.push_back(DDI->second);
640 DeferredDecls.erase(DDI);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000641 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattner0c337ed2009-05-12 21:02:27 +0000642 // If this the first reference to a C++ inline function in a class, queue up
643 // the deferred function body for emission. These are not seen as
644 // top-level declarations.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000645 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
646 DeferredDeclsToEmit.push_back(D);
Chris Lattner67b00522009-03-21 09:44:56 +0000647 }
648
Chris Lattner0558e792009-03-21 09:25:43 +0000649 // This function doesn't have a complete type (for example, the return
650 // type is an incomplete struct). Use a fake type instead, and make
651 // sure not to try to set attributes.
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000652 bool IsIncompleteFunction = false;
Chris Lattner0558e792009-03-21 09:25:43 +0000653 if (!isa<llvm::FunctionType>(Ty)) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000654 Ty = VMContext.getFunctionType(llvm::Type::VoidTy,
Chris Lattner0558e792009-03-21 09:25:43 +0000655 std::vector<const llvm::Type*>(), false);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000656 IsIncompleteFunction = true;
Chris Lattner0558e792009-03-21 09:25:43 +0000657 }
658 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
659 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000660 "", &getModule());
661 F->setName(MangledName);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000662 if (D.getDecl())
663 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F,
664 IsIncompleteFunction);
Chris Lattner0558e792009-03-21 09:25:43 +0000665 Entry = F;
666 return F;
667}
668
Chris Lattner74391b42009-03-22 21:03:39 +0000669/// GetAddrOfFunction - Return the address of the given function. If Ty is
670/// non-null, then this function will use the specified type if it has to
671/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000672llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner74391b42009-03-22 21:03:39 +0000673 const llvm::Type *Ty) {
674 // If there was no specific requested type, just convert it now.
675 if (!Ty)
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000676 Ty = getTypes().ConvertType(GD.getDecl()->getType());
677 return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
Chris Lattner74391b42009-03-22 21:03:39 +0000678}
Eli Friedman77ba7082008-05-30 19:50:47 +0000679
Chris Lattner74391b42009-03-22 21:03:39 +0000680/// CreateRuntimeFunction - Create a new runtime function with the specified
681/// type and name.
682llvm::Constant *
683CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
684 const char *Name) {
685 // Convert Name to be a uniqued string from the IdentifierInfo table.
686 Name = getContext().Idents.get(Name).getName();
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000687 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattner74391b42009-03-22 21:03:39 +0000688}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000689
Chris Lattner74391b42009-03-22 21:03:39 +0000690/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
691/// create and return an llvm GlobalVariable with the specified type. If there
692/// is something in the module with the specified name, return it potentially
693/// bitcasted to the right type.
694///
695/// If D is non-null, it specifies a decl that correspond to this. This is used
696/// to set the attributes on the global when it is first created.
697llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
698 const llvm::PointerType*Ty,
699 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000700 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000701 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000702 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000703 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000704 return Entry;
705
Chris Lattner99b53612009-03-21 08:03:33 +0000706 // Make sure the result is of the correct type.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000707 return VMContext.getConstantExprBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000708 }
Chris Lattner67b00522009-03-21 09:44:56 +0000709
710 // This is the first use or definition of a mangled name. If there is a
711 // deferred decl with this name, remember that we need to emit it at the end
712 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000713 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner67b00522009-03-21 09:44:56 +0000714 DeferredDecls.find(MangledName);
715 if (DDI != DeferredDecls.end()) {
716 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
717 // list, and remove it from DeferredDecls (since we don't need it anymore).
718 DeferredDeclsToEmit.push_back(DDI->second);
719 DeferredDecls.erase(DDI);
720 }
721
Chris Lattner99b53612009-03-21 08:03:33 +0000722 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000723 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000724 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000725 0, "", 0,
Eli Friedman56ebe502009-04-19 21:05:03 +0000726 false, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000727 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000728
729 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000730 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000731 // FIXME: This code is overly simple and should be merged with other global
732 // handling.
Chris Lattner74391b42009-03-22 21:03:39 +0000733 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000734
Chris Lattner74391b42009-03-22 21:03:39 +0000735 // FIXME: Merge with other attribute handling code.
736 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbar04d40782009-04-14 06:00:08 +0000737 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000738
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000739 if (D->hasAttr<WeakAttr>() ||
740 D->hasAttr<WeakImportAttr>())
Chris Lattner74391b42009-03-22 21:03:39 +0000741 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman56ebe502009-04-19 21:05:03 +0000742
743 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +0000744 }
745
Chris Lattner99b53612009-03-21 08:03:33 +0000746 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000747}
748
Chris Lattner74391b42009-03-22 21:03:39 +0000749
750/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
751/// given global variable. If Ty is non-null and if the global doesn't exist,
752/// then it will be greated with the specified type instead of whatever the
753/// normal requested type would be.
754llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
755 const llvm::Type *Ty) {
756 assert(D->hasGlobalStorage() && "Not a global variable");
757 QualType ASTTy = D->getType();
758 if (Ty == 0)
759 Ty = getTypes().ConvertTypeForMem(ASTTy);
760
761 const llvm::PointerType *PTy =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000762 VMContext.getPointerType(Ty, ASTTy.getAddressSpace());
Chris Lattner74391b42009-03-22 21:03:39 +0000763 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
764}
765
766/// CreateRuntimeVariable - Create a new runtime global variable with the
767/// specified type and name.
768llvm::Constant *
769CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
770 const char *Name) {
771 // Convert Name to be a uniqued string from the IdentifierInfo table.
772 Name = getContext().Idents.get(Name).getName();
Owen Andersona1cf15f2009-07-14 23:10:40 +0000773 return GetOrCreateLLVMGlobal(Name, VMContext.getPointerTypeUnqual(Ty), 0);
Chris Lattner74391b42009-03-22 21:03:39 +0000774}
775
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000776void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
777 assert(!D->getInit() && "Cannot emit definite definitions here!");
778
Douglas Gregor7520bd12009-04-21 19:28:58 +0000779 if (MayDeferGeneration(D)) {
780 // If we have not seen a reference to this variable yet, place it
781 // into the deferred declarations table to be emitted if needed
782 // later.
783 const char *MangledName = getMangledName(D);
784 if (GlobalDeclMap.count(MangledName) == 0) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000785 DeferredDecls[MangledName] = GlobalDecl(D);
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000786 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +0000787 }
788 }
789
790 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000791 EmitGlobalVarDefinition(D);
792}
793
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000794void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000795 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000796 QualType ASTTy = D->getType();
Chris Lattnerb75863d2009-04-10 00:35:59 +0000797
Chris Lattner8f32f712007-07-14 00:23:28 +0000798 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000799 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000800 // implicitly initialized with { 0 }.
801 //
802 // Note that tentative definitions are only emitted at the end of
803 // a translation unit, so they should never have incomplete
804 // type. In addition, EmitTentativeDefinition makes sure that we
805 // never attempt to emit a tentative definition if a real one
806 // exists. A use may still exists, however, so we still may need
807 // to do a RAUW.
808 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Owen Anderson69243822009-07-13 04:10:07 +0000809 Init = getLLVMContext().getNullValue(getTypes().ConvertTypeForMem(ASTTy));
Eli Friedman77ba7082008-05-30 19:50:47 +0000810 } else {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000811 Init = EmitConstantExpr(D->getInit(), D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +0000812 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000813 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000814 QualType T = D->getInit()->getType();
Owen Andersona1cf15f2009-07-14 23:10:40 +0000815 Init = VMContext.getUndef(getTypes().ConvertType(T));
Eli Friedman6e656f42009-02-20 01:18:21 +0000816 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000817 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000818
Chris Lattner2d584062009-03-21 08:13:05 +0000819 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000820 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000821
Chris Lattner570585c2009-03-21 09:16:30 +0000822 // Strip off a bitcast if we got one back.
823 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +0000824 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
825 // all zero index gep.
826 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +0000827 Entry = CE->getOperand(0);
828 }
829
830 // Entry is now either a Function or GlobalVariable.
831 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
832
Chris Lattner570585c2009-03-21 09:16:30 +0000833 // We have a definition after a declaration with the wrong type.
834 // We must make a new GlobalVariable* and update everything that used OldGV
835 // (a declaration or tentative definition) with the new GlobalVariable*
836 // (which will be a definition).
837 //
838 // This happens if there is a prototype for a global (e.g.
839 // "extern int x[];") and then a definition of a different type (e.g.
840 // "int x[10];"). This also happens when an initializer has a different type
841 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +0000842 if (GV == 0 ||
843 GV->getType()->getElementType() != InitType ||
844 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
845
846 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
847 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000848
Chris Lattner570585c2009-03-21 09:16:30 +0000849 // Make a new global with the correct type, this is now guaranteed to work.
850 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000851 GV->takeName(cast<llvm::GlobalValue>(Entry));
852
Eli Friedman77ba7082008-05-30 19:50:47 +0000853 // Replace all uses of the old global with the new global
854 llvm::Constant *NewPtrForOldDecl =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000855 VMContext.getConstantExprBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +0000856 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000857
858 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +0000859 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000860 }
Devang Patel8e53e722007-10-26 16:31:40 +0000861
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000862 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000863 SourceManager &SM = Context.getSourceManager();
864 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000865 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000866 }
867
Chris Lattner88a69ad2007-07-13 05:13:43 +0000868 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000869 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000870 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000871
Chris Lattner88a69ad2007-07-13 05:13:43 +0000872 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000873 if (D->getStorageClass() == VarDecl::Static)
874 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000875 else if (D->hasAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000876 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000877 else if (D->hasAttr<DLLExportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000878 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000879 else if (D->hasAttr<WeakAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000880 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000881 else if (!CompileOpts.NoCommon &&
882 (!D->hasExternalStorage() && !D->getInit()))
883 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000884 else
Daniel Dunbar04d40782009-04-14 06:00:08 +0000885 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000886
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000887 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000888
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000889 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000890 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000891 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000892 DI->EmitGlobalVariable(GV, D);
893 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000894}
Reid Spencer5f016e22007-07-11 17:01:13 +0000895
Chris Lattnerbdb01322009-05-05 06:16:31 +0000896/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
897/// implement a function with no prototype, e.g. "int foo() {}". If there are
898/// existing call uses of the old function in the module, this adjusts them to
899/// call the new function directly.
900///
901/// This is not just a cleanup: the always_inline pass requires direct calls to
902/// functions to be able to inline them. If there is a bitcast in the way, it
903/// won't inline them. Instcombine normally deletes these calls, but it isn't
904/// run at -O0.
905static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
906 llvm::Function *NewFn) {
907 // If we're redefining a global as a function, don't transform it.
908 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
909 if (OldFn == 0) return;
910
911 const llvm::Type *NewRetTy = NewFn->getReturnType();
912 llvm::SmallVector<llvm::Value*, 4> ArgList;
913
914 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
915 UI != E; ) {
916 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Chris Lattner08c93a72009-06-04 16:47:43 +0000917 unsigned OpNo = UI.getOperandNo();
Chris Lattnerbdb01322009-05-05 06:16:31 +0000918 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
Chris Lattner08c93a72009-06-04 16:47:43 +0000919 if (!CI || OpNo != 0) continue;
Chris Lattnerbdb01322009-05-05 06:16:31 +0000920
921 // If the return types don't match exactly, and if the call isn't dead, then
922 // we can't transform this call.
923 if (CI->getType() != NewRetTy && !CI->use_empty())
924 continue;
925
926 // If the function was passed too few arguments, don't transform. If extra
927 // arguments were passed, we silently drop them. If any of the types
928 // mismatch, we don't transform.
929 unsigned ArgNo = 0;
930 bool DontTransform = false;
931 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
932 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
933 if (CI->getNumOperands()-1 == ArgNo ||
934 CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
935 DontTransform = true;
936 break;
937 }
938 }
939 if (DontTransform)
940 continue;
941
942 // Okay, we can transform this. Create the new call instruction and copy
943 // over the required information.
944 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
945 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
946 ArgList.end(), "", CI);
947 ArgList.clear();
948 if (NewCall->getType() != llvm::Type::VoidTy)
949 NewCall->takeName(CI);
950 NewCall->setCallingConv(CI->getCallingConv());
951 NewCall->setAttributes(CI->getAttributes());
952
953 // Finally, remove the old call, replacing any uses with the new one.
954 if (!CI->use_empty())
955 CI->replaceAllUsesWith(NewCall);
956 CI->eraseFromParent();
957 }
958}
959
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000960
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000961void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000962 const llvm::FunctionType *Ty;
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000963 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
964
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000965 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
966 bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
967
968 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
969 } else {
970 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
971
972 // As a special case, make sure that definitions of K&R function
973 // "type foo()" aren't declared as varargs (which forces the backend
974 // to do unnecessary work).
975 if (D->getType()->isFunctionNoProtoType()) {
976 assert(Ty->isVarArg() && "Didn't lower type as expected");
977 // Due to stret, the lowered function could have arguments.
978 // Just create the same type as was lowered by ConvertType
979 // but strip off the varargs bit.
980 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000981 Ty = VMContext.getFunctionType(Ty->getReturnType(), Args, false);
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000982 }
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000983 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000984
Chris Lattner9fa959d2009-05-12 20:58:15 +0000985 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000986 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000987
Chris Lattner0558e792009-03-21 09:25:43 +0000988 // Strip off a bitcast if we got one back.
989 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
990 assert(CE->getOpcode() == llvm::Instruction::BitCast);
991 Entry = CE->getOperand(0);
992 }
993
994
995 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +0000996 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
997
Daniel Dunbar42745812009-03-09 23:53:08 +0000998 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +0000999 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001000 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001001
Chris Lattner62b33ea2009-03-21 08:38:50 +00001002 // F is the Function* for the one with the wrong type, we must make a new
1003 // Function* and update everything that used F (a declaration) with the new
1004 // Function* (which will be a definition).
1005 //
1006 // This happens if there is a prototype for a function
1007 // (e.g. "int f()") and then a definition of a different type
1008 // (e.g. "int f(int x)"). Start by making a new function of the
1009 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +00001010 GlobalDeclMap.erase(getMangledName(D));
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001011 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Chris Lattnerbdb01322009-05-05 06:16:31 +00001012 NewFn->takeName(OldFn);
1013
1014 // If this is an implementation of a function without a prototype, try to
1015 // replace any existing uses of the function (which may be calls) with uses
1016 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001017 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001018 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001019 OldFn->removeDeadConstantUsers();
1020 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001021
1022 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001023 if (!Entry->use_empty()) {
1024 llvm::Constant *NewPtrForOldDecl =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001025 VMContext.getConstantExprBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001026 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1027 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001028
1029 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001030 OldFn->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +00001031
Chris Lattner0558e792009-03-21 09:25:43 +00001032 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001033 }
Chris Lattner0558e792009-03-21 09:25:43 +00001034
1035 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001036
Daniel Dunbar219df662008-09-08 23:44:31 +00001037 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001038
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001039 SetFunctionDefinitionAttributes(D, Fn);
1040 SetLLVMFunctionAttributesForDefinition(D, Fn);
Daniel Dunbar219df662008-09-08 23:44:31 +00001041
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001042 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001043 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001044 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001045 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001046}
1047
Chris Lattnerbd532712009-03-22 21:47:11 +00001048void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001049 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001050 assert(AA && "Not an alias?");
1051
1052 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1053
1054 // Unique the name through the identifier table.
1055 const char *AliaseeName = AA->getAliasee().c_str();
1056 AliaseeName = getContext().Idents.get(AliaseeName).getName();
1057
1058 // Create a reference to the named value. This ensures that it is emitted
1059 // if a deferred decl.
1060 llvm::Constant *Aliasee;
1061 if (isa<llvm::FunctionType>(DeclTy))
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001062 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
Chris Lattnerbd532712009-03-22 21:47:11 +00001063 else
1064 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001065 VMContext.getPointerTypeUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001066
1067 // Create the new alias itself, but don't set a name yet.
1068 llvm::GlobalValue *GA =
1069 new llvm::GlobalAlias(Aliasee->getType(),
1070 llvm::Function::ExternalLinkage,
1071 "", Aliasee, &getModule());
1072
1073 // See if there is already something with the alias' name in the module.
1074 const char *MangledName = getMangledName(D);
1075 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1076
1077 if (Entry && !Entry->isDeclaration()) {
1078 // If there is a definition in the module, then it wins over the alias.
1079 // This is dubious, but allow it to be safe. Just ignore the alias.
1080 GA->eraseFromParent();
1081 return;
1082 }
1083
1084 if (Entry) {
1085 // If there is a declaration in the module, then we had an extern followed
1086 // by the alias, as in:
1087 // extern int test6();
1088 // ...
1089 // int test6() __attribute__((alias("test7")));
1090 //
1091 // Remove it and replace uses of it with the alias.
1092
Owen Andersona1cf15f2009-07-14 23:10:40 +00001093 Entry->replaceAllUsesWith(VMContext.getConstantExprBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001094 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001095 Entry->eraseFromParent();
1096 }
1097
1098 // Now we know that there is no conflict, set the name.
1099 Entry = GA;
1100 GA->setName(MangledName);
1101
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001102 // Set attributes which are particular to an alias; this is a
1103 // specialization of the attributes which may be set on a global
1104 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001105 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001106 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1107 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001108 if (FD->getBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001109 GA->setLinkage(llvm::Function::DLLExportLinkage);
1110 } else {
1111 GA->setLinkage(llvm::Function::DLLExportLinkage);
1112 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001113 } else if (D->hasAttr<WeakAttr>() ||
1114 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001115 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1116 }
1117
1118 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001119}
1120
Chris Lattnerb808c952009-03-22 21:56:56 +00001121/// getBuiltinLibFunction - Given a builtin id for a function like
1122/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +00001123llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001124 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1125 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1126 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001127
Douglas Gregor3e41d602009-02-13 23:20:09 +00001128 // Get the name, skip over the __builtin_ prefix (if necessary).
1129 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1130 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1131 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001132
1133 // Get the type for the builtin.
Chris Lattner86df27b2009-06-14 00:45:47 +00001134 ASTContext::GetBuiltinTypeError Error;
1135 QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1136 assert(Error == ASTContext::GE_None && "Can't get builtin type");
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001137
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001138 const llvm::FunctionType *Ty =
1139 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1140
Chris Lattnerb808c952009-03-22 21:56:56 +00001141 // Unique the name through the identifier table.
1142 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001143 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001144 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001145}
1146
Chris Lattner7acda7c2007-12-18 00:25:38 +00001147llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1148 unsigned NumTys) {
1149 return llvm::Intrinsic::getDeclaration(&getModule(),
1150 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1151}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153llvm::Function *CodeGenModule::getMemCpyFn() {
1154 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001155 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1156 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001157}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001158
Eli Friedman0c995092008-05-26 12:59:39 +00001159llvm::Function *CodeGenModule::getMemMoveFn() {
1160 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001161 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1162 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +00001163}
1164
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001165llvm::Function *CodeGenModule::getMemSetFn() {
1166 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001167 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1168 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001169}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001170
Anders Carlssone3daa762008-11-15 18:54:24 +00001171static void appendFieldAndPadding(CodeGenModule &CGM,
1172 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001173 FieldDecl *FieldD, FieldDecl *NextFieldD,
1174 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001175 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001176 // Append the field.
1177 Fields.push_back(Field);
1178
Douglas Gregor44b43212008-12-11 16:49:14 +00001179 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001180
1181 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001182 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001183 NextStructFieldNo = STy->getNumElements();
1184 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001185 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001186 }
1187
1188 // Append padding
1189 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1190 llvm::Constant *C =
Owen Anderson69243822009-07-13 04:10:07 +00001191 CGM.getLLVMContext().getNullValue(STy->getElementType(StructFieldNo + 1));
Anders Carlssone3daa762008-11-15 18:54:24 +00001192
1193 Fields.push_back(C);
1194 }
1195}
1196
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001197llvm::Constant *CodeGenModule::
Steve Naroff8d4141f2009-04-01 13:55:36 +00001198GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroffb59212a2009-04-01 21:16:31 +00001199 std::string str;
Chris Lattner271474e2009-04-19 06:59:18 +00001200 unsigned StringLength = 0;
Steve Naroffb59212a2009-04-01 21:16:31 +00001201
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001202 bool isUTF16 = false;
1203 if (Literal->containsNonAsciiOrNull()) {
1204 // Convert from UTF-8 to UTF-16.
1205 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1206 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1207 UTF16 *ToPtr = &ToBuf[0];
1208
1209 ConversionResult Result;
1210 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1211 &ToPtr, ToPtr+Literal->getByteLength(),
1212 strictConversion);
Steve Naroffaa4a7562009-04-13 19:08:08 +00001213 if (Result == conversionOK) {
1214 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1215 // without doing more surgery to this routine. Since we aren't explicitly
1216 // checking for endianness here, it's also a bug (when generating code for
1217 // a target that doesn't match the host endianness). Modeling this as an
1218 // i16 array is likely the cleanest solution.
1219 StringLength = ToPtr-&ToBuf[0];
1220 str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1221 isUTF16 = true;
1222 } else if (Result == sourceIllegal) {
Steve Narofffd942622009-04-13 20:26:29 +00001223 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
Steve Naroffaa4a7562009-04-13 19:08:08 +00001224 str.assign(Literal->getStrData(), Literal->getByteLength());
1225 StringLength = str.length();
1226 } else
1227 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroffb59212a2009-04-01 21:16:31 +00001228
Steve Naroffb59212a2009-04-01 21:16:31 +00001229 } else {
1230 str.assign(Literal->getStrData(), Literal->getByteLength());
1231 StringLength = str.length();
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001232 }
Anders Carlssonc9e20912007-08-21 00:21:21 +00001233 llvm::StringMapEntry<llvm::Constant *> &Entry =
1234 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1235
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001236 if (llvm::Constant *C = Entry.getValue())
1237 return C;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001238
Owen Anderson69243822009-07-13 04:10:07 +00001239 llvm::Constant *Zero = getLLVMContext().getNullValue(llvm::Type::Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001240 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001241
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001242 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001243 if (!CFConstantStringClassRef) {
1244 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001245 Ty = VMContext.getArrayType(Ty, 0);
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001246 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1247 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001248 // Decay array -> ptr
1249 CFConstantStringClassRef =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001250 VMContext.getConstantExprGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001251 }
1252
Anders Carlssone3daa762008-11-15 18:54:24 +00001253 QualType CFTy = getContext().getCFConstantStringType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001254 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001255
Anders Carlssone3daa762008-11-15 18:54:24 +00001256 const llvm::StructType *STy =
1257 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1258
1259 std::vector<llvm::Constant*> Fields;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001260 RecordDecl::field_iterator Field = CFRD->field_begin();
Douglas Gregor44b43212008-12-11 16:49:14 +00001261
Anders Carlssonc9e20912007-08-21 00:21:21 +00001262 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001263 FieldDecl *CurField = *Field++;
1264 FieldDecl *NextField = *Field++;
1265 appendFieldAndPadding(*this, Fields, CurField, NextField,
1266 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001267
1268 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001269 CurField = NextField;
1270 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001271 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001272 appendFieldAndPadding(*this, Fields, CurField, NextField,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001273 isUTF16 ? VMContext.getConstantInt(Ty, 0x07d0)
1274 : VMContext.getConstantInt(Ty, 0x07C8),
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001275 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001276
1277 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001278 CurField = NextField;
1279 NextField = *Field++;
Owen Andersona1cf15f2009-07-14 23:10:40 +00001280 llvm::Constant *C = VMContext.getConstantArray(str);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001281
1282 const char *Sect, *Prefix;
1283 bool isConstant;
Chris Lattner95b851e2009-07-16 05:03:48 +00001284 llvm::GlobalValue::LinkageTypes Linkage;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001285 if (isUTF16) {
1286 Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1287 Sect = getContext().Target.getUnicodeStringSection();
Chris Lattner95b851e2009-07-16 05:03:48 +00001288 // FIXME: why do utf strings get "l" labels instead of "L" labels?
1289 Linkage = llvm::GlobalValue::InternalLinkage;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001290 // FIXME: Why does GCC not set constant here?
1291 isConstant = false;
1292 } else {
Chris Lattner95b851e2009-07-16 05:03:48 +00001293 Prefix = ".str";
Daniel Dunbara9668e02009-04-03 00:57:44 +00001294 Sect = getContext().Target.getCFStringDataSection();
Chris Lattner95b851e2009-07-16 05:03:48 +00001295 Linkage = llvm::GlobalValue::PrivateLinkage;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001296 // FIXME: -fwritable-strings should probably affect this, but we
1297 // are following gcc here.
1298 isConstant = true;
1299 }
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001300 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00001301 new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
Chris Lattner95b851e2009-07-16 05:03:48 +00001302 Linkage, C, Prefix);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001303 if (Sect)
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001304 GV->setSection(Sect);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001305 if (isUTF16) {
1306 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1307 GV->setAlignment(Align);
1308 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001309 appendFieldAndPadding(*this, Fields, CurField, NextField,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001310 VMContext.getConstantExprGetElementPtr(GV, Zeros, 2),
Anders Carlssone3daa762008-11-15 18:54:24 +00001311 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001312
1313 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001314 CurField = NextField;
1315 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001316 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001317 appendFieldAndPadding(*this, Fields, CurField, NextField,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001318 VMContext.getConstantInt(Ty, StringLength), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001319
1320 // The struct.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001321 C = VMContext.getConstantStruct(STy, Fields);
Owen Anderson1c431b32009-07-08 19:05:04 +00001322 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
Chris Lattner95b851e2009-07-16 05:03:48 +00001323 llvm::GlobalVariable::PrivateLinkage, C,
1324 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001325 if (const char *Sect = getContext().Target.getCFStringSection())
1326 GV->setSection(Sect);
Anders Carlsson0c678292007-11-01 00:41:52 +00001327 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001328
Anders Carlsson0c678292007-11-01 00:41:52 +00001329 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001330}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001331
Daniel Dunbar61432932008-08-13 23:20:05 +00001332/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001333/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001334std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001335 const char *StrData = E->getStrData();
1336 unsigned Len = E->getByteLength();
1337
1338 const ConstantArrayType *CAT =
1339 getContext().getAsConstantArrayType(E->getType());
1340 assert(CAT && "String isn't pointer or array!");
1341
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001342 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001343 std::string Str(StrData, StrData+Len);
1344 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001345
1346 if (E->isWide())
1347 RealLen *= getContext().Target.getWCharWidth()/8;
1348
Daniel Dunbar1e049762008-08-10 20:25:57 +00001349 Str.resize(RealLen, '\0');
1350
1351 return Str;
1352}
1353
Daniel Dunbar61432932008-08-13 23:20:05 +00001354/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1355/// constant array for the given string literal.
1356llvm::Constant *
1357CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1358 // FIXME: This can be more efficient.
1359 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1360}
1361
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001362/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1363/// array for the given ObjCEncodeExpr node.
1364llvm::Constant *
1365CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1366 std::string Str;
1367 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001368
1369 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001370}
1371
1372
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001373/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001374static llvm::Constant *GenerateStringLiteral(const std::string &str,
1375 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001376 CodeGenModule &CGM,
1377 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001378 // Create Constant for this string literal. Don't add a '\0'.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001379 llvm::Constant *C = CGM.getLLVMContext().getConstantArray(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001380
1381 // Create a global variable for this string
Owen Anderson1c431b32009-07-08 19:05:04 +00001382 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
Chris Lattner95b851e2009-07-16 05:03:48 +00001383 llvm::GlobalValue::PrivateLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00001384 C, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001385}
1386
Daniel Dunbar61432932008-08-13 23:20:05 +00001387/// GetAddrOfConstantString - Returns a pointer to a character array
1388/// containing the literal. This contents are exactly that of the
1389/// given string, i.e. it will not be null terminated automatically;
1390/// see GetAddrOfConstantCString. Note that whether the result is
1391/// actually a pointer to an LLVM constant depends on
1392/// Feature.WriteableStrings.
1393///
1394/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001395llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1396 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001397 bool IsConstant = !Features.WritableStrings;
1398
1399 // Get the default prefix if a name wasn't specified.
1400 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001401 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001402
1403 // Don't share any string literals if strings aren't constant.
1404 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001405 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001406
1407 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner95b851e2009-07-16 05:03:48 +00001408 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001409
1410 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001411 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001412
1413 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001414 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001415 Entry.setValue(C);
1416 return C;
1417}
Daniel Dunbar61432932008-08-13 23:20:05 +00001418
1419/// GetAddrOfConstantCString - Returns a pointer to a character
1420/// array containing the literal and a terminating '\-'
1421/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001422llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1423 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001424 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001425}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001426
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001427/// EmitObjCPropertyImplementations - Emit information for synthesized
1428/// properties for an implementation.
1429void CodeGenModule::EmitObjCPropertyImplementations(const
1430 ObjCImplementationDecl *D) {
Douglas Gregor653f1b12009-04-23 01:02:12 +00001431 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001432 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001433 ObjCPropertyImplDecl *PID = *i;
1434
1435 // Dynamic is just for type-checking.
1436 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1437 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1438
1439 // Determine which methods need to be implemented, some may have
1440 // been overridden. Note that ::isSynthesized is not the method
1441 // we want, that just indicates if the decl came from a
1442 // property. What we want to know is if the method is defined in
1443 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001444 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001445 CodeGenFunction(*this).GenerateObjCGetter(
1446 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001447 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001448 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001449 CodeGenFunction(*this).GenerateObjCSetter(
1450 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001451 }
1452 }
1453}
1454
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001455/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001456void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001457 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00001458 I != E; ++I)
1459 EmitTopLevelDecl(*I);
1460}
1461
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001462// EmitLinkageSpec - Emit all declarations in a linkage spec.
1463void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1464 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1465 ErrorUnsupported(LSD, "linkage spec");
1466 return;
1467 }
1468
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001469 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001470 I != E; ++I)
1471 EmitTopLevelDecl(*I);
1472}
1473
Daniel Dunbar41071de2008-08-15 23:26:23 +00001474/// EmitTopLevelDecl - Emit code for a single top level declaration.
1475void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1476 // If an error has occurred, stop code generation, but continue
1477 // parsing and semantic analysis (to ensure all warnings and errors
1478 // are emitted).
1479 if (Diags.hasErrorOccurred())
1480 return;
1481
Douglas Gregor16e8be22009-06-29 17:30:29 +00001482 // Ignore dependent declarations.
1483 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1484 return;
1485
Daniel Dunbar41071de2008-08-15 23:26:23 +00001486 switch (D->getKind()) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001487 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001488 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00001489 // Skip function templates
1490 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1491 return;
1492
1493 // Fall through
1494
Daniel Dunbar41071de2008-08-15 23:26:23 +00001495 case Decl::Var:
Anders Carlsson2a131fb2009-05-05 04:44:02 +00001496 EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001497 break;
1498
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001499 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001500 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001501 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001502 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001503 // No code generation needed.
1504 case Decl::Using:
Douglas Gregor127102b2009-06-29 20:59:39 +00001505 case Decl::ClassTemplate:
1506 case Decl::FunctionTemplate:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001507 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001508 case Decl::CXXConstructor:
1509 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1510 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00001511 case Decl::CXXDestructor:
1512 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1513 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00001514
1515 case Decl::StaticAssert:
1516 // Nothing to do.
1517 break;
1518
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001519 // Objective-C Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001520
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001521 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001522 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001523 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001524 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00001525 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00001526 break;
1527
Daniel Dunbar41071de2008-08-15 23:26:23 +00001528 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001529 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001530 break;
1531
1532 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001533 // Categories have properties but don't support synthesize so we
1534 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001535 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1536 break;
1537
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001538 case Decl::ObjCImplementation: {
1539 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1540 EmitObjCPropertyImplementations(OMD);
1541 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001542 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001543 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001544 case Decl::ObjCMethod: {
1545 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1546 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001547 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00001548 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1549 break;
1550 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001551 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001552 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001553 break;
1554
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001555 case Decl::LinkageSpec:
1556 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001557 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001558
1559 case Decl::FileScopeAsm: {
1560 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1561 std::string AsmString(AD->getAsmString()->getStrData(),
1562 AD->getAsmString()->getByteLength());
1563
1564 const std::string &S = getModule().getModuleInlineAsm();
1565 if (S.empty())
1566 getModule().setModuleInlineAsm(AsmString);
1567 else
1568 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1569 break;
1570 }
1571
1572 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00001573 // Make sure we handled everything we should, every other kind is a
1574 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
1575 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001576 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1577 }
1578}