blob: 6e1321f4d6c677e7b21b8b136bcf205059f832dc [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
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#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"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000021#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000022#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000025#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattner45e8cbd2007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000035 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000036 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000037 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman0c995092008-05-26 12:59:39 +000038 CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000039
40 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000041 if (Features.NeXTRuntime) {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000042 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanianee0af742009-01-21 22:04:16 +000043 : CreateMacObjCRuntime(*this);
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000044 } else {
45 Runtime = CreateGNUObjCRuntime(*this);
46 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000047 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000048
49 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000050 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000051}
52
53CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000054 delete Runtime;
55 delete DebugInfo;
56}
57
58void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000059 EmitStatics();
Daniel Dunbar219df662008-09-08 23:44:31 +000060 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000061 if (Runtime)
62 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
63 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000064 EmitCtorList(GlobalCtors, "llvm.global_ctors");
65 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000066 EmitAnnotations();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000067 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000068}
Reid Spencer5f016e22007-07-11 17:01:13 +000069
Daniel Dunbarf1968f22008-10-01 00:49:24 +000070void CodeGenModule::BindRuntimeFunctions() {
71 // Deal with protecting runtime function names.
72 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
73 llvm::Function *Fn = RuntimeFunctions[i].first;
74 const std::string &Name = RuntimeFunctions[i].second;
75
Daniel Dunbar0293d542008-11-19 06:15:35 +000076 // Discard unused runtime functions.
77 if (Fn->use_empty()) {
78 Fn->eraseFromParent();
79 continue;
80 }
81
Daniel Dunbarf1968f22008-10-01 00:49:24 +000082 // See if there is a conflict against a function.
83 llvm::Function *Conflict = TheModule.getFunction(Name);
84 if (Conflict) {
85 // Decide which version to take. If the conflict is a definition
86 // we are forced to take that, otherwise assume the runtime
87 // knows best.
88 if (!Conflict->isDeclaration()) {
89 llvm::Value *Casted =
90 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
91 Fn->replaceAllUsesWith(Casted);
92 Fn->eraseFromParent();
93 } else {
94 Fn->takeName(Conflict);
95 llvm::Value *Casted =
96 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
97 Conflict->replaceAllUsesWith(Casted);
98 Conflict->eraseFromParent();
99 }
100 } else {
101 // FIXME: There still may be conflicts with aliases and
102 // variables.
103 Fn->setName(Name);
104 }
105 }
106}
107
Daniel Dunbar488e9932008-08-16 00:56:44 +0000108/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000109/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000110void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
111 bool OmitOnError) {
112 if (OmitOnError && getDiags().hasErrorOccurred())
113 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000114 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000115 "cannot codegen this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000116 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000117 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
118 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000119}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000120
Daniel Dunbar488e9932008-08-16 00:56:44 +0000121/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000122/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000123void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
124 bool OmitOnError) {
125 if (OmitOnError && getDiags().hasErrorOccurred())
126 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000127 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000128 "cannot codegen this %0 yet");
129 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000130 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000131}
132
Daniel Dunbar41071de2008-08-15 23:26:23 +0000133/// setGlobalVisibility - Set the visibility for the given LLVM
134/// GlobalValue according to the given clang AST visibility value.
135static void setGlobalVisibility(llvm::GlobalValue *GV,
136 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000137 switch (Vis) {
138 default: assert(0 && "Unknown visibility!");
139 case VisibilityAttr::DefaultVisibility:
140 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
141 break;
142 case VisibilityAttr::HiddenVisibility:
143 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
144 break;
145 case VisibilityAttr::ProtectedVisibility:
146 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
147 break;
148 }
149}
150
Chris Lattner6d397602008-03-14 17:18:18 +0000151/// AddGlobalCtor - Add a function to the list that will be called before
152/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000153void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000154 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000155 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000156}
157
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000158/// AddGlobalDtor - Add a function to the list that will be called
159/// when the module is unloaded.
160void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000161 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000162 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
163}
164
165void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
166 // Ctor function type is void()*.
167 llvm::FunctionType* CtorFTy =
168 llvm::FunctionType::get(llvm::Type::VoidTy,
169 std::vector<const llvm::Type*>(),
170 false);
171 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
172
173 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000174 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000175 llvm::StructType::get(llvm::Type::Int32Ty,
176 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000177
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000178 // Construct the constructor and destructor arrays.
179 std::vector<llvm::Constant*> Ctors;
180 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
181 std::vector<llvm::Constant*> S;
182 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
183 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
184 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000185 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186
187 if (!Ctors.empty()) {
188 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
189 new llvm::GlobalVariable(AT, false,
190 llvm::GlobalValue::AppendingLinkage,
191 llvm::ConstantArray::get(AT, Ctors),
192 GlobalName,
193 &TheModule);
194 }
Chris Lattner6d397602008-03-14 17:18:18 +0000195}
196
Nate Begeman532485c2008-04-18 23:43:57 +0000197void CodeGenModule::EmitAnnotations() {
198 if (Annotations.empty())
199 return;
200
201 // Create a new global variable for the ConstantStruct in the Module.
202 llvm::Constant *Array =
203 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
204 Annotations.size()),
205 Annotations);
206 llvm::GlobalValue *gv =
207 new llvm::GlobalVariable(Array->getType(), false,
208 llvm::GlobalValue::AppendingLinkage, Array,
209 "llvm.global.annotations", &TheModule);
210 gv->setSection("llvm.metadata");
211}
212
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000213static void SetGlobalValueAttributes(const Decl *D,
214 bool IsInternal,
215 bool IsInline,
Daniel Dunbar219df662008-09-08 23:44:31 +0000216 llvm::GlobalValue *GV,
217 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000218 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000219 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000220 if (!ForDefinition) {
221 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000222 if (D->getAttr<DLLImportAttr>()) {
223 // The dllimport attribute is overridden by a subsequent declaration as
224 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000225 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000226 // dllimport attribute can be applied only to function decls, not to
227 // definitions.
228 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
229 if (!FD->getBody())
230 GV->setLinkage(llvm::Function::DLLImportLinkage);
231 } else
232 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000233 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000234 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000235 } else {
236 if (IsInternal) {
237 GV->setLinkage(llvm::Function::InternalLinkage);
238 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000239 if (D->getAttr<DLLExportAttr>()) {
240 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
241 // The dllexport attribute is ignored for undefined symbols.
242 if (FD->getBody())
243 GV->setLinkage(llvm::Function::DLLExportLinkage);
244 } else
245 GV->setLinkage(llvm::Function::DLLExportLinkage);
246 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000247 GV->setLinkage(llvm::Function::WeakLinkage);
248 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000249 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000250
Daniel Dunbar49988882009-01-13 02:25:00 +0000251 // FIXME: Figure out the relative priority of the attribute,
252 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000253 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000254 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000255 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000256
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000257 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000258 // Prefaced with special LLVM marker to indicate that the name
259 // should not be munged.
260 GV->setName("\01" + ALA->getLabel());
261 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000262}
263
Devang Patel761d7f72008-09-25 21:02:23 +0000264void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000265 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000266 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000267 AttributeListType AttributeList;
268 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
269 AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000270
Devang Patel761d7f72008-09-25 21:02:23 +0000271 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
272 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000273
274 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000275 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000276 F->setCallingConv(llvm::CallingConv::X86_FastCall);
277
278 if (D->getAttr<StdCallAttr>())
279 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000280}
281
282/// SetFunctionAttributesForDefinition - Set function attributes
283/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000284void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
285 llvm::Function *F) {
286 if (isa<ObjCMethodDecl>(D)) {
287 SetGlobalValueAttributes(D, true, false, F, true);
288 } else {
289 const FunctionDecl *FD = cast<FunctionDecl>(D);
290 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
291 FD->isInline(), F, true);
292 }
293
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000294 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000295 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000296
297 if (D->getAttr<AlwaysInlineAttr>())
298 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000299}
300
301void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
302 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000303 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000304
Daniel Dunbar219df662008-09-08 23:44:31 +0000305 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000306}
307
308void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
309 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000310 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000311
Daniel Dunbar219df662008-09-08 23:44:31 +0000312 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
313 FD->isInline(), F, false);
314}
315
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000316
Daniel Dunbar219df662008-09-08 23:44:31 +0000317void CodeGenModule::EmitAliases() {
318 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
319 const FunctionDecl *D = Aliases[i];
320 const AliasAttr *AA = D->getAttr<AliasAttr>();
321
322 // This is something of a hack, if the FunctionDecl got overridden
323 // then its attributes will be moved to the new declaration. In
324 // this case the current decl has no alias attribute, but we will
325 // eventually see it.
326 if (!AA)
327 continue;
328
329 const std::string& aliaseeName = AA->getAliasee();
330 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
331 if (!aliasee) {
332 // FIXME: This isn't unsupported, this is just an error, which
333 // sema should catch, but...
334 ErrorUnsupported(D, "alias referencing a missing function");
335 continue;
336 }
337
338 llvm::GlobalValue *GA =
339 new llvm::GlobalAlias(aliasee->getType(),
340 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000341 D->getNameAsString(), aliasee, &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000342
343 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
344 if (Entry) {
345 // If we created a dummy function for this then replace it.
346 GA->takeName(Entry);
347
348 llvm::Value *Casted =
349 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
350 Entry->replaceAllUsesWith(Casted);
351 Entry->eraseFromParent();
352
353 Entry = GA;
354 }
355
356 // Alias should never be internal or inline.
357 SetGlobalValueAttributes(D, false, false, GA, true);
358 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000359}
360
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000361void CodeGenModule::EmitStatics() {
362 // Emit code for each used static decl encountered. Since a previously unused
363 // static decl may become used during the generation of code for a static
364 // function, iterate until no changes are made.
365 bool Changed;
366 do {
367 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000368
369 for (std::list<const ValueDecl*>::iterator i = StaticDecls.begin(),
370 e = StaticDecls.end(); i != e; ) {
371 const ValueDecl *D = *i;
372
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000373 // Check if we have used a decl with the same name
374 // FIXME: The AST should have some sort of aggregate decls or
375 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000376 // FIXME: This is missing some important cases. For example, we
377 // need to check for uses in an alias and in a constructor.
Anders Carlssonb723f752009-01-04 02:08:04 +0000378 if (!GlobalDeclMap.count(D->getIdentifier())) {
379 i++;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000380 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000381 }
382
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000383 // Emit the definition.
384 EmitGlobalDefinition(D);
385
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000386 // Erase the used decl from the list.
Anders Carlssonb723f752009-01-04 02:08:04 +0000387 i = StaticDecls.erase(i);
388
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000389 // Remember that we made a change.
390 Changed = true;
391 }
392 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000393}
394
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000395/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
396/// annotation information for a given GlobalValue. The annotation struct is
397/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000398/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000399/// created from the AnnotateAttr's annotation. The third field is a constant
400/// string containing the name of the translation unit. The fourth field is
401/// the line number in the file of the annotated value declaration.
402///
403/// FIXME: this does not unique the annotation string constants, as llvm-gcc
404/// appears to.
405///
406llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
407 const AnnotateAttr *AA,
408 unsigned LineNo) {
409 llvm::Module *M = &getModule();
410
411 // get [N x i8] constants for the annotation string, and the filename string
412 // which are the 2nd and 3rd elements of the global annotation structure.
413 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
414 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
415 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
416 true);
417
418 // Get the two global values corresponding to the ConstantArrays we just
419 // created to hold the bytes of the strings.
420 llvm::GlobalValue *annoGV =
421 new llvm::GlobalVariable(anno->getType(), false,
422 llvm::GlobalValue::InternalLinkage, anno,
423 GV->getName() + ".str", M);
424 // translation unit name string, emitted into the llvm.metadata section.
425 llvm::GlobalValue *unitGV =
426 new llvm::GlobalVariable(unit->getType(), false,
427 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
428
429 // Create the ConstantStruct that is the global annotion.
430 llvm::Constant *Fields[4] = {
431 llvm::ConstantExpr::getBitCast(GV, SBP),
432 llvm::ConstantExpr::getBitCast(annoGV, SBP),
433 llvm::ConstantExpr::getBitCast(unitGV, SBP),
434 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
435 };
436 return llvm::ConstantStruct::get(Fields, 4, false);
437}
438
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000439void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
440 bool isDef, isStatic;
441
442 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000443 // Aliases are deferred until code for everything else has been
444 // emitted.
445 if (FD->getAttr<AliasAttr>()) {
446 assert(!FD->isThisDeclarationADefinition() &&
447 "Function alias cannot have a definition!");
448 Aliases.push_back(FD);
449 return;
450 }
451
452 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000453 isStatic = FD->getStorageClass() == FunctionDecl::Static;
454 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
455 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
456
Daniel Dunbar49988882009-01-13 02:25:00 +0000457 isDef = !((VD->getStorageClass() == VarDecl::Extern ||
458 VD->getStorageClass() == VarDecl::PrivateExtern) &&
459 VD->getInit() == 0);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000460 isStatic = VD->getStorageClass() == VarDecl::Static;
461 } else {
462 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000463 return;
464 }
465
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000466 // Forward declarations are emitted lazily on first use.
467 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000468 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000469
470 // If the global is a static, defer code generation until later so
471 // we can easily omit unused statics.
472 if (isStatic) {
473 StaticDecls.push_back(Global);
474 return;
475 }
476
477 // Otherwise emit the definition.
478 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000479}
480
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000481void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
482 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
483 EmitGlobalFunctionDefinition(FD);
484 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
485 EmitGlobalVarDefinition(VD);
486 } else {
487 assert(0 && "Invalid argument to EmitGlobalDefinition()");
488 }
489}
490
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000491 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000492 assert(D->hasGlobalStorage() && "Not a global variable");
493
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000494 QualType ASTTy = D->getType();
495 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000496 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000497
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000498 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000499 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar49988882009-01-13 02:25:00 +0000500 if (!Entry) {
501 llvm::GlobalVariable *GV =
502 new llvm::GlobalVariable(Ty, false,
503 llvm::GlobalValue::ExternalLinkage,
504 0, D->getNameAsString(), &getModule(), 0,
505 ASTTy.getAddressSpace());
506 Entry = GV;
507
508 // Handle things which are present even on external declarations.
509
510 // FIXME: This code is overly simple and should be merged with
511 // other global handling.
512
513 GV->setConstant(D->getType().isConstant(Context));
514
515 if (D->getStorageClass() == VarDecl::PrivateExtern)
516 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
517 }
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000518
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000519 // Make sure the result is of the correct type.
520 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000521}
522
523void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000524 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000525 QualType ASTTy = D->getType();
526 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000527
Chris Lattner8f32f712007-07-14 00:23:28 +0000528 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000529 // This is a tentative definition; tentative definitions are
530 // implicitly initialized with { 0 }
531 const llvm::Type* InitTy;
532 if (ASTTy->isIncompleteArrayType()) {
533 // An incomplete array is normally [ TYPE x 0 ], but we need
534 // to fix it to [ TYPE x 1 ].
535 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
536 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
537 } else {
538 InitTy = VarTy;
539 }
540 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000541 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000542 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000543 }
544 const llvm::Type* InitType = Init->getType();
545
Daniel Dunbar90db8822008-08-25 06:18:57 +0000546 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000547 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
548
Eli Friedman77ba7082008-05-30 19:50:47 +0000549 if (!GV) {
550 GV = new llvm::GlobalVariable(InitType, false,
551 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000552 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000553 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000554 } else if (GV->getType() !=
555 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000556 // We have a definition after a prototype with the wrong type.
557 // We must make a new GlobalVariable* and update everything that used OldGV
558 // (a declaration or tentative definition) with the new GlobalVariable*
559 // (which will be a definition).
560 //
561 // This happens if there is a prototype for a global (e.g. "extern int x[];")
562 // and then a definition of a different type (e.g. "int x[10];"). This also
563 // happens when an initializer has a different type from the type of the
564 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000565 //
566 // FIXME: This also ends up happening if there's a definition followed by
567 // a tentative definition! (Although Sema rejects that construct
568 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000569
570 // Save the old global
571 llvm::GlobalVariable *OldGV = GV;
572
573 // Make a new global with the correct type
574 GV = new llvm::GlobalVariable(InitType, false,
575 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000576 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000577 ASTTy.getAddressSpace());
578 // Steal the name of the old global
579 GV->takeName(OldGV);
580
581 // Replace all uses of the old global with the new global
582 llvm::Constant *NewPtrForOldDecl =
583 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
584 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000585
586 // Erase the old global, since it is no longer used.
587 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000588 }
Devang Patel8e53e722007-10-26 16:31:40 +0000589
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000590 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000591
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000592 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
593 SourceManager &SM = Context.getSourceManager();
594 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000595 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000596 }
597
Chris Lattner88a69ad2007-07-13 05:13:43 +0000598 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000599 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000600
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000601 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
602 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000603 if (const IncompleteArrayType* IAT =
604 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000605 Align = Context.getTypeAlign(IAT->getElementType());
606 else
607 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000608 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
609 Align = std::max(Align, AA->getAlignment());
610 }
611 GV->setAlignment(Align / 8);
612
Chris Lattnerddee4232008-03-03 03:28:21 +0000613 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000614 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000615 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000616
617 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
618 // Prefaced with special LLVM marker to indicate that the name
619 // should not be munged.
620 GV->setName("\01" + ALA->getLabel());
621 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000622
623 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000624 if (D->getStorageClass() == VarDecl::Static)
625 GV->setLinkage(llvm::Function::InternalLinkage);
626 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000627 GV->setLinkage(llvm::Function::DLLImportLinkage);
628 else if (D->getAttr<DLLExportAttr>())
629 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000630 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000631 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000632 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000633 // FIXME: This isn't right. This should handle common linkage and other
634 // stuff.
635 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000636 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000637 case VarDecl::Auto:
638 case VarDecl::Register:
639 assert(0 && "Can't have auto or register globals");
640 case VarDecl::None:
641 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000642 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000643 else
644 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000645 break;
646 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000647 // FIXME: common
648 break;
649
Chris Lattnerddee4232008-03-03 03:28:21 +0000650 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000651 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
652 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000653 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000654 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000655 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000656
657 // Emit global variable debug information.
658 CGDebugInfo *DI = getDebugInfo();
659 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000660 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000661 DI->EmitGlobalVariable(GV, D);
662 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000663}
Reid Spencer5f016e22007-07-11 17:01:13 +0000664
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000665llvm::GlobalValue *
666CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000667 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
668 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
669 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000670 D->getNameAsString(),&getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000671 SetFunctionAttributes(D, F);
672 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000673}
674
675llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000676 QualType ASTTy = D->getType();
677 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
678 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000679
680 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000681 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000682 if (!Entry)
683 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000684
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000685 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000686}
687
688void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000689 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000690 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000691 Entry = EmitForwardFunctionDefinition(D);
692 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000693 // If the types mismatch then we have to rewrite the definition.
694 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
695 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000696 // Otherwise, we have a definition after a prototype with the wrong type.
697 // F is the Function* for the one with the wrong type, we must make a new
698 // Function* and update everything that used F (a declaration) with the new
699 // Function* (which will be a definition).
700 //
701 // This happens if there is a prototype for a function (e.g. "int f()") and
702 // then a definition of a different type (e.g. "int f(int x)"). Start by
703 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000704 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
705 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000706
707 // Replace uses of F with the Function we will endow with a body.
708 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000709 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
710 Entry->replaceAllUsesWith(NewPtrForOldDecl);
711
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000712 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000713 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000714 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000715
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000716 Entry = NewFn;
717 }
718 }
719
Daniel Dunbar219df662008-09-08 23:44:31 +0000720 llvm::Function *Fn = cast<llvm::Function>(Entry);
721 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000722
Daniel Dunbar219df662008-09-08 23:44:31 +0000723 SetFunctionAttributesForDefinition(D, Fn);
724
725 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
726 AddGlobalCtor(Fn, CA->getPriority());
727 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
728 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000729 }
730}
731
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000732llvm::Function *
733CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
734 const std::string &Name) {
735 llvm::Function *Fn = llvm::Function::Create(FTy,
736 llvm::Function::ExternalLinkage,
737 "", &TheModule);
738 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
739 return Fn;
740}
741
Chris Lattnerc5b88062008-02-06 05:08:19 +0000742void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
743 // Make sure that this type is translated.
744 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000745}
746
747
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000748/// getBuiltinLibFunction
749llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000750 if (BuiltinID > BuiltinFunctions.size())
751 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000752
Chris Lattner1426fec2007-12-13 00:38:03 +0000753 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
754 // a slot for it.
755 assert(BuiltinID && "Invalid Builtin ID");
756 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000757 if (FunctionSlot)
758 return FunctionSlot;
759
760 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
761
762 // Get the name, skip over the __builtin_ prefix.
763 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
764
765 // Get the type for the builtin.
766 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
767 const llvm::FunctionType *Ty =
768 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
769
770 // FIXME: This has a serious problem with code like this:
771 // void abs() {}
772 // ... __builtin_abs(x);
773 // The two versions of abs will collide. The fix is for the builtin to win,
774 // and for the existing one to be turned into a constantexpr cast of the
775 // builtin. In the case where the existing one is a static function, it
776 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000777 if (llvm::Function *Existing = getModule().getFunction(Name)) {
778 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
779 return FunctionSlot = Existing;
780 assert(Existing == 0 && "FIXME: Name collision");
781 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000782
783 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000784 return FunctionSlot =
785 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
786 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000787}
788
Chris Lattner7acda7c2007-12-18 00:25:38 +0000789llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
790 unsigned NumTys) {
791 return llvm::Intrinsic::getDeclaration(&getModule(),
792 (llvm::Intrinsic::ID)IID, Tys, NumTys);
793}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000794
Reid Spencer5f016e22007-07-11 17:01:13 +0000795llvm::Function *CodeGenModule::getMemCpyFn() {
796 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000797 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
798 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000800
Eli Friedman0c995092008-05-26 12:59:39 +0000801llvm::Function *CodeGenModule::getMemMoveFn() {
802 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000803 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
804 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000805}
806
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000807llvm::Function *CodeGenModule::getMemSetFn() {
808 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000809 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
810 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000811}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000812
Anders Carlssone3daa762008-11-15 18:54:24 +0000813static void appendFieldAndPadding(CodeGenModule &CGM,
814 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000815 FieldDecl *FieldD, FieldDecl *NextFieldD,
816 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000817 RecordDecl* RD, const llvm::StructType *STy)
818{
819 // Append the field.
820 Fields.push_back(Field);
821
Douglas Gregor44b43212008-12-11 16:49:14 +0000822 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000823
824 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000825 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000826 NextStructFieldNo = STy->getNumElements();
827 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000828 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000829 }
830
831 // Append padding
832 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
833 llvm::Constant *C =
834 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
835
836 Fields.push_back(C);
837 }
838}
839
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000840// We still need to work out the details of handling UTF-16.
841// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000842llvm::Constant *CodeGenModule::
843GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000844 llvm::StringMapEntry<llvm::Constant *> &Entry =
845 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
846
847 if (Entry.getValue())
848 return Entry.getValue();
849
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000850 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
851 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000852
853 if (!CFConstantStringClassRef) {
854 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
855 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000856
857 // FIXME: This is fairly broken if
858 // __CFConstantStringClassReference is already defined, in that it
859 // will get renamed and the user will most likely see an opaque
860 // error message. This is a general issue with relying on
861 // particular names.
862 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000863 new llvm::GlobalVariable(Ty, false,
864 llvm::GlobalVariable::ExternalLinkage, 0,
865 "__CFConstantStringClassReference",
866 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000867
868 // Decay array -> ptr
869 CFConstantStringClassRef =
870 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000871 }
872
Anders Carlssone3daa762008-11-15 18:54:24 +0000873 QualType CFTy = getContext().getCFConstantStringType();
874 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000875
Anders Carlssone3daa762008-11-15 18:54:24 +0000876 const llvm::StructType *STy =
877 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
878
879 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +0000880 RecordDecl::field_iterator Field = CFRD->field_begin();
881
Anders Carlssonc9e20912007-08-21 00:21:21 +0000882 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000883 FieldDecl *CurField = *Field++;
884 FieldDecl *NextField = *Field++;
885 appendFieldAndPadding(*this, Fields, CurField, NextField,
886 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000887
888 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +0000889 CurField = NextField;
890 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000891 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000892 appendFieldAndPadding(*this, Fields, CurField, NextField,
893 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000894
895 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000896 CurField = NextField;
897 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000898 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000899 C = new llvm::GlobalVariable(C->getType(), true,
900 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000901 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +0000902 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +0000903 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
904 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000905
906 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +0000907 CurField = NextField;
908 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000909 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000910 appendFieldAndPadding(*this, Fields, CurField, NextField,
911 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000912
913 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +0000914 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000915 llvm::GlobalVariable *GV =
916 new llvm::GlobalVariable(C->getType(), true,
917 llvm::GlobalVariable::InternalLinkage,
918 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000919
Anders Carlsson0c678292007-11-01 00:41:52 +0000920 GV->setSection("__DATA,__cfstring");
921 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000922
Anders Carlsson0c678292007-11-01 00:41:52 +0000923 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000924}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000925
Daniel Dunbar61432932008-08-13 23:20:05 +0000926/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000927/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000928std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000929 if (E->isWide()) {
930 ErrorUnsupported(E, "wide string");
931 return "FIXME";
932 }
933
Daniel Dunbar1e049762008-08-10 20:25:57 +0000934 const char *StrData = E->getStrData();
935 unsigned Len = E->getByteLength();
936
937 const ConstantArrayType *CAT =
938 getContext().getAsConstantArrayType(E->getType());
939 assert(CAT && "String isn't pointer or array!");
940
941 // Resize the string to the right size
942 // FIXME: What about wchar_t strings?
943 std::string Str(StrData, StrData+Len);
944 uint64_t RealLen = CAT->getSize().getZExtValue();
945 Str.resize(RealLen, '\0');
946
947 return Str;
948}
949
Daniel Dunbar61432932008-08-13 23:20:05 +0000950/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
951/// constant array for the given string literal.
952llvm::Constant *
953CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
954 // FIXME: This can be more efficient.
955 return GetAddrOfConstantString(GetStringForStringLiteral(S));
956}
957
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000958/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000959static llvm::Constant *GenerateStringLiteral(const std::string &str,
960 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000961 CodeGenModule &CGM,
962 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000963 // Create Constant for this string literal. Don't add a '\0'.
964 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000965
966 // Create a global variable for this string
967 C = new llvm::GlobalVariable(C->getType(), constant,
968 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000969 C,
970 GlobalName ? GlobalName : ".str",
971 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000972
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000973 return C;
974}
975
Daniel Dunbar61432932008-08-13 23:20:05 +0000976/// GetAddrOfConstantString - Returns a pointer to a character array
977/// containing the literal. This contents are exactly that of the
978/// given string, i.e. it will not be null terminated automatically;
979/// see GetAddrOfConstantCString. Note that whether the result is
980/// actually a pointer to an LLVM constant depends on
981/// Feature.WriteableStrings.
982///
983/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000984llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
985 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000986 // Don't share any string literals if writable-strings is turned on.
987 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000988 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000989
990 llvm::StringMapEntry<llvm::Constant *> &Entry =
991 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
992
993 if (Entry.getValue())
994 return Entry.getValue();
995
996 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000997 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000998 Entry.setValue(C);
999 return C;
1000}
Daniel Dunbar61432932008-08-13 23:20:05 +00001001
1002/// GetAddrOfConstantCString - Returns a pointer to a character
1003/// array containing the literal and a terminating '\-'
1004/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001005llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1006 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001007 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001008}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001009
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001010/// EmitObjCPropertyImplementations - Emit information for synthesized
1011/// properties for an implementation.
1012void CodeGenModule::EmitObjCPropertyImplementations(const
1013 ObjCImplementationDecl *D) {
1014 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1015 e = D->propimpl_end(); i != e; ++i) {
1016 ObjCPropertyImplDecl *PID = *i;
1017
1018 // Dynamic is just for type-checking.
1019 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1020 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1021
1022 // Determine which methods need to be implemented, some may have
1023 // been overridden. Note that ::isSynthesized is not the method
1024 // we want, that just indicates if the decl came from a
1025 // property. What we want to know is if the method is defined in
1026 // this implementation.
1027 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001028 CodeGenFunction(*this).GenerateObjCGetter(
1029 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001030 if (!PD->isReadOnly() &&
1031 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001032 CodeGenFunction(*this).GenerateObjCSetter(
1033 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001034 }
1035 }
1036}
1037
Daniel Dunbar41071de2008-08-15 23:26:23 +00001038/// EmitTopLevelDecl - Emit code for a single top level declaration.
1039void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1040 // If an error has occurred, stop code generation, but continue
1041 // parsing and semantic analysis (to ensure all warnings and errors
1042 // are emitted).
1043 if (Diags.hasErrorOccurred())
1044 return;
1045
1046 switch (D->getKind()) {
1047 case Decl::Function:
1048 case Decl::Var:
1049 EmitGlobal(cast<ValueDecl>(D));
1050 break;
1051
1052 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001053 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001054 break;
1055
1056 // Objective-C Decls
1057
1058 // Forward declarations, no (immediate) code generation.
1059 case Decl::ObjCClass:
1060 case Decl::ObjCCategory:
1061 case Decl::ObjCForwardProtocol:
1062 case Decl::ObjCInterface:
1063 break;
1064
1065 case Decl::ObjCProtocol:
1066 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1067 break;
1068
1069 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001070 // Categories have properties but don't support synthesize so we
1071 // can ignore them here.
1072
Daniel Dunbar41071de2008-08-15 23:26:23 +00001073 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1074 break;
1075
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001076 case Decl::ObjCImplementation: {
1077 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1078 EmitObjCPropertyImplementations(OMD);
1079 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001080 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001081 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001082 case Decl::ObjCMethod: {
1083 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1084 // If this is not a prototype, emit the body.
1085 if (OMD->getBody())
1086 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1087 break;
1088 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001089 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001090 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001091 break;
1092
1093 case Decl::LinkageSpec: {
1094 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1095 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001096 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001097 // FIXME: implement C++ linkage, C linkage works mostly by C
1098 // language reuse already.
1099 break;
1100 }
1101
1102 case Decl::FileScopeAsm: {
1103 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1104 std::string AsmString(AD->getAsmString()->getStrData(),
1105 AD->getAsmString()->getByteLength());
1106
1107 const std::string &S = getModule().getModuleInlineAsm();
1108 if (S.empty())
1109 getModule().setModuleInlineAsm(AsmString);
1110 else
1111 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1112 break;
1113 }
1114
1115 default:
1116 // Make sure we handled everything we should, every other kind is
1117 // a non-top-level decl. FIXME: Would be nice to have an
1118 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1119 // that easily.
1120 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1121 }
1122}
1123