blob: df4a3d07636d193098ff6232a6b03c62f616e8b5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Anders Carlsson1f1cd392009-02-12 17:55:02 +000039 CFConstantStringClassRef(0), NSConcreteGlobalBlock(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000040
41 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000042 if (Features.NeXTRuntime) {
Fariborz Jahaniand0374812009-01-22 23:02:58 +000043 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanian48543f52009-01-21 22:04:16 +000044 : CreateMacObjCRuntime(*this);
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000045 } else {
46 Runtime = CreateGNUObjCRuntime(*this);
47 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000048 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000060 EmitStatics();
Daniel Dunbar566a6502008-09-08 23:44:31 +000061 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000062 if (Runtime)
63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000065 EmitCtorList(GlobalCtors, "llvm.global_ctors");
66 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000067 EmitAnnotations();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000068 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000069}
Chris Lattner4b009652007-07-25 00:24:17 +000070
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000071void CodeGenModule::BindRuntimeFunctions() {
72 // Deal with protecting runtime function names.
73 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
74 llvm::Function *Fn = RuntimeFunctions[i].first;
75 const std::string &Name = RuntimeFunctions[i].second;
76
Daniel Dunbarfc1543e2008-11-19 06:15:35 +000077 // Discard unused runtime functions.
78 if (Fn->use_empty()) {
79 Fn->eraseFromParent();
80 continue;
81 }
82
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000083 // See if there is a conflict against a function.
84 llvm::Function *Conflict = TheModule.getFunction(Name);
85 if (Conflict) {
86 // Decide which version to take. If the conflict is a definition
87 // we are forced to take that, otherwise assume the runtime
88 // knows best.
89 if (!Conflict->isDeclaration()) {
90 llvm::Value *Casted =
91 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
92 Fn->replaceAllUsesWith(Casted);
93 Fn->eraseFromParent();
94 } else {
95 Fn->takeName(Conflict);
96 llvm::Value *Casted =
97 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
98 Conflict->replaceAllUsesWith(Casted);
99 Conflict->eraseFromParent();
100 }
101 } else {
102 // FIXME: There still may be conflicts with aliases and
103 // variables.
104 Fn->setName(Name);
105 }
106 }
107}
108
Daniel Dunbar9503b782008-08-16 00:56:44 +0000109/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000110/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000111void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
112 bool OmitOnError) {
113 if (OmitOnError && getDiags().hasErrorOccurred())
114 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000115 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000116 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000117 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000118 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
119 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000120}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000121
Daniel Dunbar9503b782008-08-16 00:56:44 +0000122/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000123/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000124void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
125 bool OmitOnError) {
126 if (OmitOnError && getDiags().hasErrorOccurred())
127 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000128 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000129 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +0000130 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000131 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000132}
133
Daniel Dunbar27250d32008-08-15 23:26:23 +0000134/// setGlobalVisibility - Set the visibility for the given LLVM
135/// GlobalValue according to the given clang AST visibility value.
136static void setGlobalVisibility(llvm::GlobalValue *GV,
137 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000138 switch (Vis) {
139 default: assert(0 && "Unknown visibility!");
140 case VisibilityAttr::DefaultVisibility:
141 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
142 break;
143 case VisibilityAttr::HiddenVisibility:
144 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
145 break;
146 case VisibilityAttr::ProtectedVisibility:
147 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
148 break;
149 }
150}
151
Douglas Gregor3556bc72009-02-13 00:10:09 +0000152/// \brief Retrieves the mangled name for the given declaration.
153///
154/// If the given declaration requires a mangled name, returns an
155/// IdentifierInfo* containing the mangled name. Otherwise, returns
156/// the name of the declaration as an identifier.
157///
158/// FIXME: Returning an IdentifierInfo* here is a total hack. We
159/// really need some kind of string abstraction that either stores a
160/// mangled name or stores an IdentifierInfo*. This will require
161/// changes to the GlobalDeclMap, too.
162///
163/// FIXME: Performance here is going to be terribly until we start
164/// caching mangled names. However, we should fix the problem above
165/// first.
166IdentifierInfo *CodeGenModule::getMangledName(const NamedDecl *ND) const {
167 std::string Name;
168 llvm::raw_string_ostream Out(Name);
169 if (!mangleName(ND, Context, Out))
170 return ND->getIdentifier();
171
172 return &Context.Idents.get(Out.str());
173}
174
Chris Lattner753d2592008-03-14 17:18:18 +0000175/// AddGlobalCtor - Add a function to the list that will be called before
176/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000177void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000178 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000179 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000180}
181
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000182/// AddGlobalDtor - Add a function to the list that will be called
183/// when the module is unloaded.
184void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000185 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000186 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
187}
188
189void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
190 // Ctor function type is void()*.
191 llvm::FunctionType* CtorFTy =
192 llvm::FunctionType::get(llvm::Type::VoidTy,
193 std::vector<const llvm::Type*>(),
194 false);
195 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
196
197 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000198 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000199 llvm::StructType::get(llvm::Type::Int32Ty,
200 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000201
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000202 // Construct the constructor and destructor arrays.
203 std::vector<llvm::Constant*> Ctors;
204 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
205 std::vector<llvm::Constant*> S;
206 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
207 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
208 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000209 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000210
211 if (!Ctors.empty()) {
212 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
213 new llvm::GlobalVariable(AT, false,
214 llvm::GlobalValue::AppendingLinkage,
215 llvm::ConstantArray::get(AT, Ctors),
216 GlobalName,
217 &TheModule);
218 }
Chris Lattner753d2592008-03-14 17:18:18 +0000219}
220
Nate Begeman52da5c72008-04-18 23:43:57 +0000221void CodeGenModule::EmitAnnotations() {
222 if (Annotations.empty())
223 return;
224
225 // Create a new global variable for the ConstantStruct in the Module.
226 llvm::Constant *Array =
227 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
228 Annotations.size()),
229 Annotations);
230 llvm::GlobalValue *gv =
231 new llvm::GlobalVariable(Array->getType(), false,
232 llvm::GlobalValue::AppendingLinkage, Array,
233 "llvm.global.annotations", &TheModule);
234 gv->setSection("llvm.metadata");
235}
236
Daniel Dunbara8f02052008-09-08 21:33:45 +0000237static void SetGlobalValueAttributes(const Decl *D,
238 bool IsInternal,
239 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000240 llvm::GlobalValue *GV,
241 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000242 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000243 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000244 if (!ForDefinition) {
245 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000246 if (D->getAttr<DLLImportAttr>()) {
247 // The dllimport attribute is overridden by a subsequent declaration as
248 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000249 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000250 // dllimport attribute can be applied only to function decls, not to
251 // definitions.
252 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
253 if (!FD->getBody())
254 GV->setLinkage(llvm::Function::DLLImportLinkage);
255 } else
256 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000257 }
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000258 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000259 } else {
260 if (IsInternal) {
261 GV->setLinkage(llvm::Function::InternalLinkage);
262 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000263 if (D->getAttr<DLLExportAttr>()) {
264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // The dllexport attribute is ignored for undefined symbols.
266 if (FD->getBody())
267 GV->setLinkage(llvm::Function::DLLExportLinkage);
268 } else
269 GV->setLinkage(llvm::Function::DLLExportLinkage);
270 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar566a6502008-09-08 23:44:31 +0000271 GV->setLinkage(llvm::Function::WeakLinkage);
272 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000273 }
Nuno Lopes78534382008-06-08 15:45:52 +0000274
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000275 // FIXME: Figure out the relative priority of the attribute,
276 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000277 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000278 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000279 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000280
Daniel Dunbara8f02052008-09-08 21:33:45 +0000281 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000282 // Prefaced with special LLVM marker to indicate that the name
283 // should not be munged.
284 GV->setName("\01" + ALA->getLabel());
285 }
Daniel Dunbar97509722009-02-12 17:28:23 +0000286
287 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
288 GV->setSection(SA->getName());
Nuno Lopes78534382008-06-08 15:45:52 +0000289}
290
Devang Patela85a9ef2008-09-25 21:02:23 +0000291void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000292 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000293 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000294 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000295 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000296
Devang Patela85a9ef2008-09-25 21:02:23 +0000297 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
298 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000299
300 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000301 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000302 F->setCallingConv(llvm::CallingConv::X86_FastCall);
303
304 if (D->getAttr<StdCallAttr>())
305 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000306}
307
308/// SetFunctionAttributesForDefinition - Set function attributes
309/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000310void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
311 llvm::Function *F) {
312 if (isa<ObjCMethodDecl>(D)) {
313 SetGlobalValueAttributes(D, true, false, F, true);
314 } else {
315 const FunctionDecl *FD = cast<FunctionDecl>(D);
316 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
317 FD->isInline(), F, true);
318 }
319
Daniel Dunbarf2787002008-09-04 23:41:35 +0000320 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000321 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000322
323 if (D->getAttr<AlwaysInlineAttr>())
324 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000325}
326
327void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
328 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000329 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000330
Daniel Dunbar566a6502008-09-08 23:44:31 +0000331 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000332}
333
334void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
335 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000336 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000337
Daniel Dunbar566a6502008-09-08 23:44:31 +0000338 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
339 FD->isInline(), F, false);
340}
341
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000342
Daniel Dunbar566a6502008-09-08 23:44:31 +0000343void CodeGenModule::EmitAliases() {
344 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
345 const FunctionDecl *D = Aliases[i];
346 const AliasAttr *AA = D->getAttr<AliasAttr>();
347
348 // This is something of a hack, if the FunctionDecl got overridden
349 // then its attributes will be moved to the new declaration. In
350 // this case the current decl has no alias attribute, but we will
351 // eventually see it.
352 if (!AA)
353 continue;
354
355 const std::string& aliaseeName = AA->getAliasee();
356 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
357 if (!aliasee) {
358 // FIXME: This isn't unsupported, this is just an error, which
359 // sema should catch, but...
360 ErrorUnsupported(D, "alias referencing a missing function");
361 continue;
362 }
363
364 llvm::GlobalValue *GA =
365 new llvm::GlobalAlias(aliasee->getType(),
366 llvm::Function::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000367 getMangledName(D)->getName(), aliasee,
368 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000369
Douglas Gregor3556bc72009-02-13 00:10:09 +0000370 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000371 if (Entry) {
372 // If we created a dummy function for this then replace it.
373 GA->takeName(Entry);
374
375 llvm::Value *Casted =
376 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
377 Entry->replaceAllUsesWith(Casted);
378 Entry->eraseFromParent();
379
380 Entry = GA;
381 }
382
383 // Alias should never be internal or inline.
384 SetGlobalValueAttributes(D, false, false, GA, true);
385 }
Eli Friedman9be42212008-06-01 15:54:49 +0000386}
387
Nate Begemanad320b62008-04-20 06:29:50 +0000388void CodeGenModule::EmitStatics() {
389 // Emit code for each used static decl encountered. Since a previously unused
390 // static decl may become used during the generation of code for a static
391 // function, iterate until no changes are made.
392 bool Changed;
393 do {
394 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000395
396 for (std::list<const ValueDecl*>::iterator i = StaticDecls.begin(),
397 e = StaticDecls.end(); i != e; ) {
398 const ValueDecl *D = *i;
399
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000400 // Check if we have used a decl with the same name
401 // FIXME: The AST should have some sort of aggregate decls or
402 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000403 // FIXME: This is missing some important cases. For example, we
404 // need to check for uses in an alias and in a constructor.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000405 if (!GlobalDeclMap.count(getMangledName(D))) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000406 i++;
Daniel Dunbarced89142008-08-06 00:03:29 +0000407 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000408 }
409
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000410 // Emit the definition.
411 EmitGlobalDefinition(D);
412
Nate Begemanad320b62008-04-20 06:29:50 +0000413 // Erase the used decl from the list.
Anders Carlsson2e427d52009-01-04 02:08:04 +0000414 i = StaticDecls.erase(i);
415
Nate Begemanad320b62008-04-20 06:29:50 +0000416 // Remember that we made a change.
417 Changed = true;
418 }
419 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000420}
421
Nate Begeman8a704172008-04-19 04:17:09 +0000422/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
423/// annotation information for a given GlobalValue. The annotation struct is
424/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000425/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000426/// created from the AnnotateAttr's annotation. The third field is a constant
427/// string containing the name of the translation unit. The fourth field is
428/// the line number in the file of the annotated value declaration.
429///
430/// FIXME: this does not unique the annotation string constants, as llvm-gcc
431/// appears to.
432///
433llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
434 const AnnotateAttr *AA,
435 unsigned LineNo) {
436 llvm::Module *M = &getModule();
437
438 // get [N x i8] constants for the annotation string, and the filename string
439 // which are the 2nd and 3rd elements of the global annotation structure.
440 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
441 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
442 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
443 true);
444
445 // Get the two global values corresponding to the ConstantArrays we just
446 // created to hold the bytes of the strings.
447 llvm::GlobalValue *annoGV =
448 new llvm::GlobalVariable(anno->getType(), false,
449 llvm::GlobalValue::InternalLinkage, anno,
450 GV->getName() + ".str", M);
451 // translation unit name string, emitted into the llvm.metadata section.
452 llvm::GlobalValue *unitGV =
453 new llvm::GlobalVariable(unit->getType(), false,
454 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
455
456 // Create the ConstantStruct that is the global annotion.
457 llvm::Constant *Fields[4] = {
458 llvm::ConstantExpr::getBitCast(GV, SBP),
459 llvm::ConstantExpr::getBitCast(annoGV, SBP),
460 llvm::ConstantExpr::getBitCast(unitGV, SBP),
461 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
462 };
463 return llvm::ConstantStruct::get(Fields, 4, false);
464}
465
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000466void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
467 bool isDef, isStatic;
468
469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000470 // Aliases are deferred until code for everything else has been
471 // emitted.
472 if (FD->getAttr<AliasAttr>()) {
473 assert(!FD->isThisDeclarationADefinition() &&
474 "Function alias cannot have a definition!");
475 Aliases.push_back(FD);
476 return;
477 }
478
479 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000480 isStatic = FD->getStorageClass() == FunctionDecl::Static;
481 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
482 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
483
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000484 isDef = !((VD->getStorageClass() == VarDecl::Extern ||
485 VD->getStorageClass() == VarDecl::PrivateExtern) &&
486 VD->getInit() == 0);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000487 isStatic = VD->getStorageClass() == VarDecl::Static;
488 } else {
489 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000490 return;
491 }
492
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000493 // Forward declarations are emitted lazily on first use.
494 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000495 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000496
497 // If the global is a static, defer code generation until later so
498 // we can easily omit unused statics.
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000499 if (isStatic && !Features.EmitAllDecls) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000500 StaticDecls.push_back(Global);
501 return;
502 }
503
504 // Otherwise emit the definition.
505 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000506}
507
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000508void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
509 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
510 EmitGlobalFunctionDefinition(FD);
511 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
512 EmitGlobalVarDefinition(VD);
513 } else {
514 assert(0 && "Invalid argument to EmitGlobalDefinition()");
515 }
516}
517
Daniel Dunbar2188c532008-07-30 16:32:24 +0000518 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000519 assert(D->hasGlobalStorage() && "Not a global variable");
520
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000521 QualType ASTTy = D->getType();
522 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000523 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000524
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000525 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000526 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000527 if (!Entry) {
528 llvm::GlobalVariable *GV =
529 new llvm::GlobalVariable(Ty, false,
530 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000531 0, getMangledName(D)->getName(), &getModule(),
532 0, ASTTy.getAddressSpace());
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000533 Entry = GV;
534
535 // Handle things which are present even on external declarations.
536
537 // FIXME: This code is overly simple and should be merged with
538 // other global handling.
539
540 GV->setConstant(D->getType().isConstant(Context));
541
542 if (D->getStorageClass() == VarDecl::PrivateExtern)
543 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
544 }
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000545
Daniel Dunbar2188c532008-07-30 16:32:24 +0000546 // Make sure the result is of the correct type.
547 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000548}
549
550void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000551 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000552 QualType ASTTy = D->getType();
553 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000554
Chris Lattner4b009652007-07-25 00:24:17 +0000555 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000556 // This is a tentative definition; tentative definitions are
557 // implicitly initialized with { 0 }
558 const llvm::Type* InitTy;
559 if (ASTTy->isIncompleteArrayType()) {
560 // An incomplete array is normally [ TYPE x 0 ], but we need
561 // to fix it to [ TYPE x 1 ].
562 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
563 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
564 } else {
565 InitTy = VarTy;
566 }
567 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000568 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000569 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000570 }
571 const llvm::Type* InitType = Init->getType();
572
Douglas Gregor3556bc72009-02-13 00:10:09 +0000573 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000574 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
575
Eli Friedman43a0ce82008-05-30 19:50:47 +0000576 if (!GV) {
577 GV = new llvm::GlobalVariable(InitType, false,
578 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000579 0, getMangledName(D)->getName(),
580 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000581 } else if (GV->getType() !=
582 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000583 // We have a definition after a prototype with the wrong type.
584 // We must make a new GlobalVariable* and update everything that used OldGV
585 // (a declaration or tentative definition) with the new GlobalVariable*
586 // (which will be a definition).
587 //
588 // This happens if there is a prototype for a global (e.g. "extern int x[];")
589 // and then a definition of a different type (e.g. "int x[10];"). This also
590 // happens when an initializer has a different type from the type of the
591 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000592 //
593 // FIXME: This also ends up happening if there's a definition followed by
594 // a tentative definition! (Although Sema rejects that construct
595 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000596
597 // Save the old global
598 llvm::GlobalVariable *OldGV = GV;
599
600 // Make a new global with the correct type
601 GV = new llvm::GlobalVariable(InitType, false,
602 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000603 0, getMangledName(D)->getName(),
604 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000605 // Steal the name of the old global
606 GV->takeName(OldGV);
607
608 // Replace all uses of the old global with the new global
609 llvm::Constant *NewPtrForOldDecl =
610 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
611 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000612
613 // Erase the old global, since it is no longer used.
614 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000615 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000616
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000617 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000618
Nate Begeman8a704172008-04-19 04:17:09 +0000619 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
620 SourceManager &SM = Context.getSourceManager();
621 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000622 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000623 }
624
Chris Lattner4b009652007-07-25 00:24:17 +0000625 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000626 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000627
Eli Friedman7008e9a2008-05-30 20:39:54 +0000628 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
629 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000630 if (const IncompleteArrayType* IAT =
631 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000632 Align = Context.getTypeAlign(IAT->getElementType());
633 else
634 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000635 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
636 Align = std::max(Align, AA->getAlignment());
637 }
638 GV->setAlignment(Align / 8);
639
Chris Lattner402b3372008-03-03 03:28:21 +0000640 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000641 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000642 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000643
644 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
645 // Prefaced with special LLVM marker to indicate that the name
646 // should not be munged.
647 GV->setName("\01" + ALA->getLabel());
648 }
Chris Lattner4b009652007-07-25 00:24:17 +0000649
650 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000651 if (D->getStorageClass() == VarDecl::Static)
652 GV->setLinkage(llvm::Function::InternalLinkage);
653 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000654 GV->setLinkage(llvm::Function::DLLImportLinkage);
655 else if (D->getAttr<DLLExportAttr>())
656 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000657 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000658 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000659 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000660 // FIXME: This isn't right. This should handle common linkage and other
661 // stuff.
662 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000663 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000664 case VarDecl::Auto:
665 case VarDecl::Register:
666 assert(0 && "Can't have auto or register globals");
667 case VarDecl::None:
668 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000669 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000670 else
671 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000672 break;
673 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000674 // FIXME: common
675 break;
676
Chris Lattner402b3372008-03-03 03:28:21 +0000677 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000678 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
679 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000680 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000681 }
Chris Lattner4b009652007-07-25 00:24:17 +0000682 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000683
Daniel Dunbar97509722009-02-12 17:28:23 +0000684 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
685 GV->setSection(SA->getName());
686
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000687 // Emit global variable debug information.
688 CGDebugInfo *DI = getDebugInfo();
689 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000690 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000691 DI->EmitGlobalVariable(GV, D);
692 }
Chris Lattner4b009652007-07-25 00:24:17 +0000693}
694
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000695llvm::GlobalValue *
696CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000697 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
698 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
699 llvm::Function::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000700 getMangledName(D)->getName(),
701 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000702 SetFunctionAttributes(D, F);
703 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000704}
705
706llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000707 QualType ASTTy = D->getType();
708 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
709 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000710
711 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000712 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000713 if (!Entry)
714 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000715
Daniel Dunbar2188c532008-07-30 16:32:24 +0000716 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000717}
718
719void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Douglas Gregor3556bc72009-02-13 00:10:09 +0000720 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000721 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000722 Entry = EmitForwardFunctionDefinition(D);
723 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000724 // If the types mismatch then we have to rewrite the definition.
725 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
726 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000727 // Otherwise, we have a definition after a prototype with the wrong type.
728 // F is the Function* for the one with the wrong type, we must make a new
729 // Function* and update everything that used F (a declaration) with the new
730 // Function* (which will be a definition).
731 //
732 // This happens if there is a prototype for a function (e.g. "int f()") and
733 // then a definition of a different type (e.g. "int f(int x)"). Start by
734 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000735 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
736 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000737
738 // Replace uses of F with the Function we will endow with a body.
739 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000740 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
741 Entry->replaceAllUsesWith(NewPtrForOldDecl);
742
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000743 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000744 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000745 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000746
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000747 Entry = NewFn;
748 }
749 }
750
Daniel Dunbar566a6502008-09-08 23:44:31 +0000751 llvm::Function *Fn = cast<llvm::Function>(Entry);
752 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000753
Daniel Dunbar566a6502008-09-08 23:44:31 +0000754 SetFunctionAttributesForDefinition(D, Fn);
755
756 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
757 AddGlobalCtor(Fn, CA->getPriority());
758 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
759 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000760 }
761}
762
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000763llvm::Function *
764CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
765 const std::string &Name) {
766 llvm::Function *Fn = llvm::Function::Create(FTy,
767 llvm::Function::ExternalLinkage,
768 "", &TheModule);
769 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
770 return Fn;
771}
772
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000773void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
774 // Make sure that this type is translated.
775 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000776}
777
778
Chris Lattnerab862cc2007-08-31 04:31:45 +0000779/// getBuiltinLibFunction
780llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000781 if (BuiltinID > BuiltinFunctions.size())
782 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000783
Chris Lattner9f2d6892007-12-13 00:38:03 +0000784 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
785 // a slot for it.
786 assert(BuiltinID && "Invalid Builtin ID");
787 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000788 if (FunctionSlot)
789 return FunctionSlot;
790
791 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
792
793 // Get the name, skip over the __builtin_ prefix.
794 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
795
796 // Get the type for the builtin.
797 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
798 const llvm::FunctionType *Ty =
799 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
800
801 // FIXME: This has a serious problem with code like this:
802 // void abs() {}
803 // ... __builtin_abs(x);
804 // The two versions of abs will collide. The fix is for the builtin to win,
805 // and for the existing one to be turned into a constantexpr cast of the
806 // builtin. In the case where the existing one is a static function, it
807 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000808 if (llvm::Function *Existing = getModule().getFunction(Name)) {
809 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
810 return FunctionSlot = Existing;
811 assert(Existing == 0 && "FIXME: Name collision");
812 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000813
814 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000815 return FunctionSlot =
816 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
817 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000818}
819
Chris Lattner4b23f942007-12-18 00:25:38 +0000820llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
821 unsigned NumTys) {
822 return llvm::Intrinsic::getDeclaration(&getModule(),
823 (llvm::Intrinsic::ID)IID, Tys, NumTys);
824}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000825
Chris Lattner4b009652007-07-25 00:24:17 +0000826llvm::Function *CodeGenModule::getMemCpyFn() {
827 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000828 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
829 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000830}
Anders Carlsson36a04872007-08-21 00:21:21 +0000831
Eli Friedman8f08a252008-05-26 12:59:39 +0000832llvm::Function *CodeGenModule::getMemMoveFn() {
833 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000834 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
835 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000836}
837
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000838llvm::Function *CodeGenModule::getMemSetFn() {
839 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000840 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
841 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000842}
Chris Lattner4b23f942007-12-18 00:25:38 +0000843
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000844static void appendFieldAndPadding(CodeGenModule &CGM,
845 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000846 FieldDecl *FieldD, FieldDecl *NextFieldD,
847 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000848 RecordDecl* RD, const llvm::StructType *STy)
849{
850 // Append the field.
851 Fields.push_back(Field);
852
Douglas Gregor8acb7272008-12-11 16:49:14 +0000853 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000854
855 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000856 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000857 NextStructFieldNo = STy->getNumElements();
858 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000859 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000860 }
861
862 // Append padding
863 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
864 llvm::Constant *C =
865 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
866
867 Fields.push_back(C);
868 }
869}
870
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000871// We still need to work out the details of handling UTF-16.
872// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000873llvm::Constant *CodeGenModule::
874GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000875 llvm::StringMapEntry<llvm::Constant *> &Entry =
876 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
877
878 if (Entry.getValue())
879 return Entry.getValue();
880
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000881 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
882 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000883
884 if (!CFConstantStringClassRef) {
885 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
886 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000887
888 // FIXME: This is fairly broken if
889 // __CFConstantStringClassReference is already defined, in that it
890 // will get renamed and the user will most likely see an opaque
891 // error message. This is a general issue with relying on
892 // particular names.
893 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000894 new llvm::GlobalVariable(Ty, false,
895 llvm::GlobalVariable::ExternalLinkage, 0,
896 "__CFConstantStringClassReference",
897 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000898
899 // Decay array -> ptr
900 CFConstantStringClassRef =
901 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000902 }
903
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000904 QualType CFTy = getContext().getCFConstantStringType();
905 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000906
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000907 const llvm::StructType *STy =
908 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
909
910 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000911 RecordDecl::field_iterator Field = CFRD->field_begin();
912
Anders Carlsson36a04872007-08-21 00:21:21 +0000913 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000914 FieldDecl *CurField = *Field++;
915 FieldDecl *NextField = *Field++;
916 appendFieldAndPadding(*this, Fields, CurField, NextField,
917 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000918
919 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000920 CurField = NextField;
921 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000922 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000923 appendFieldAndPadding(*this, Fields, CurField, NextField,
924 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000925
926 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000927 CurField = NextField;
928 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000929 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000930 C = new llvm::GlobalVariable(C->getType(), true,
931 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000932 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000933 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000934 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
935 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000936
937 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000938 CurField = NextField;
939 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +0000940 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000941 appendFieldAndPadding(*this, Fields, CurField, NextField,
942 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000943
944 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000945 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000946 llvm::GlobalVariable *GV =
947 new llvm::GlobalVariable(C->getType(), true,
948 llvm::GlobalVariable::InternalLinkage,
949 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000950
Anders Carlsson9be009e2007-11-01 00:41:52 +0000951 GV->setSection("__DATA,__cfstring");
952 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000953
Anders Carlsson9be009e2007-11-01 00:41:52 +0000954 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000955}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000956
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000957/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000958/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000959std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000960 if (E->isWide()) {
961 ErrorUnsupported(E, "wide string");
962 return "FIXME";
963 }
964
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000965 const char *StrData = E->getStrData();
966 unsigned Len = E->getByteLength();
967
968 const ConstantArrayType *CAT =
969 getContext().getAsConstantArrayType(E->getType());
970 assert(CAT && "String isn't pointer or array!");
971
972 // Resize the string to the right size
973 // FIXME: What about wchar_t strings?
974 std::string Str(StrData, StrData+Len);
975 uint64_t RealLen = CAT->getSize().getZExtValue();
976 Str.resize(RealLen, '\0');
977
978 return Str;
979}
980
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000981/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
982/// constant array for the given string literal.
983llvm::Constant *
984CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
985 // FIXME: This can be more efficient.
986 return GetAddrOfConstantString(GetStringForStringLiteral(S));
987}
988
Chris Lattnera6dcce32008-02-11 00:02:17 +0000989/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000990static llvm::Constant *GenerateStringLiteral(const std::string &str,
991 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000992 CodeGenModule &CGM,
993 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000994 // Create Constant for this string literal. Don't add a '\0'.
995 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000996
997 // Create a global variable for this string
998 C = new llvm::GlobalVariable(C->getType(), constant,
999 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001000 C,
1001 GlobalName ? GlobalName : ".str",
1002 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001003
Chris Lattnerdb6be562007-11-28 05:34:05 +00001004 return C;
1005}
1006
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001007/// GetAddrOfConstantString - Returns a pointer to a character array
1008/// containing the literal. This contents are exactly that of the
1009/// given string, i.e. it will not be null terminated automatically;
1010/// see GetAddrOfConstantCString. Note that whether the result is
1011/// actually a pointer to an LLVM constant depends on
1012/// Feature.WriteableStrings.
1013///
1014/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001015llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1016 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001017 // Don't share any string literals if writable-strings is turned on.
1018 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001019 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001020
1021 llvm::StringMapEntry<llvm::Constant *> &Entry =
1022 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1023
1024 if (Entry.getValue())
1025 return Entry.getValue();
1026
1027 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001028 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001029 Entry.setValue(C);
1030 return C;
1031}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001032
1033/// GetAddrOfConstantCString - Returns a pointer to a character
1034/// array containing the literal and a terminating '\-'
1035/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001036llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1037 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001038 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001039}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001040
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001041/// EmitObjCPropertyImplementations - Emit information for synthesized
1042/// properties for an implementation.
1043void CodeGenModule::EmitObjCPropertyImplementations(const
1044 ObjCImplementationDecl *D) {
1045 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1046 e = D->propimpl_end(); i != e; ++i) {
1047 ObjCPropertyImplDecl *PID = *i;
1048
1049 // Dynamic is just for type-checking.
1050 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1051 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1052
1053 // Determine which methods need to be implemented, some may have
1054 // been overridden. Note that ::isSynthesized is not the method
1055 // we want, that just indicates if the decl came from a
1056 // property. What we want to know is if the method is defined in
1057 // this implementation.
1058 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001059 CodeGenFunction(*this).GenerateObjCGetter(
1060 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001061 if (!PD->isReadOnly() &&
1062 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001063 CodeGenFunction(*this).GenerateObjCSetter(
1064 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001065 }
1066 }
1067}
1068
Daniel Dunbar27250d32008-08-15 23:26:23 +00001069/// EmitTopLevelDecl - Emit code for a single top level declaration.
1070void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1071 // If an error has occurred, stop code generation, but continue
1072 // parsing and semantic analysis (to ensure all warnings and errors
1073 // are emitted).
1074 if (Diags.hasErrorOccurred())
1075 return;
1076
1077 switch (D->getKind()) {
1078 case Decl::Function:
1079 case Decl::Var:
1080 EmitGlobal(cast<ValueDecl>(D));
1081 break;
1082
1083 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001084 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001085 break;
1086
1087 // Objective-C Decls
1088
1089 // Forward declarations, no (immediate) code generation.
1090 case Decl::ObjCClass:
1091 case Decl::ObjCCategory:
1092 case Decl::ObjCForwardProtocol:
1093 case Decl::ObjCInterface:
1094 break;
1095
1096 case Decl::ObjCProtocol:
1097 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1098 break;
1099
1100 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001101 // Categories have properties but don't support synthesize so we
1102 // can ignore them here.
1103
Daniel Dunbar27250d32008-08-15 23:26:23 +00001104 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1105 break;
1106
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001107 case Decl::ObjCImplementation: {
1108 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1109 EmitObjCPropertyImplementations(OMD);
1110 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001111 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001112 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001113 case Decl::ObjCMethod: {
1114 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1115 // If this is not a prototype, emit the body.
1116 if (OMD->getBody())
1117 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1118 break;
1119 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001120 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001121 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001122 break;
1123
1124 case Decl::LinkageSpec: {
1125 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1126 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001127 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001128 // FIXME: implement C++ linkage, C linkage works mostly by C
1129 // language reuse already.
1130 break;
1131 }
1132
1133 case Decl::FileScopeAsm: {
1134 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1135 std::string AsmString(AD->getAsmString()->getStrData(),
1136 AD->getAsmString()->getByteLength());
1137
1138 const std::string &S = getModule().getModuleInlineAsm();
1139 if (S.empty())
1140 getModule().setModuleInlineAsm(AsmString);
1141 else
1142 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1143 break;
1144 }
1145
1146 default:
1147 // Make sure we handled everything we should, every other kind is
1148 // a non-top-level decl. FIXME: Would be nice to have an
1149 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1150 // that easily.
1151 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1152 }
1153}