blob: 3e146215f487939143f8bed9a24cc6fbea639a42 [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
75 // See if there is a conflict against a function.
76 llvm::Function *Conflict = TheModule.getFunction(Name);
77 if (Conflict) {
78 // Decide which version to take. If the conflict is a definition
79 // we are forced to take that, otherwise assume the runtime
80 // knows best.
81 if (!Conflict->isDeclaration()) {
82 llvm::Value *Casted =
83 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
84 Fn->replaceAllUsesWith(Casted);
85 Fn->eraseFromParent();
86 } else {
87 Fn->takeName(Conflict);
88 llvm::Value *Casted =
89 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
90 Conflict->replaceAllUsesWith(Casted);
91 Conflict->eraseFromParent();
92 }
93 } else {
94 // FIXME: There still may be conflicts with aliases and
95 // variables.
96 Fn->setName(Name);
97 }
98 }
99}
100
Daniel Dunbar488e9932008-08-16 00:56:44 +0000101/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000102/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000103void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
104 bool OmitOnError) {
105 if (OmitOnError && getDiags().hasErrorOccurred())
106 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000107 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000108 "cannot codegen this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000109 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000110 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
111 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000112}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000113
Daniel Dunbar488e9932008-08-16 00:56:44 +0000114/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000115/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000116void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
117 bool OmitOnError) {
118 if (OmitOnError && getDiags().hasErrorOccurred())
119 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000120 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000121 "cannot codegen this %0 yet");
122 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000123 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000124}
125
Daniel Dunbar41071de2008-08-15 23:26:23 +0000126/// setGlobalVisibility - Set the visibility for the given LLVM
127/// GlobalValue according to the given clang AST visibility value.
128static void setGlobalVisibility(llvm::GlobalValue *GV,
129 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000130 switch (Vis) {
131 default: assert(0 && "Unknown visibility!");
132 case VisibilityAttr::DefaultVisibility:
133 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
134 break;
135 case VisibilityAttr::HiddenVisibility:
136 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
137 break;
138 case VisibilityAttr::ProtectedVisibility:
139 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
140 break;
141 }
142}
143
Chris Lattner6d397602008-03-14 17:18:18 +0000144/// AddGlobalCtor - Add a function to the list that will be called before
145/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000146void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000147 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000148 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000149}
150
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000151/// AddGlobalDtor - Add a function to the list that will be called
152/// when the module is unloaded.
153void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
154 // TODO: Type coercion of void()* types.
155 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
156}
157
158void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
159 // Ctor function type is void()*.
160 llvm::FunctionType* CtorFTy =
161 llvm::FunctionType::get(llvm::Type::VoidTy,
162 std::vector<const llvm::Type*>(),
163 false);
164 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
165
166 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000167 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000168 llvm::StructType::get(llvm::Type::Int32Ty,
169 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000170
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000171 // Construct the constructor and destructor arrays.
172 std::vector<llvm::Constant*> Ctors;
173 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
174 std::vector<llvm::Constant*> S;
175 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
176 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
177 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000178 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000179
180 if (!Ctors.empty()) {
181 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
182 new llvm::GlobalVariable(AT, false,
183 llvm::GlobalValue::AppendingLinkage,
184 llvm::ConstantArray::get(AT, Ctors),
185 GlobalName,
186 &TheModule);
187 }
Chris Lattner6d397602008-03-14 17:18:18 +0000188}
189
Nate Begeman532485c2008-04-18 23:43:57 +0000190void CodeGenModule::EmitAnnotations() {
191 if (Annotations.empty())
192 return;
193
194 // Create a new global variable for the ConstantStruct in the Module.
195 llvm::Constant *Array =
196 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
197 Annotations.size()),
198 Annotations);
199 llvm::GlobalValue *gv =
200 new llvm::GlobalVariable(Array->getType(), false,
201 llvm::GlobalValue::AppendingLinkage, Array,
202 "llvm.global.annotations", &TheModule);
203 gv->setSection("llvm.metadata");
204}
205
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000206static void SetGlobalValueAttributes(const Decl *D,
207 bool IsInternal,
208 bool IsInline,
Daniel Dunbar219df662008-09-08 23:44:31 +0000209 llvm::GlobalValue *GV,
210 bool ForDefinition) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000211 // TODO: Set up linkage and many other things. Note, this is a simple
212 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000213 if (!ForDefinition) {
214 // Only a few attributes are set on declarations.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000215 if (D->getAttr<DLLImportAttr>())
216 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000217 } else {
218 if (IsInternal) {
219 GV->setLinkage(llvm::Function::InternalLinkage);
220 } else {
221 if (D->getAttr<DLLImportAttr>())
222 GV->setLinkage(llvm::Function::DLLImportLinkage);
223 else if (D->getAttr<DLLExportAttr>())
224 GV->setLinkage(llvm::Function::DLLExportLinkage);
225 else if (D->getAttr<WeakAttr>() || IsInline)
226 GV->setLinkage(llvm::Function::WeakLinkage);
227 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000228 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000229
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000230 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000231 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000232 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000233
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000234 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000235 // Prefaced with special LLVM marker to indicate that the name
236 // should not be munged.
237 GV->setName("\01" + ALA->getLabel());
238 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000239}
240
Devang Patel761d7f72008-09-25 21:02:23 +0000241void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000242 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000243 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000244 AttributeListType AttributeList;
245 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
246 AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000247
Devang Patel761d7f72008-09-25 21:02:23 +0000248 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
249 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000250
251 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000252 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000253 F->setCallingConv(llvm::CallingConv::X86_FastCall);
254
255 if (D->getAttr<StdCallAttr>())
256 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000257}
258
259/// SetFunctionAttributesForDefinition - Set function attributes
260/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000261void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
262 llvm::Function *F) {
263 if (isa<ObjCMethodDecl>(D)) {
264 SetGlobalValueAttributes(D, true, false, F, true);
265 } else {
266 const FunctionDecl *FD = cast<FunctionDecl>(D);
267 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
268 FD->isInline(), F, true);
269 }
270
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000271 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000272 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000273
274 if (D->getAttr<AlwaysInlineAttr>())
275 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000276}
277
278void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
279 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000280 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000281
Daniel Dunbar219df662008-09-08 23:44:31 +0000282 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000283}
284
285void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
286 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000287 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000288
Daniel Dunbar219df662008-09-08 23:44:31 +0000289 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
290 FD->isInline(), F, false);
291}
292
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000293
Daniel Dunbar219df662008-09-08 23:44:31 +0000294void CodeGenModule::EmitAliases() {
295 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
296 const FunctionDecl *D = Aliases[i];
297 const AliasAttr *AA = D->getAttr<AliasAttr>();
298
299 // This is something of a hack, if the FunctionDecl got overridden
300 // then its attributes will be moved to the new declaration. In
301 // this case the current decl has no alias attribute, but we will
302 // eventually see it.
303 if (!AA)
304 continue;
305
306 const std::string& aliaseeName = AA->getAliasee();
307 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
308 if (!aliasee) {
309 // FIXME: This isn't unsupported, this is just an error, which
310 // sema should catch, but...
311 ErrorUnsupported(D, "alias referencing a missing function");
312 continue;
313 }
314
315 llvm::GlobalValue *GA =
316 new llvm::GlobalAlias(aliasee->getType(),
317 llvm::Function::ExternalLinkage,
318 D->getName(),
319 aliasee,
320 &getModule());
321
322 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
323 if (Entry) {
324 // If we created a dummy function for this then replace it.
325 GA->takeName(Entry);
326
327 llvm::Value *Casted =
328 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
329 Entry->replaceAllUsesWith(Casted);
330 Entry->eraseFromParent();
331
332 Entry = GA;
333 }
334
335 // Alias should never be internal or inline.
336 SetGlobalValueAttributes(D, false, false, GA, true);
337 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000338}
339
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000340void CodeGenModule::EmitStatics() {
341 // Emit code for each used static decl encountered. Since a previously unused
342 // static decl may become used during the generation of code for a static
343 // function, iterate until no changes are made.
344 bool Changed;
345 do {
346 Changed = false;
347 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000348 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000349
350 // Check if we have used a decl with the same name
351 // FIXME: The AST should have some sort of aggregate decls or
352 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000353 // FIXME: This is missing some important cases. For example, we
354 // need to check for uses in an alias and in a constructor.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000355 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbara735ad82008-08-06 00:03:29 +0000356 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000357
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000358 // Emit the definition.
359 EmitGlobalDefinition(D);
360
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000361 // Erase the used decl from the list.
362 StaticDecls[i] = StaticDecls.back();
363 StaticDecls.pop_back();
364 --i;
365 --e;
366
367 // Remember that we made a change.
368 Changed = true;
369 }
370 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000371}
372
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000373/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
374/// annotation information for a given GlobalValue. The annotation struct is
375/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000376/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000377/// created from the AnnotateAttr's annotation. The third field is a constant
378/// string containing the name of the translation unit. The fourth field is
379/// the line number in the file of the annotated value declaration.
380///
381/// FIXME: this does not unique the annotation string constants, as llvm-gcc
382/// appears to.
383///
384llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
385 const AnnotateAttr *AA,
386 unsigned LineNo) {
387 llvm::Module *M = &getModule();
388
389 // get [N x i8] constants for the annotation string, and the filename string
390 // which are the 2nd and 3rd elements of the global annotation structure.
391 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
392 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
393 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
394 true);
395
396 // Get the two global values corresponding to the ConstantArrays we just
397 // created to hold the bytes of the strings.
398 llvm::GlobalValue *annoGV =
399 new llvm::GlobalVariable(anno->getType(), false,
400 llvm::GlobalValue::InternalLinkage, anno,
401 GV->getName() + ".str", M);
402 // translation unit name string, emitted into the llvm.metadata section.
403 llvm::GlobalValue *unitGV =
404 new llvm::GlobalVariable(unit->getType(), false,
405 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
406
407 // Create the ConstantStruct that is the global annotion.
408 llvm::Constant *Fields[4] = {
409 llvm::ConstantExpr::getBitCast(GV, SBP),
410 llvm::ConstantExpr::getBitCast(annoGV, SBP),
411 llvm::ConstantExpr::getBitCast(unitGV, SBP),
412 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
413 };
414 return llvm::ConstantStruct::get(Fields, 4, false);
415}
416
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000417void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
418 bool isDef, isStatic;
419
420 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000421 // Aliases are deferred until code for everything else has been
422 // emitted.
423 if (FD->getAttr<AliasAttr>()) {
424 assert(!FD->isThisDeclarationADefinition() &&
425 "Function alias cannot have a definition!");
426 Aliases.push_back(FD);
427 return;
428 }
429
430 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000431 isStatic = FD->getStorageClass() == FunctionDecl::Static;
432 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
433 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
434
435 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
436 isStatic = VD->getStorageClass() == VarDecl::Static;
437 } else {
438 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000439 return;
440 }
441
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000442 // Forward declarations are emitted lazily on first use.
443 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000444 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000445
446 // If the global is a static, defer code generation until later so
447 // we can easily omit unused statics.
448 if (isStatic) {
449 StaticDecls.push_back(Global);
450 return;
451 }
452
453 // Otherwise emit the definition.
454 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000455}
456
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000457void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
458 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
459 EmitGlobalFunctionDefinition(FD);
460 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
461 EmitGlobalVarDefinition(VD);
462 } else {
463 assert(0 && "Invalid argument to EmitGlobalDefinition()");
464 }
465}
466
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000467 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000468 assert(D->hasGlobalStorage() && "Not a global variable");
469
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000470 QualType ASTTy = D->getType();
471 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000472 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000473
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000474 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000475 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000476 if (!Entry)
477 Entry = new llvm::GlobalVariable(Ty, false,
478 llvm::GlobalValue::ExternalLinkage,
479 0, D->getName(), &getModule(), 0,
480 ASTTy.getAddressSpace());
481
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000482 // Make sure the result is of the correct type.
483 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000484}
485
486void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000487 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000488 QualType ASTTy = D->getType();
489 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000490
Chris Lattner8f32f712007-07-14 00:23:28 +0000491 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000492 // This is a tentative definition; tentative definitions are
493 // implicitly initialized with { 0 }
494 const llvm::Type* InitTy;
495 if (ASTTy->isIncompleteArrayType()) {
496 // An incomplete array is normally [ TYPE x 0 ], but we need
497 // to fix it to [ TYPE x 1 ].
498 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
499 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
500 } else {
501 InitTy = VarTy;
502 }
503 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000504 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000505 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000506 }
507 const llvm::Type* InitType = Init->getType();
508
Daniel Dunbar90db8822008-08-25 06:18:57 +0000509 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000510 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
511
Eli Friedman77ba7082008-05-30 19:50:47 +0000512 if (!GV) {
513 GV = new llvm::GlobalVariable(InitType, false,
514 llvm::GlobalValue::ExternalLinkage,
515 0, D->getName(), &getModule(), 0,
516 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000517 } else if (GV->getType() !=
518 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000519 // We have a definition after a prototype with the wrong type.
520 // We must make a new GlobalVariable* and update everything that used OldGV
521 // (a declaration or tentative definition) with the new GlobalVariable*
522 // (which will be a definition).
523 //
524 // This happens if there is a prototype for a global (e.g. "extern int x[];")
525 // and then a definition of a different type (e.g. "int x[10];"). This also
526 // happens when an initializer has a different type from the type of the
527 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000528 //
529 // FIXME: This also ends up happening if there's a definition followed by
530 // a tentative definition! (Although Sema rejects that construct
531 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000532
533 // Save the old global
534 llvm::GlobalVariable *OldGV = GV;
535
536 // Make a new global with the correct type
537 GV = new llvm::GlobalVariable(InitType, false,
538 llvm::GlobalValue::ExternalLinkage,
539 0, D->getName(), &getModule(), 0,
540 ASTTy.getAddressSpace());
541 // Steal the name of the old global
542 GV->takeName(OldGV);
543
544 // Replace all uses of the old global with the new global
545 llvm::Constant *NewPtrForOldDecl =
546 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
547 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000548
549 // Erase the old global, since it is no longer used.
550 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000551 }
Devang Patel8e53e722007-10-26 16:31:40 +0000552
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000553 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000554
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000555 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
556 SourceManager &SM = Context.getSourceManager();
557 AddAnnotation(EmitAnnotateAttr(GV, AA,
558 SM.getLogicalLineNumber(D->getLocation())));
559 }
560
Chris Lattner88a69ad2007-07-13 05:13:43 +0000561 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000562 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000563
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000564 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
565 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000566 if (const IncompleteArrayType* IAT =
567 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000568 Align = Context.getTypeAlign(IAT->getElementType());
569 else
570 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000571 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
572 Align = std::max(Align, AA->getAlignment());
573 }
574 GV->setAlignment(Align / 8);
575
Chris Lattnerddee4232008-03-03 03:28:21 +0000576 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000577 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000578 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000579
580 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
581 // Prefaced with special LLVM marker to indicate that the name
582 // should not be munged.
583 GV->setName("\01" + ALA->getLabel());
584 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000585
586 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000587 if (D->getStorageClass() == VarDecl::Static)
588 GV->setLinkage(llvm::Function::InternalLinkage);
589 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000590 GV->setLinkage(llvm::Function::DLLImportLinkage);
591 else if (D->getAttr<DLLExportAttr>())
592 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000593 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000594 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000595 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000596 // FIXME: This isn't right. This should handle common linkage and other
597 // stuff.
598 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000599 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000600 case VarDecl::Auto:
601 case VarDecl::Register:
602 assert(0 && "Can't have auto or register globals");
603 case VarDecl::None:
604 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000605 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000606 break;
607 case VarDecl::Extern:
608 case VarDecl::PrivateExtern:
609 // todo: common
610 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000611 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000612 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000613
614 // Emit global variable debug information.
615 CGDebugInfo *DI = getDebugInfo();
616 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000617 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000618 DI->EmitGlobalVariable(GV, D);
619 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000620}
Reid Spencer5f016e22007-07-11 17:01:13 +0000621
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000622llvm::GlobalValue *
623CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000624 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
625 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
626 llvm::Function::ExternalLinkage,
627 D->getName(), &getModule());
628 SetFunctionAttributes(D, F);
629 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000630}
631
632llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000633 QualType ASTTy = D->getType();
634 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
635 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000636
637 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000638 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000639 if (!Entry)
640 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000641
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000642 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000643}
644
645void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000646 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000647 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000648 Entry = EmitForwardFunctionDefinition(D);
649 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000650 // If the types mismatch then we have to rewrite the definition.
651 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
652 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000653 // Otherwise, we have a definition after a prototype with the wrong type.
654 // F is the Function* for the one with the wrong type, we must make a new
655 // Function* and update everything that used F (a declaration) with the new
656 // Function* (which will be a definition).
657 //
658 // This happens if there is a prototype for a function (e.g. "int f()") and
659 // then a definition of a different type (e.g. "int f(int x)"). Start by
660 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000661 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
662 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000663
664 // Replace uses of F with the Function we will endow with a body.
665 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000666 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
667 Entry->replaceAllUsesWith(NewPtrForOldDecl);
668
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000669 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000670 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000671 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000672
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000673 Entry = NewFn;
674 }
675 }
676
Daniel Dunbar219df662008-09-08 23:44:31 +0000677 llvm::Function *Fn = cast<llvm::Function>(Entry);
678 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000679
Daniel Dunbar219df662008-09-08 23:44:31 +0000680 SetFunctionAttributesForDefinition(D, Fn);
681
682 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
683 AddGlobalCtor(Fn, CA->getPriority());
684 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
685 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000686 }
687}
688
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000689llvm::Function *
690CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
691 const std::string &Name) {
692 llvm::Function *Fn = llvm::Function::Create(FTy,
693 llvm::Function::ExternalLinkage,
694 "", &TheModule);
695 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
696 return Fn;
697}
698
Chris Lattnerc5b88062008-02-06 05:08:19 +0000699void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
700 // Make sure that this type is translated.
701 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000702}
703
704
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000705/// getBuiltinLibFunction
706llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000707 if (BuiltinID > BuiltinFunctions.size())
708 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000709
Chris Lattner1426fec2007-12-13 00:38:03 +0000710 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
711 // a slot for it.
712 assert(BuiltinID && "Invalid Builtin ID");
713 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000714 if (FunctionSlot)
715 return FunctionSlot;
716
717 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
718
719 // Get the name, skip over the __builtin_ prefix.
720 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
721
722 // Get the type for the builtin.
723 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
724 const llvm::FunctionType *Ty =
725 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
726
727 // FIXME: This has a serious problem with code like this:
728 // void abs() {}
729 // ... __builtin_abs(x);
730 // The two versions of abs will collide. The fix is for the builtin to win,
731 // and for the existing one to be turned into a constantexpr cast of the
732 // builtin. In the case where the existing one is a static function, it
733 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000734 if (llvm::Function *Existing = getModule().getFunction(Name)) {
735 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
736 return FunctionSlot = Existing;
737 assert(Existing == 0 && "FIXME: Name collision");
738 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000739
740 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000741 return FunctionSlot =
742 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
743 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000744}
745
Chris Lattner7acda7c2007-12-18 00:25:38 +0000746llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
747 unsigned NumTys) {
748 return llvm::Intrinsic::getDeclaration(&getModule(),
749 (llvm::Intrinsic::ID)IID, Tys, NumTys);
750}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752llvm::Function *CodeGenModule::getMemCpyFn() {
753 if (MemCpyFn) return MemCpyFn;
754 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000755 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 default: assert(0 && "Unknown ptr width");
757 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
758 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
759 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000760 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000761}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000762
Eli Friedman0c995092008-05-26 12:59:39 +0000763llvm::Function *CodeGenModule::getMemMoveFn() {
764 if (MemMoveFn) return MemMoveFn;
765 llvm::Intrinsic::ID IID;
766 switch (Context.Target.getPointerWidth(0)) {
767 default: assert(0 && "Unknown ptr width");
768 case 32: IID = llvm::Intrinsic::memmove_i32; break;
769 case 64: IID = llvm::Intrinsic::memmove_i64; break;
770 }
771 return MemMoveFn = getIntrinsic(IID);
772}
773
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000774llvm::Function *CodeGenModule::getMemSetFn() {
775 if (MemSetFn) return MemSetFn;
776 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000777 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000778 default: assert(0 && "Unknown ptr width");
779 case 32: IID = llvm::Intrinsic::memset_i32; break;
780 case 64: IID = llvm::Intrinsic::memset_i64; break;
781 }
782 return MemSetFn = getIntrinsic(IID);
783}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000784
Anders Carlssone3daa762008-11-15 18:54:24 +0000785static void appendFieldAndPadding(CodeGenModule &CGM,
786 std::vector<llvm::Constant*>& Fields,
787 int FieldNo, llvm::Constant* Field,
788 RecordDecl* RD, const llvm::StructType *STy)
789{
790 // Append the field.
791 Fields.push_back(Field);
792
793 int StructFieldNo =
794 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo));
795
796 int NextStructFieldNo;
797 if (FieldNo + 1 == RD->getNumMembers()) {
798 NextStructFieldNo = STy->getNumElements();
799 } else {
800 NextStructFieldNo =
801 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo + 1));
802 }
803
804 // Append padding
805 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
806 llvm::Constant *C =
807 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
808
809 Fields.push_back(C);
810 }
811}
812
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000813// We still need to work out the details of handling UTF-16.
814// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000815llvm::Constant *CodeGenModule::
816GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000817 llvm::StringMapEntry<llvm::Constant *> &Entry =
818 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
819
820 if (Entry.getValue())
821 return Entry.getValue();
822
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000823 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
824 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000825
826 if (!CFConstantStringClassRef) {
827 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
828 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000829
830 // FIXME: This is fairly broken if
831 // __CFConstantStringClassReference is already defined, in that it
832 // will get renamed and the user will most likely see an opaque
833 // error message. This is a general issue with relying on
834 // particular names.
835 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000836 new llvm::GlobalVariable(Ty, false,
837 llvm::GlobalVariable::ExternalLinkage, 0,
838 "__CFConstantStringClassReference",
839 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000840
841 // Decay array -> ptr
842 CFConstantStringClassRef =
843 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000844 }
845
Anders Carlssone3daa762008-11-15 18:54:24 +0000846 QualType CFTy = getContext().getCFConstantStringType();
847 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000848
Anders Carlssone3daa762008-11-15 18:54:24 +0000849 const llvm::StructType *STy =
850 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
851
852 std::vector<llvm::Constant*> Fields;
853
854
Anders Carlssonc9e20912007-08-21 00:21:21 +0000855 // Class pointer.
Anders Carlssone3daa762008-11-15 18:54:24 +0000856 appendFieldAndPadding(*this, Fields, 0, CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000857
858 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000859 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Anders Carlssone3daa762008-11-15 18:54:24 +0000860 appendFieldAndPadding(*this, Fields, 1, llvm::ConstantInt::get(Ty, 0x07C8),
861 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000862
863 // String pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000864 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000865 C = new llvm::GlobalVariable(C->getType(), true,
866 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000867 C, ".str", &getModule());
868 appendFieldAndPadding(*this, Fields, 2,
869 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
870 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000871
872 // String length.
873 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlssone3daa762008-11-15 18:54:24 +0000874 appendFieldAndPadding(*this, Fields, 3, llvm::ConstantInt::get(Ty, str.length()),
875 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000876
877 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +0000878 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000879 llvm::GlobalVariable *GV =
880 new llvm::GlobalVariable(C->getType(), true,
881 llvm::GlobalVariable::InternalLinkage,
882 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000883
Anders Carlsson0c678292007-11-01 00:41:52 +0000884 GV->setSection("__DATA,__cfstring");
885 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000886
Anders Carlsson0c678292007-11-01 00:41:52 +0000887 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000888}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000889
Daniel Dunbar61432932008-08-13 23:20:05 +0000890/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000891/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000892std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000893 if (E->isWide()) {
894 ErrorUnsupported(E, "wide string");
895 return "FIXME";
896 }
897
Daniel Dunbar1e049762008-08-10 20:25:57 +0000898 const char *StrData = E->getStrData();
899 unsigned Len = E->getByteLength();
900
901 const ConstantArrayType *CAT =
902 getContext().getAsConstantArrayType(E->getType());
903 assert(CAT && "String isn't pointer or array!");
904
905 // Resize the string to the right size
906 // FIXME: What about wchar_t strings?
907 std::string Str(StrData, StrData+Len);
908 uint64_t RealLen = CAT->getSize().getZExtValue();
909 Str.resize(RealLen, '\0');
910
911 return Str;
912}
913
Daniel Dunbar61432932008-08-13 23:20:05 +0000914/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
915/// constant array for the given string literal.
916llvm::Constant *
917CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
918 // FIXME: This can be more efficient.
919 return GetAddrOfConstantString(GetStringForStringLiteral(S));
920}
921
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000922/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000923static llvm::Constant *GenerateStringLiteral(const std::string &str,
924 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000925 CodeGenModule &CGM,
926 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000927 // Create Constant for this string literal. Don't add a '\0'.
928 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000929
930 // Create a global variable for this string
931 C = new llvm::GlobalVariable(C->getType(), constant,
932 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000933 C,
934 GlobalName ? GlobalName : ".str",
935 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000936
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000937 return C;
938}
939
Daniel Dunbar61432932008-08-13 23:20:05 +0000940/// GetAddrOfConstantString - Returns a pointer to a character array
941/// containing the literal. This contents are exactly that of the
942/// given string, i.e. it will not be null terminated automatically;
943/// see GetAddrOfConstantCString. Note that whether the result is
944/// actually a pointer to an LLVM constant depends on
945/// Feature.WriteableStrings.
946///
947/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000948llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
949 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000950 // Don't share any string literals if writable-strings is turned on.
951 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000952 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000953
954 llvm::StringMapEntry<llvm::Constant *> &Entry =
955 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
956
957 if (Entry.getValue())
958 return Entry.getValue();
959
960 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000961 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000962 Entry.setValue(C);
963 return C;
964}
Daniel Dunbar61432932008-08-13 23:20:05 +0000965
966/// GetAddrOfConstantCString - Returns a pointer to a character
967/// array containing the literal and a terminating '\-'
968/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000969llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
970 const char *GlobalName){
971 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +0000972}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000973
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000974/// EmitObjCPropertyImplementations - Emit information for synthesized
975/// properties for an implementation.
976void CodeGenModule::EmitObjCPropertyImplementations(const
977 ObjCImplementationDecl *D) {
978 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
979 e = D->propimpl_end(); i != e; ++i) {
980 ObjCPropertyImplDecl *PID = *i;
981
982 // Dynamic is just for type-checking.
983 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
984 ObjCPropertyDecl *PD = PID->getPropertyDecl();
985
986 // Determine which methods need to be implemented, some may have
987 // been overridden. Note that ::isSynthesized is not the method
988 // we want, that just indicates if the decl came from a
989 // property. What we want to know is if the method is defined in
990 // this implementation.
991 if (!D->getInstanceMethod(PD->getGetterName()))
992 CodeGenFunction(*this).GenerateObjCGetter(PID);
993 if (!PD->isReadOnly() &&
994 !D->getInstanceMethod(PD->getSetterName()))
995 CodeGenFunction(*this).GenerateObjCSetter(PID);
996 }
997 }
998}
999
Daniel Dunbar41071de2008-08-15 23:26:23 +00001000/// EmitTopLevelDecl - Emit code for a single top level declaration.
1001void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1002 // If an error has occurred, stop code generation, but continue
1003 // parsing and semantic analysis (to ensure all warnings and errors
1004 // are emitted).
1005 if (Diags.hasErrorOccurred())
1006 return;
1007
1008 switch (D->getKind()) {
1009 case Decl::Function:
1010 case Decl::Var:
1011 EmitGlobal(cast<ValueDecl>(D));
1012 break;
1013
1014 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001015 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001016 break;
1017
1018 // Objective-C Decls
1019
1020 // Forward declarations, no (immediate) code generation.
1021 case Decl::ObjCClass:
1022 case Decl::ObjCCategory:
1023 case Decl::ObjCForwardProtocol:
1024 case Decl::ObjCInterface:
1025 break;
1026
1027 case Decl::ObjCProtocol:
1028 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1029 break;
1030
1031 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001032 // Categories have properties but don't support synthesize so we
1033 // can ignore them here.
1034
Daniel Dunbar41071de2008-08-15 23:26:23 +00001035 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1036 break;
1037
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001038 case Decl::ObjCImplementation: {
1039 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1040 EmitObjCPropertyImplementations(OMD);
1041 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001042 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001043 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001044 case Decl::ObjCMethod: {
1045 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1046 // If this is not a prototype, emit the body.
1047 if (OMD->getBody())
1048 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1049 break;
1050 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001051 case Decl::ObjCCompatibleAlias:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001052 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001053 break;
1054
1055 case Decl::LinkageSpec: {
1056 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1057 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001058 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001059 // FIXME: implement C++ linkage, C linkage works mostly by C
1060 // language reuse already.
1061 break;
1062 }
1063
1064 case Decl::FileScopeAsm: {
1065 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1066 std::string AsmString(AD->getAsmString()->getStrData(),
1067 AD->getAsmString()->getByteLength());
1068
1069 const std::string &S = getModule().getModuleInlineAsm();
1070 if (S.empty())
1071 getModule().setModuleInlineAsm(AsmString);
1072 else
1073 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1074 break;
1075 }
1076
1077 default:
1078 // Make sure we handled everything we should, every other kind is
1079 // a non-top-level decl. FIXME: Would be nice to have an
1080 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1081 // that easily.
1082 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1083 }
1084}
1085