blob: ff8acde99510d0a02013541fbe6a46be3bda0124 [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) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000042 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000046 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar219df662008-09-08 23:44:31 +000059 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000060 if (Runtime)
61 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
62 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000063 EmitCtorList(GlobalCtors, "llvm.global_ctors");
64 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000065 EmitAnnotations();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000066 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000067}
Reid Spencer5f016e22007-07-11 17:01:13 +000068
Daniel Dunbarf1968f22008-10-01 00:49:24 +000069void CodeGenModule::BindRuntimeFunctions() {
70 // Deal with protecting runtime function names.
71 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
72 llvm::Function *Fn = RuntimeFunctions[i].first;
73 const std::string &Name = RuntimeFunctions[i].second;
74
Daniel Dunbar0293d542008-11-19 06:15:35 +000075 // Discard unused runtime functions.
76 if (Fn->use_empty()) {
77 Fn->eraseFromParent();
78 continue;
79 }
80
Daniel Dunbarf1968f22008-10-01 00:49:24 +000081 // See if there is a conflict against a function.
82 llvm::Function *Conflict = TheModule.getFunction(Name);
83 if (Conflict) {
84 // Decide which version to take. If the conflict is a definition
85 // we are forced to take that, otherwise assume the runtime
86 // knows best.
87 if (!Conflict->isDeclaration()) {
88 llvm::Value *Casted =
89 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
90 Fn->replaceAllUsesWith(Casted);
91 Fn->eraseFromParent();
92 } else {
93 Fn->takeName(Conflict);
94 llvm::Value *Casted =
95 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
96 Conflict->replaceAllUsesWith(Casted);
97 Conflict->eraseFromParent();
98 }
99 } else {
100 // FIXME: There still may be conflicts with aliases and
101 // variables.
102 Fn->setName(Name);
103 }
104 }
105}
106
Daniel Dunbar488e9932008-08-16 00:56:44 +0000107/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000108/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000109void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
110 bool OmitOnError) {
111 if (OmitOnError && getDiags().hasErrorOccurred())
112 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000113 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000114 "cannot codegen this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000115 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000116 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
117 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000118}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000119
Daniel Dunbar488e9932008-08-16 00:56:44 +0000120/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000121/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000122void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
123 bool OmitOnError) {
124 if (OmitOnError && getDiags().hasErrorOccurred())
125 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000127 "cannot codegen this %0 yet");
128 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000129 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000130}
131
Daniel Dunbar41071de2008-08-15 23:26:23 +0000132/// setGlobalVisibility - Set the visibility for the given LLVM
133/// GlobalValue according to the given clang AST visibility value.
134static void setGlobalVisibility(llvm::GlobalValue *GV,
135 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000136 switch (Vis) {
137 default: assert(0 && "Unknown visibility!");
138 case VisibilityAttr::DefaultVisibility:
139 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
140 break;
141 case VisibilityAttr::HiddenVisibility:
142 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
143 break;
144 case VisibilityAttr::ProtectedVisibility:
145 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
146 break;
147 }
148}
149
Chris Lattner6d397602008-03-14 17:18:18 +0000150/// AddGlobalCtor - Add a function to the list that will be called before
151/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000153 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000154 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000155}
156
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000157/// AddGlobalDtor - Add a function to the list that will be called
158/// when the module is unloaded.
159void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
160 // TODO: Type coercion of void()* types.
161 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
162}
163
164void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
165 // Ctor function type is void()*.
166 llvm::FunctionType* CtorFTy =
167 llvm::FunctionType::get(llvm::Type::VoidTy,
168 std::vector<const llvm::Type*>(),
169 false);
170 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
171
172 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000173 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000174 llvm::StructType::get(llvm::Type::Int32Ty,
175 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000176
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000177 // Construct the constructor and destructor arrays.
178 std::vector<llvm::Constant*> Ctors;
179 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
180 std::vector<llvm::Constant*> S;
181 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
182 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
183 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000184 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185
186 if (!Ctors.empty()) {
187 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
188 new llvm::GlobalVariable(AT, false,
189 llvm::GlobalValue::AppendingLinkage,
190 llvm::ConstantArray::get(AT, Ctors),
191 GlobalName,
192 &TheModule);
193 }
Chris Lattner6d397602008-03-14 17:18:18 +0000194}
195
Nate Begeman532485c2008-04-18 23:43:57 +0000196void CodeGenModule::EmitAnnotations() {
197 if (Annotations.empty())
198 return;
199
200 // Create a new global variable for the ConstantStruct in the Module.
201 llvm::Constant *Array =
202 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
203 Annotations.size()),
204 Annotations);
205 llvm::GlobalValue *gv =
206 new llvm::GlobalVariable(Array->getType(), false,
207 llvm::GlobalValue::AppendingLinkage, Array,
208 "llvm.global.annotations", &TheModule);
209 gv->setSection("llvm.metadata");
210}
211
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000212static void SetGlobalValueAttributes(const Decl *D,
213 bool IsInternal,
214 bool IsInline,
Daniel Dunbar219df662008-09-08 23:44:31 +0000215 llvm::GlobalValue *GV,
216 bool ForDefinition) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000217 // TODO: Set up linkage and many other things. Note, this is a simple
218 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000219 if (!ForDefinition) {
220 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000221 if (D->getAttr<DLLImportAttr>()) {
222 // The dllimport attribute is overridden by a subsequent declaration as
223 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000224 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000225 // dllimport attribute can be applied only to function decls, not to
226 // definitions.
227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
228 if (!FD->getBody())
229 GV->setLinkage(llvm::Function::DLLImportLinkage);
230 } else
231 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000232 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000233 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000234 } else {
235 if (IsInternal) {
236 GV->setLinkage(llvm::Function::InternalLinkage);
237 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000238 if (D->getAttr<DLLExportAttr>()) {
239 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
240 // The dllexport attribute is ignored for undefined symbols.
241 if (FD->getBody())
242 GV->setLinkage(llvm::Function::DLLExportLinkage);
243 } else
244 GV->setLinkage(llvm::Function::DLLExportLinkage);
245 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000246 GV->setLinkage(llvm::Function::WeakLinkage);
247 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000248 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000249
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000250 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000251 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000252 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000253
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000254 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000255 // Prefaced with special LLVM marker to indicate that the name
256 // should not be munged.
257 GV->setName("\01" + ALA->getLabel());
258 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000259}
260
Devang Patel761d7f72008-09-25 21:02:23 +0000261void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000262 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000263 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000264 AttributeListType AttributeList;
265 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
266 AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000267
Devang Patel761d7f72008-09-25 21:02:23 +0000268 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
269 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000270
271 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000272 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000273 F->setCallingConv(llvm::CallingConv::X86_FastCall);
274
275 if (D->getAttr<StdCallAttr>())
276 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000277}
278
279/// SetFunctionAttributesForDefinition - Set function attributes
280/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000281void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
282 llvm::Function *F) {
283 if (isa<ObjCMethodDecl>(D)) {
284 SetGlobalValueAttributes(D, true, false, F, true);
285 } else {
286 const FunctionDecl *FD = cast<FunctionDecl>(D);
287 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
288 FD->isInline(), F, true);
289 }
290
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000291 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000292 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000293
294 if (D->getAttr<AlwaysInlineAttr>())
295 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000296}
297
298void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
299 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000300 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000301
Daniel Dunbar219df662008-09-08 23:44:31 +0000302 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000303}
304
305void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
306 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000307 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000308
Daniel Dunbar219df662008-09-08 23:44:31 +0000309 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
310 FD->isInline(), F, false);
311}
312
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000313
Daniel Dunbar219df662008-09-08 23:44:31 +0000314void CodeGenModule::EmitAliases() {
315 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
316 const FunctionDecl *D = Aliases[i];
317 const AliasAttr *AA = D->getAttr<AliasAttr>();
318
319 // This is something of a hack, if the FunctionDecl got overridden
320 // then its attributes will be moved to the new declaration. In
321 // this case the current decl has no alias attribute, but we will
322 // eventually see it.
323 if (!AA)
324 continue;
325
326 const std::string& aliaseeName = AA->getAliasee();
327 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
328 if (!aliasee) {
329 // FIXME: This isn't unsupported, this is just an error, which
330 // sema should catch, but...
331 ErrorUnsupported(D, "alias referencing a missing function");
332 continue;
333 }
334
335 llvm::GlobalValue *GA =
336 new llvm::GlobalAlias(aliasee->getType(),
337 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000338 D->getNameAsString(), aliasee, &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000339
340 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
341 if (Entry) {
342 // If we created a dummy function for this then replace it.
343 GA->takeName(Entry);
344
345 llvm::Value *Casted =
346 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
347 Entry->replaceAllUsesWith(Casted);
348 Entry->eraseFromParent();
349
350 Entry = GA;
351 }
352
353 // Alias should never be internal or inline.
354 SetGlobalValueAttributes(D, false, false, GA, true);
355 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000356}
357
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000358void CodeGenModule::EmitStatics() {
359 // Emit code for each used static decl encountered. Since a previously unused
360 // static decl may become used during the generation of code for a static
361 // function, iterate until no changes are made.
362 bool Changed;
363 do {
364 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000365
366 for (std::list<const ValueDecl*>::iterator i = StaticDecls.begin(),
367 e = StaticDecls.end(); i != e; ) {
368 const ValueDecl *D = *i;
369
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000370 // Check if we have used a decl with the same name
371 // FIXME: The AST should have some sort of aggregate decls or
372 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000373 // FIXME: This is missing some important cases. For example, we
374 // need to check for uses in an alias and in a constructor.
Anders Carlssonb723f752009-01-04 02:08:04 +0000375 if (!GlobalDeclMap.count(D->getIdentifier())) {
376 i++;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000377 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000378 }
379
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000380 // Emit the definition.
381 EmitGlobalDefinition(D);
382
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000383 // Erase the used decl from the list.
Anders Carlssonb723f752009-01-04 02:08:04 +0000384 i = StaticDecls.erase(i);
385
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000386 // Remember that we made a change.
387 Changed = true;
388 }
389 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000390}
391
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000392/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
393/// annotation information for a given GlobalValue. The annotation struct is
394/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000395/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000396/// created from the AnnotateAttr's annotation. The third field is a constant
397/// string containing the name of the translation unit. The fourth field is
398/// the line number in the file of the annotated value declaration.
399///
400/// FIXME: this does not unique the annotation string constants, as llvm-gcc
401/// appears to.
402///
403llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
404 const AnnotateAttr *AA,
405 unsigned LineNo) {
406 llvm::Module *M = &getModule();
407
408 // get [N x i8] constants for the annotation string, and the filename string
409 // which are the 2nd and 3rd elements of the global annotation structure.
410 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
411 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
412 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
413 true);
414
415 // Get the two global values corresponding to the ConstantArrays we just
416 // created to hold the bytes of the strings.
417 llvm::GlobalValue *annoGV =
418 new llvm::GlobalVariable(anno->getType(), false,
419 llvm::GlobalValue::InternalLinkage, anno,
420 GV->getName() + ".str", M);
421 // translation unit name string, emitted into the llvm.metadata section.
422 llvm::GlobalValue *unitGV =
423 new llvm::GlobalVariable(unit->getType(), false,
424 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
425
426 // Create the ConstantStruct that is the global annotion.
427 llvm::Constant *Fields[4] = {
428 llvm::ConstantExpr::getBitCast(GV, SBP),
429 llvm::ConstantExpr::getBitCast(annoGV, SBP),
430 llvm::ConstantExpr::getBitCast(unitGV, SBP),
431 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
432 };
433 return llvm::ConstantStruct::get(Fields, 4, false);
434}
435
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000436void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
437 bool isDef, isStatic;
438
439 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000440 // Aliases are deferred until code for everything else has been
441 // emitted.
442 if (FD->getAttr<AliasAttr>()) {
443 assert(!FD->isThisDeclarationADefinition() &&
444 "Function alias cannot have a definition!");
445 Aliases.push_back(FD);
446 return;
447 }
448
449 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000450 isStatic = FD->getStorageClass() == FunctionDecl::Static;
451 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
452 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
453
454 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
455 isStatic = VD->getStorageClass() == VarDecl::Static;
456 } else {
457 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000458 return;
459 }
460
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000461 // Forward declarations are emitted lazily on first use.
462 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000463 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000464
465 // If the global is a static, defer code generation until later so
466 // we can easily omit unused statics.
467 if (isStatic) {
468 StaticDecls.push_back(Global);
469 return;
470 }
471
472 // Otherwise emit the definition.
473 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000474}
475
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000476void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
478 EmitGlobalFunctionDefinition(FD);
479 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
480 EmitGlobalVarDefinition(VD);
481 } else {
482 assert(0 && "Invalid argument to EmitGlobalDefinition()");
483 }
484}
485
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000486 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000487 assert(D->hasGlobalStorage() && "Not a global variable");
488
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000489 QualType ASTTy = D->getType();
490 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000491 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000492
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000493 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000494 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000495 if (!Entry)
496 Entry = new llvm::GlobalVariable(Ty, false,
497 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000498 0, D->getNameAsString(), &getModule(), 0,
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000499 ASTTy.getAddressSpace());
500
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000501 // Make sure the result is of the correct type.
502 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000503}
504
505void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000506 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000507 QualType ASTTy = D->getType();
508 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000509
Chris Lattner8f32f712007-07-14 00:23:28 +0000510 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000511 // This is a tentative definition; tentative definitions are
512 // implicitly initialized with { 0 }
513 const llvm::Type* InitTy;
514 if (ASTTy->isIncompleteArrayType()) {
515 // An incomplete array is normally [ TYPE x 0 ], but we need
516 // to fix it to [ TYPE x 1 ].
517 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
518 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
519 } else {
520 InitTy = VarTy;
521 }
522 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000523 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000524 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000525 }
526 const llvm::Type* InitType = Init->getType();
527
Daniel Dunbar90db8822008-08-25 06:18:57 +0000528 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000529 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
530
Eli Friedman77ba7082008-05-30 19:50:47 +0000531 if (!GV) {
532 GV = new llvm::GlobalVariable(InitType, false,
533 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000534 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000535 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000536 } else if (GV->getType() !=
537 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000538 // We have a definition after a prototype with the wrong type.
539 // We must make a new GlobalVariable* and update everything that used OldGV
540 // (a declaration or tentative definition) with the new GlobalVariable*
541 // (which will be a definition).
542 //
543 // This happens if there is a prototype for a global (e.g. "extern int x[];")
544 // and then a definition of a different type (e.g. "int x[10];"). This also
545 // happens when an initializer has a different type from the type of the
546 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000547 //
548 // FIXME: This also ends up happening if there's a definition followed by
549 // a tentative definition! (Although Sema rejects that construct
550 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000551
552 // Save the old global
553 llvm::GlobalVariable *OldGV = GV;
554
555 // Make a new global with the correct type
556 GV = new llvm::GlobalVariable(InitType, false,
557 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000558 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000559 ASTTy.getAddressSpace());
560 // Steal the name of the old global
561 GV->takeName(OldGV);
562
563 // Replace all uses of the old global with the new global
564 llvm::Constant *NewPtrForOldDecl =
565 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
566 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000567
568 // Erase the old global, since it is no longer used.
569 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000570 }
Devang Patel8e53e722007-10-26 16:31:40 +0000571
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000572 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000573
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000574 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
575 SourceManager &SM = Context.getSourceManager();
576 AddAnnotation(EmitAnnotateAttr(GV, AA,
577 SM.getLogicalLineNumber(D->getLocation())));
578 }
579
Chris Lattner88a69ad2007-07-13 05:13:43 +0000580 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000581 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000582
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000583 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
584 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000585 if (const IncompleteArrayType* IAT =
586 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000587 Align = Context.getTypeAlign(IAT->getElementType());
588 else
589 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000590 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
591 Align = std::max(Align, AA->getAlignment());
592 }
593 GV->setAlignment(Align / 8);
594
Chris Lattnerddee4232008-03-03 03:28:21 +0000595 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000596 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000597 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000598
599 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
600 // Prefaced with special LLVM marker to indicate that the name
601 // should not be munged.
602 GV->setName("\01" + ALA->getLabel());
603 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000604
605 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000606 if (D->getStorageClass() == VarDecl::Static)
607 GV->setLinkage(llvm::Function::InternalLinkage);
608 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000609 GV->setLinkage(llvm::Function::DLLImportLinkage);
610 else if (D->getAttr<DLLExportAttr>())
611 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000612 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000613 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000614 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000615 // FIXME: This isn't right. This should handle common linkage and other
616 // stuff.
617 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000618 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000619 case VarDecl::Auto:
620 case VarDecl::Register:
621 assert(0 && "Can't have auto or register globals");
622 case VarDecl::None:
623 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000624 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000625 else
626 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000627 break;
628 case VarDecl::Extern:
629 case VarDecl::PrivateExtern:
630 // todo: common
631 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000632 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000633 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000634
635 // Emit global variable debug information.
636 CGDebugInfo *DI = getDebugInfo();
637 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000638 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000639 DI->EmitGlobalVariable(GV, D);
640 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000641}
Reid Spencer5f016e22007-07-11 17:01:13 +0000642
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000643llvm::GlobalValue *
644CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000645 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
646 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
647 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000648 D->getNameAsString(),&getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000649 SetFunctionAttributes(D, F);
650 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000651}
652
653llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000654 QualType ASTTy = D->getType();
655 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
656 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000657
658 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000659 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000660 if (!Entry)
661 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000662
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000663 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000664}
665
666void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000667 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000668 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000669 Entry = EmitForwardFunctionDefinition(D);
670 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000671 // If the types mismatch then we have to rewrite the definition.
672 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
673 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000674 // Otherwise, we have a definition after a prototype with the wrong type.
675 // F is the Function* for the one with the wrong type, we must make a new
676 // Function* and update everything that used F (a declaration) with the new
677 // Function* (which will be a definition).
678 //
679 // This happens if there is a prototype for a function (e.g. "int f()") and
680 // then a definition of a different type (e.g. "int f(int x)"). Start by
681 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000682 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
683 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000684
685 // Replace uses of F with the Function we will endow with a body.
686 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000687 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
688 Entry->replaceAllUsesWith(NewPtrForOldDecl);
689
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000690 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000691 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000692 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000693
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000694 Entry = NewFn;
695 }
696 }
697
Daniel Dunbar219df662008-09-08 23:44:31 +0000698 llvm::Function *Fn = cast<llvm::Function>(Entry);
699 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000700
Daniel Dunbar219df662008-09-08 23:44:31 +0000701 SetFunctionAttributesForDefinition(D, Fn);
702
703 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
704 AddGlobalCtor(Fn, CA->getPriority());
705 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
706 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000707 }
708}
709
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000710llvm::Function *
711CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
712 const std::string &Name) {
713 llvm::Function *Fn = llvm::Function::Create(FTy,
714 llvm::Function::ExternalLinkage,
715 "", &TheModule);
716 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
717 return Fn;
718}
719
Chris Lattnerc5b88062008-02-06 05:08:19 +0000720void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
721 // Make sure that this type is translated.
722 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000723}
724
725
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000726/// getBuiltinLibFunction
727llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000728 if (BuiltinID > BuiltinFunctions.size())
729 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000730
Chris Lattner1426fec2007-12-13 00:38:03 +0000731 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
732 // a slot for it.
733 assert(BuiltinID && "Invalid Builtin ID");
734 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000735 if (FunctionSlot)
736 return FunctionSlot;
737
738 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
739
740 // Get the name, skip over the __builtin_ prefix.
741 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
742
743 // Get the type for the builtin.
744 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
745 const llvm::FunctionType *Ty =
746 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
747
748 // FIXME: This has a serious problem with code like this:
749 // void abs() {}
750 // ... __builtin_abs(x);
751 // The two versions of abs will collide. The fix is for the builtin to win,
752 // and for the existing one to be turned into a constantexpr cast of the
753 // builtin. In the case where the existing one is a static function, it
754 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000755 if (llvm::Function *Existing = getModule().getFunction(Name)) {
756 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
757 return FunctionSlot = Existing;
758 assert(Existing == 0 && "FIXME: Name collision");
759 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000760
761 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000762 return FunctionSlot =
763 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
764 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000765}
766
Chris Lattner7acda7c2007-12-18 00:25:38 +0000767llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
768 unsigned NumTys) {
769 return llvm::Intrinsic::getDeclaration(&getModule(),
770 (llvm::Intrinsic::ID)IID, Tys, NumTys);
771}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773llvm::Function *CodeGenModule::getMemCpyFn() {
774 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000775 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
776 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000777}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000778
Eli Friedman0c995092008-05-26 12:59:39 +0000779llvm::Function *CodeGenModule::getMemMoveFn() {
780 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000781 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
782 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000783}
784
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000785llvm::Function *CodeGenModule::getMemSetFn() {
786 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000787 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
788 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000789}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000790
Anders Carlssone3daa762008-11-15 18:54:24 +0000791static void appendFieldAndPadding(CodeGenModule &CGM,
792 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000793 FieldDecl *FieldD, FieldDecl *NextFieldD,
794 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000795 RecordDecl* RD, const llvm::StructType *STy)
796{
797 // Append the field.
798 Fields.push_back(Field);
799
Douglas Gregor44b43212008-12-11 16:49:14 +0000800 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000801
802 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000803 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000804 NextStructFieldNo = STy->getNumElements();
805 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000806 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000807 }
808
809 // Append padding
810 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
811 llvm::Constant *C =
812 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
813
814 Fields.push_back(C);
815 }
816}
817
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000818// We still need to work out the details of handling UTF-16.
819// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000820llvm::Constant *CodeGenModule::
821GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000822 llvm::StringMapEntry<llvm::Constant *> &Entry =
823 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
824
825 if (Entry.getValue())
826 return Entry.getValue();
827
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000828 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
829 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000830
831 if (!CFConstantStringClassRef) {
832 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
833 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000834
835 // FIXME: This is fairly broken if
836 // __CFConstantStringClassReference is already defined, in that it
837 // will get renamed and the user will most likely see an opaque
838 // error message. This is a general issue with relying on
839 // particular names.
840 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000841 new llvm::GlobalVariable(Ty, false,
842 llvm::GlobalVariable::ExternalLinkage, 0,
843 "__CFConstantStringClassReference",
844 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000845
846 // Decay array -> ptr
847 CFConstantStringClassRef =
848 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000849 }
850
Anders Carlssone3daa762008-11-15 18:54:24 +0000851 QualType CFTy = getContext().getCFConstantStringType();
852 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000853
Anders Carlssone3daa762008-11-15 18:54:24 +0000854 const llvm::StructType *STy =
855 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
856
857 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +0000858 RecordDecl::field_iterator Field = CFRD->field_begin();
859
Anders Carlssonc9e20912007-08-21 00:21:21 +0000860 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000861 FieldDecl *CurField = *Field++;
862 FieldDecl *NextField = *Field++;
863 appendFieldAndPadding(*this, Fields, CurField, NextField,
864 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000865
866 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +0000867 CurField = NextField;
868 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000869 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000870 appendFieldAndPadding(*this, Fields, CurField, NextField,
871 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000872
873 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000874 CurField = NextField;
875 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000876 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000877 C = new llvm::GlobalVariable(C->getType(), true,
878 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000879 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +0000880 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +0000881 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
882 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000883
884 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +0000885 CurField = NextField;
886 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000887 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000888 appendFieldAndPadding(*this, Fields, CurField, NextField,
889 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000890
891 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +0000892 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000893 llvm::GlobalVariable *GV =
894 new llvm::GlobalVariable(C->getType(), true,
895 llvm::GlobalVariable::InternalLinkage,
896 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000897
Anders Carlsson0c678292007-11-01 00:41:52 +0000898 GV->setSection("__DATA,__cfstring");
899 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000900
Anders Carlsson0c678292007-11-01 00:41:52 +0000901 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000902}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000903
Daniel Dunbar61432932008-08-13 23:20:05 +0000904/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000905/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000906std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000907 if (E->isWide()) {
908 ErrorUnsupported(E, "wide string");
909 return "FIXME";
910 }
911
Daniel Dunbar1e049762008-08-10 20:25:57 +0000912 const char *StrData = E->getStrData();
913 unsigned Len = E->getByteLength();
914
915 const ConstantArrayType *CAT =
916 getContext().getAsConstantArrayType(E->getType());
917 assert(CAT && "String isn't pointer or array!");
918
919 // Resize the string to the right size
920 // FIXME: What about wchar_t strings?
921 std::string Str(StrData, StrData+Len);
922 uint64_t RealLen = CAT->getSize().getZExtValue();
923 Str.resize(RealLen, '\0');
924
925 return Str;
926}
927
Daniel Dunbar61432932008-08-13 23:20:05 +0000928/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
929/// constant array for the given string literal.
930llvm::Constant *
931CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
932 // FIXME: This can be more efficient.
933 return GetAddrOfConstantString(GetStringForStringLiteral(S));
934}
935
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000936/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000937static llvm::Constant *GenerateStringLiteral(const std::string &str,
938 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000939 CodeGenModule &CGM,
940 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000941 // Create Constant for this string literal. Don't add a '\0'.
942 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000943
944 // Create a global variable for this string
945 C = new llvm::GlobalVariable(C->getType(), constant,
946 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000947 C,
948 GlobalName ? GlobalName : ".str",
949 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000950
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000951 return C;
952}
953
Daniel Dunbar61432932008-08-13 23:20:05 +0000954/// GetAddrOfConstantString - Returns a pointer to a character array
955/// containing the literal. This contents are exactly that of the
956/// given string, i.e. it will not be null terminated automatically;
957/// see GetAddrOfConstantCString. Note that whether the result is
958/// actually a pointer to an LLVM constant depends on
959/// Feature.WriteableStrings.
960///
961/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000962llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
963 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000964 // Don't share any string literals if writable-strings is turned on.
965 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000966 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000967
968 llvm::StringMapEntry<llvm::Constant *> &Entry =
969 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
970
971 if (Entry.getValue())
972 return Entry.getValue();
973
974 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000975 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000976 Entry.setValue(C);
977 return C;
978}
Daniel Dunbar61432932008-08-13 23:20:05 +0000979
980/// GetAddrOfConstantCString - Returns a pointer to a character
981/// array containing the literal and a terminating '\-'
982/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000983llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
984 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +0000985 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +0000986}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000987
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000988/// EmitObjCPropertyImplementations - Emit information for synthesized
989/// properties for an implementation.
990void CodeGenModule::EmitObjCPropertyImplementations(const
991 ObjCImplementationDecl *D) {
992 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
993 e = D->propimpl_end(); i != e; ++i) {
994 ObjCPropertyImplDecl *PID = *i;
995
996 // Dynamic is just for type-checking.
997 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
998 ObjCPropertyDecl *PD = PID->getPropertyDecl();
999
1000 // Determine which methods need to be implemented, some may have
1001 // been overridden. Note that ::isSynthesized is not the method
1002 // we want, that just indicates if the decl came from a
1003 // property. What we want to know is if the method is defined in
1004 // this implementation.
1005 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001006 CodeGenFunction(*this).GenerateObjCGetter(
1007 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001008 if (!PD->isReadOnly() &&
1009 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001010 CodeGenFunction(*this).GenerateObjCSetter(
1011 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001012 }
1013 }
1014}
1015
Daniel Dunbar41071de2008-08-15 23:26:23 +00001016/// EmitTopLevelDecl - Emit code for a single top level declaration.
1017void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1018 // If an error has occurred, stop code generation, but continue
1019 // parsing and semantic analysis (to ensure all warnings and errors
1020 // are emitted).
1021 if (Diags.hasErrorOccurred())
1022 return;
1023
1024 switch (D->getKind()) {
1025 case Decl::Function:
1026 case Decl::Var:
1027 EmitGlobal(cast<ValueDecl>(D));
1028 break;
1029
1030 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001031 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001032 break;
1033
1034 // Objective-C Decls
1035
1036 // Forward declarations, no (immediate) code generation.
1037 case Decl::ObjCClass:
1038 case Decl::ObjCCategory:
1039 case Decl::ObjCForwardProtocol:
1040 case Decl::ObjCInterface:
1041 break;
1042
1043 case Decl::ObjCProtocol:
1044 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1045 break;
1046
1047 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001048 // Categories have properties but don't support synthesize so we
1049 // can ignore them here.
1050
Daniel Dunbar41071de2008-08-15 23:26:23 +00001051 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1052 break;
1053
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001054 case Decl::ObjCImplementation: {
1055 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1056 EmitObjCPropertyImplementations(OMD);
1057 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001058 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001059 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001060 case Decl::ObjCMethod: {
1061 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1062 // If this is not a prototype, emit the body.
1063 if (OMD->getBody())
1064 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1065 break;
1066 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001067 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001068 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001069 break;
1070
1071 case Decl::LinkageSpec: {
1072 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1073 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001074 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001075 // FIXME: implement C++ linkage, C linkage works mostly by C
1076 // language reuse already.
1077 break;
1078 }
1079
1080 case Decl::FileScopeAsm: {
1081 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1082 std::string AsmString(AD->getAsmString()->getStrData(),
1083 AD->getAsmString()->getByteLength());
1084
1085 const std::string &S = getModule().getModuleInlineAsm();
1086 if (S.empty())
1087 getModule().setModuleInlineAsm(AsmString);
1088 else
1089 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1090 break;
1091 }
1092
1093 default:
1094 // Make sure we handled everything we should, every other kind is
1095 // a non-top-level decl. FIXME: Would be nice to have an
1096 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1097 // that easily.
1098 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1099 }
1100}
1101