blob: d7d732997b603a61568c292e2ead614d753d0987 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000021#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000022#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000025#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattnerdb6be562007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000035 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000036 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000037 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000038 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000039
40 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000041 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000042 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000046 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar566a6502008-09-08 23:44:31 +000059 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000060 if (Runtime)
61 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
62 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000063 EmitCtorList(GlobalCtors, "llvm.global_ctors");
64 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000065 EmitAnnotations();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000066 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000067}
Chris Lattner4b009652007-07-25 00:24:17 +000068
Daniel Dunbar18c2ec62008-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 Dunbar9503b782008-08-16 00:56:44 +0000101/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000102/// specified stmt yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +0000107 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000108 "cannot codegen this %0 yet");
109 SourceRange Range = S->getSourceRange();
110 std::string Msg = Type;
Chris Lattnerb034e282008-11-18 04:56:44 +0000111 const std::string *Strs[] = { &Msg };
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000112 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Chris Lattnerb034e282008-11-18 04:56:44 +0000113 Strs, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000114}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000115
Daniel Dunbar9503b782008-08-16 00:56:44 +0000116/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000117/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000118void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
119 bool OmitOnError) {
120 if (OmitOnError && getDiags().hasErrorOccurred())
121 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000122 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +0000123 "cannot codegen this %0 yet");
124 std::string Msg = Type;
Chris Lattnerb034e282008-11-18 04:56:44 +0000125 const std::string *Strs[] = { &Msg };
126 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, Strs, 1);
Chris Lattner806a5f52008-01-12 07:05:38 +0000127}
128
Daniel Dunbar27250d32008-08-15 23:26:23 +0000129/// setGlobalVisibility - Set the visibility for the given LLVM
130/// GlobalValue according to the given clang AST visibility value.
131static void setGlobalVisibility(llvm::GlobalValue *GV,
132 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000133 switch (Vis) {
134 default: assert(0 && "Unknown visibility!");
135 case VisibilityAttr::DefaultVisibility:
136 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
137 break;
138 case VisibilityAttr::HiddenVisibility:
139 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
140 break;
141 case VisibilityAttr::ProtectedVisibility:
142 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
143 break;
144 }
145}
146
Chris Lattner753d2592008-03-14 17:18:18 +0000147/// AddGlobalCtor - Add a function to the list that will be called before
148/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000149void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000150 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000151 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000152}
153
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000154/// AddGlobalDtor - Add a function to the list that will be called
155/// when the module is unloaded.
156void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
157 // TODO: Type coercion of void()* types.
158 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
159}
160
161void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
162 // Ctor function type is void()*.
163 llvm::FunctionType* CtorFTy =
164 llvm::FunctionType::get(llvm::Type::VoidTy,
165 std::vector<const llvm::Type*>(),
166 false);
167 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
168
169 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000170 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000171 llvm::StructType::get(llvm::Type::Int32Ty,
172 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000173
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000174 // Construct the constructor and destructor arrays.
175 std::vector<llvm::Constant*> Ctors;
176 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
177 std::vector<llvm::Constant*> S;
178 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
179 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
180 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000181 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000182
183 if (!Ctors.empty()) {
184 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
185 new llvm::GlobalVariable(AT, false,
186 llvm::GlobalValue::AppendingLinkage,
187 llvm::ConstantArray::get(AT, Ctors),
188 GlobalName,
189 &TheModule);
190 }
Chris Lattner753d2592008-03-14 17:18:18 +0000191}
192
Nate Begeman52da5c72008-04-18 23:43:57 +0000193void CodeGenModule::EmitAnnotations() {
194 if (Annotations.empty())
195 return;
196
197 // Create a new global variable for the ConstantStruct in the Module.
198 llvm::Constant *Array =
199 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
200 Annotations.size()),
201 Annotations);
202 llvm::GlobalValue *gv =
203 new llvm::GlobalVariable(Array->getType(), false,
204 llvm::GlobalValue::AppendingLinkage, Array,
205 "llvm.global.annotations", &TheModule);
206 gv->setSection("llvm.metadata");
207}
208
Daniel Dunbara8f02052008-09-08 21:33:45 +0000209static void SetGlobalValueAttributes(const Decl *D,
210 bool IsInternal,
211 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000212 llvm::GlobalValue *GV,
213 bool ForDefinition) {
Nuno Lopes78534382008-06-08 15:45:52 +0000214 // TODO: Set up linkage and many other things. Note, this is a simple
215 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000216 if (!ForDefinition) {
217 // Only a few attributes are set on declarations.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000218 if (D->getAttr<DLLImportAttr>())
219 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000220 } else {
221 if (IsInternal) {
222 GV->setLinkage(llvm::Function::InternalLinkage);
223 } else {
224 if (D->getAttr<DLLImportAttr>())
225 GV->setLinkage(llvm::Function::DLLImportLinkage);
226 else if (D->getAttr<DLLExportAttr>())
227 GV->setLinkage(llvm::Function::DLLExportLinkage);
228 else if (D->getAttr<WeakAttr>() || IsInline)
229 GV->setLinkage(llvm::Function::WeakLinkage);
230 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000231 }
Nuno Lopes78534382008-06-08 15:45:52 +0000232
Daniel Dunbara8f02052008-09-08 21:33:45 +0000233 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000234 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000235 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000236
Daniel Dunbara8f02052008-09-08 21:33:45 +0000237 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000238 // Prefaced with special LLVM marker to indicate that the name
239 // should not be munged.
240 GV->setName("\01" + ALA->getLabel());
241 }
Nuno Lopes78534382008-06-08 15:45:52 +0000242}
243
Devang Patela85a9ef2008-09-25 21:02:23 +0000244void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000245 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000246 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000247 AttributeListType AttributeList;
248 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
249 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000250
Devang Patela85a9ef2008-09-25 21:02:23 +0000251 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
252 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000253
254 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000255 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000256 F->setCallingConv(llvm::CallingConv::X86_FastCall);
257
258 if (D->getAttr<StdCallAttr>())
259 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000260}
261
262/// SetFunctionAttributesForDefinition - Set function attributes
263/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000264void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
265 llvm::Function *F) {
266 if (isa<ObjCMethodDecl>(D)) {
267 SetGlobalValueAttributes(D, true, false, F, true);
268 } else {
269 const FunctionDecl *FD = cast<FunctionDecl>(D);
270 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
271 FD->isInline(), F, true);
272 }
273
Daniel Dunbarf2787002008-09-04 23:41:35 +0000274 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000275 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000276
277 if (D->getAttr<AlwaysInlineAttr>())
278 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000279}
280
281void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
282 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000283 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000284
Daniel Dunbar566a6502008-09-08 23:44:31 +0000285 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000286}
287
288void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
289 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000290 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000291
Daniel Dunbar566a6502008-09-08 23:44:31 +0000292 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
293 FD->isInline(), F, false);
294}
295
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000296
Daniel Dunbar566a6502008-09-08 23:44:31 +0000297void CodeGenModule::EmitAliases() {
298 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
299 const FunctionDecl *D = Aliases[i];
300 const AliasAttr *AA = D->getAttr<AliasAttr>();
301
302 // This is something of a hack, if the FunctionDecl got overridden
303 // then its attributes will be moved to the new declaration. In
304 // this case the current decl has no alias attribute, but we will
305 // eventually see it.
306 if (!AA)
307 continue;
308
309 const std::string& aliaseeName = AA->getAliasee();
310 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
311 if (!aliasee) {
312 // FIXME: This isn't unsupported, this is just an error, which
313 // sema should catch, but...
314 ErrorUnsupported(D, "alias referencing a missing function");
315 continue;
316 }
317
318 llvm::GlobalValue *GA =
319 new llvm::GlobalAlias(aliasee->getType(),
320 llvm::Function::ExternalLinkage,
321 D->getName(),
322 aliasee,
323 &getModule());
324
325 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
326 if (Entry) {
327 // If we created a dummy function for this then replace it.
328 GA->takeName(Entry);
329
330 llvm::Value *Casted =
331 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
332 Entry->replaceAllUsesWith(Casted);
333 Entry->eraseFromParent();
334
335 Entry = GA;
336 }
337
338 // Alias should never be internal or inline.
339 SetGlobalValueAttributes(D, false, false, GA, true);
340 }
Eli Friedman9be42212008-06-01 15:54:49 +0000341}
342
Nate Begemanad320b62008-04-20 06:29:50 +0000343void CodeGenModule::EmitStatics() {
344 // Emit code for each used static decl encountered. Since a previously unused
345 // static decl may become used during the generation of code for a static
346 // function, iterate until no changes are made.
347 bool Changed;
348 do {
349 Changed = false;
350 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000351 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000352
353 // Check if we have used a decl with the same name
354 // FIXME: The AST should have some sort of aggregate decls or
355 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000356 // FIXME: This is missing some important cases. For example, we
357 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000358 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000359 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000360
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000361 // Emit the definition.
362 EmitGlobalDefinition(D);
363
Nate Begemanad320b62008-04-20 06:29:50 +0000364 // Erase the used decl from the list.
365 StaticDecls[i] = StaticDecls.back();
366 StaticDecls.pop_back();
367 --i;
368 --e;
369
370 // Remember that we made a change.
371 Changed = true;
372 }
373 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000374}
375
Nate Begeman8a704172008-04-19 04:17:09 +0000376/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
377/// annotation information for a given GlobalValue. The annotation struct is
378/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000379/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000380/// created from the AnnotateAttr's annotation. The third field is a constant
381/// string containing the name of the translation unit. The fourth field is
382/// the line number in the file of the annotated value declaration.
383///
384/// FIXME: this does not unique the annotation string constants, as llvm-gcc
385/// appears to.
386///
387llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
388 const AnnotateAttr *AA,
389 unsigned LineNo) {
390 llvm::Module *M = &getModule();
391
392 // get [N x i8] constants for the annotation string, and the filename string
393 // which are the 2nd and 3rd elements of the global annotation structure.
394 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
395 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
396 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
397 true);
398
399 // Get the two global values corresponding to the ConstantArrays we just
400 // created to hold the bytes of the strings.
401 llvm::GlobalValue *annoGV =
402 new llvm::GlobalVariable(anno->getType(), false,
403 llvm::GlobalValue::InternalLinkage, anno,
404 GV->getName() + ".str", M);
405 // translation unit name string, emitted into the llvm.metadata section.
406 llvm::GlobalValue *unitGV =
407 new llvm::GlobalVariable(unit->getType(), false,
408 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
409
410 // Create the ConstantStruct that is the global annotion.
411 llvm::Constant *Fields[4] = {
412 llvm::ConstantExpr::getBitCast(GV, SBP),
413 llvm::ConstantExpr::getBitCast(annoGV, SBP),
414 llvm::ConstantExpr::getBitCast(unitGV, SBP),
415 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
416 };
417 return llvm::ConstantStruct::get(Fields, 4, false);
418}
419
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000420void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
421 bool isDef, isStatic;
422
423 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000424 // Aliases are deferred until code for everything else has been
425 // emitted.
426 if (FD->getAttr<AliasAttr>()) {
427 assert(!FD->isThisDeclarationADefinition() &&
428 "Function alias cannot have a definition!");
429 Aliases.push_back(FD);
430 return;
431 }
432
433 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000434 isStatic = FD->getStorageClass() == FunctionDecl::Static;
435 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
436 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
437
438 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
439 isStatic = VD->getStorageClass() == VarDecl::Static;
440 } else {
441 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000442 return;
443 }
444
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000445 // Forward declarations are emitted lazily on first use.
446 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000447 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000448
449 // If the global is a static, defer code generation until later so
450 // we can easily omit unused statics.
451 if (isStatic) {
452 StaticDecls.push_back(Global);
453 return;
454 }
455
456 // Otherwise emit the definition.
457 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000458}
459
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000460void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
461 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
462 EmitGlobalFunctionDefinition(FD);
463 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
464 EmitGlobalVarDefinition(VD);
465 } else {
466 assert(0 && "Invalid argument to EmitGlobalDefinition()");
467 }
468}
469
Daniel Dunbar2188c532008-07-30 16:32:24 +0000470 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000471 assert(D->hasGlobalStorage() && "Not a global variable");
472
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000473 QualType ASTTy = D->getType();
474 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000475 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000476
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000477 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000478 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000479 if (!Entry)
480 Entry = new llvm::GlobalVariable(Ty, false,
481 llvm::GlobalValue::ExternalLinkage,
482 0, D->getName(), &getModule(), 0,
483 ASTTy.getAddressSpace());
484
Daniel Dunbar2188c532008-07-30 16:32:24 +0000485 // Make sure the result is of the correct type.
486 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000487}
488
489void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000490 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000491 QualType ASTTy = D->getType();
492 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000493
Chris Lattner4b009652007-07-25 00:24:17 +0000494 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000495 // This is a tentative definition; tentative definitions are
496 // implicitly initialized with { 0 }
497 const llvm::Type* InitTy;
498 if (ASTTy->isIncompleteArrayType()) {
499 // An incomplete array is normally [ TYPE x 0 ], but we need
500 // to fix it to [ TYPE x 1 ].
501 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
502 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
503 } else {
504 InitTy = VarTy;
505 }
506 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000507 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000508 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000509 }
510 const llvm::Type* InitType = Init->getType();
511
Daniel Dunbarad30be42008-08-25 06:18:57 +0000512 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000513 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
514
Eli Friedman43a0ce82008-05-30 19:50:47 +0000515 if (!GV) {
516 GV = new llvm::GlobalVariable(InitType, false,
517 llvm::GlobalValue::ExternalLinkage,
518 0, D->getName(), &getModule(), 0,
519 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000520 } else if (GV->getType() !=
521 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000522 // We have a definition after a prototype with the wrong type.
523 // We must make a new GlobalVariable* and update everything that used OldGV
524 // (a declaration or tentative definition) with the new GlobalVariable*
525 // (which will be a definition).
526 //
527 // This happens if there is a prototype for a global (e.g. "extern int x[];")
528 // and then a definition of a different type (e.g. "int x[10];"). This also
529 // happens when an initializer has a different type from the type of the
530 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000531 //
532 // FIXME: This also ends up happening if there's a definition followed by
533 // a tentative definition! (Although Sema rejects that construct
534 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000535
536 // Save the old global
537 llvm::GlobalVariable *OldGV = GV;
538
539 // Make a new global with the correct type
540 GV = new llvm::GlobalVariable(InitType, false,
541 llvm::GlobalValue::ExternalLinkage,
542 0, D->getName(), &getModule(), 0,
543 ASTTy.getAddressSpace());
544 // Steal the name of the old global
545 GV->takeName(OldGV);
546
547 // Replace all uses of the old global with the new global
548 llvm::Constant *NewPtrForOldDecl =
549 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
550 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000551
552 // Erase the old global, since it is no longer used.
553 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000554 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000555
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000556 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000557
Nate Begeman8a704172008-04-19 04:17:09 +0000558 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
559 SourceManager &SM = Context.getSourceManager();
560 AddAnnotation(EmitAnnotateAttr(GV, AA,
561 SM.getLogicalLineNumber(D->getLocation())));
562 }
563
Chris Lattner4b009652007-07-25 00:24:17 +0000564 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000565 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000566
Eli Friedman7008e9a2008-05-30 20:39:54 +0000567 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
568 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000569 if (const IncompleteArrayType* IAT =
570 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000571 Align = Context.getTypeAlign(IAT->getElementType());
572 else
573 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000574 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
575 Align = std::max(Align, AA->getAlignment());
576 }
577 GV->setAlignment(Align / 8);
578
Chris Lattner402b3372008-03-03 03:28:21 +0000579 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000580 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000581 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000582
583 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
584 // Prefaced with special LLVM marker to indicate that the name
585 // should not be munged.
586 GV->setName("\01" + ALA->getLabel());
587 }
Chris Lattner4b009652007-07-25 00:24:17 +0000588
589 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000590 if (D->getStorageClass() == VarDecl::Static)
591 GV->setLinkage(llvm::Function::InternalLinkage);
592 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000593 GV->setLinkage(llvm::Function::DLLImportLinkage);
594 else if (D->getAttr<DLLExportAttr>())
595 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000596 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000597 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000598 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000599 // FIXME: This isn't right. This should handle common linkage and other
600 // stuff.
601 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000602 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000603 case VarDecl::Auto:
604 case VarDecl::Register:
605 assert(0 && "Can't have auto or register globals");
606 case VarDecl::None:
607 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000608 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000609 break;
610 case VarDecl::Extern:
611 case VarDecl::PrivateExtern:
612 // todo: common
613 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000614 }
Chris Lattner4b009652007-07-25 00:24:17 +0000615 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000616
617 // Emit global variable debug information.
618 CGDebugInfo *DI = getDebugInfo();
619 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000620 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000621 DI->EmitGlobalVariable(GV, D);
622 }
Chris Lattner4b009652007-07-25 00:24:17 +0000623}
624
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000625llvm::GlobalValue *
626CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000627 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
628 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
629 llvm::Function::ExternalLinkage,
630 D->getName(), &getModule());
631 SetFunctionAttributes(D, F);
632 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000633}
634
635llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000636 QualType ASTTy = D->getType();
637 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
638 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000639
640 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000641 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000642 if (!Entry)
643 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000644
Daniel Dunbar2188c532008-07-30 16:32:24 +0000645 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000646}
647
648void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000649 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000650 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000651 Entry = EmitForwardFunctionDefinition(D);
652 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000653 // If the types mismatch then we have to rewrite the definition.
654 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
655 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000656 // Otherwise, we have a definition after a prototype with the wrong type.
657 // F is the Function* for the one with the wrong type, we must make a new
658 // Function* and update everything that used F (a declaration) with the new
659 // Function* (which will be a definition).
660 //
661 // This happens if there is a prototype for a function (e.g. "int f()") and
662 // then a definition of a different type (e.g. "int f(int x)"). Start by
663 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000664 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
665 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000666
667 // Replace uses of F with the Function we will endow with a body.
668 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000669 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
670 Entry->replaceAllUsesWith(NewPtrForOldDecl);
671
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000672 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000673 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000674 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000675
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000676 Entry = NewFn;
677 }
678 }
679
Daniel Dunbar566a6502008-09-08 23:44:31 +0000680 llvm::Function *Fn = cast<llvm::Function>(Entry);
681 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000682
Daniel Dunbar566a6502008-09-08 23:44:31 +0000683 SetFunctionAttributesForDefinition(D, Fn);
684
685 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
686 AddGlobalCtor(Fn, CA->getPriority());
687 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
688 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000689 }
690}
691
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000692llvm::Function *
693CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
694 const std::string &Name) {
695 llvm::Function *Fn = llvm::Function::Create(FTy,
696 llvm::Function::ExternalLinkage,
697 "", &TheModule);
698 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
699 return Fn;
700}
701
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000702void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
703 // Make sure that this type is translated.
704 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000705}
706
707
Chris Lattnerab862cc2007-08-31 04:31:45 +0000708/// getBuiltinLibFunction
709llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000710 if (BuiltinID > BuiltinFunctions.size())
711 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000712
Chris Lattner9f2d6892007-12-13 00:38:03 +0000713 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
714 // a slot for it.
715 assert(BuiltinID && "Invalid Builtin ID");
716 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000717 if (FunctionSlot)
718 return FunctionSlot;
719
720 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
721
722 // Get the name, skip over the __builtin_ prefix.
723 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
724
725 // Get the type for the builtin.
726 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
727 const llvm::FunctionType *Ty =
728 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
729
730 // FIXME: This has a serious problem with code like this:
731 // void abs() {}
732 // ... __builtin_abs(x);
733 // The two versions of abs will collide. The fix is for the builtin to win,
734 // and for the existing one to be turned into a constantexpr cast of the
735 // builtin. In the case where the existing one is a static function, it
736 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000737 if (llvm::Function *Existing = getModule().getFunction(Name)) {
738 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
739 return FunctionSlot = Existing;
740 assert(Existing == 0 && "FIXME: Name collision");
741 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000742
743 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000744 return FunctionSlot =
745 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
746 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000747}
748
Chris Lattner4b23f942007-12-18 00:25:38 +0000749llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
750 unsigned NumTys) {
751 return llvm::Intrinsic::getDeclaration(&getModule(),
752 (llvm::Intrinsic::ID)IID, Tys, NumTys);
753}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000754
Chris Lattner4b009652007-07-25 00:24:17 +0000755llvm::Function *CodeGenModule::getMemCpyFn() {
756 if (MemCpyFn) return MemCpyFn;
757 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000758 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000759 default: assert(0 && "Unknown ptr width");
760 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
761 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
762 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000763 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000764}
Anders Carlsson36a04872007-08-21 00:21:21 +0000765
Eli Friedman8f08a252008-05-26 12:59:39 +0000766llvm::Function *CodeGenModule::getMemMoveFn() {
767 if (MemMoveFn) return MemMoveFn;
768 llvm::Intrinsic::ID IID;
769 switch (Context.Target.getPointerWidth(0)) {
770 default: assert(0 && "Unknown ptr width");
771 case 32: IID = llvm::Intrinsic::memmove_i32; break;
772 case 64: IID = llvm::Intrinsic::memmove_i64; break;
773 }
774 return MemMoveFn = getIntrinsic(IID);
775}
776
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000777llvm::Function *CodeGenModule::getMemSetFn() {
778 if (MemSetFn) return MemSetFn;
779 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000780 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000781 default: assert(0 && "Unknown ptr width");
782 case 32: IID = llvm::Intrinsic::memset_i32; break;
783 case 64: IID = llvm::Intrinsic::memset_i64; break;
784 }
785 return MemSetFn = getIntrinsic(IID);
786}
Chris Lattner4b23f942007-12-18 00:25:38 +0000787
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000788static void appendFieldAndPadding(CodeGenModule &CGM,
789 std::vector<llvm::Constant*>& Fields,
790 int FieldNo, llvm::Constant* Field,
791 RecordDecl* RD, const llvm::StructType *STy)
792{
793 // Append the field.
794 Fields.push_back(Field);
795
796 int StructFieldNo =
797 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo));
798
799 int NextStructFieldNo;
800 if (FieldNo + 1 == RD->getNumMembers()) {
801 NextStructFieldNo = STy->getNumElements();
802 } else {
803 NextStructFieldNo =
804 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo + 1));
805 }
806
807 // Append padding
808 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
809 llvm::Constant *C =
810 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
811
812 Fields.push_back(C);
813 }
814}
815
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000816// We still need to work out the details of handling UTF-16.
817// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000818llvm::Constant *CodeGenModule::
819GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000820 llvm::StringMapEntry<llvm::Constant *> &Entry =
821 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
822
823 if (Entry.getValue())
824 return Entry.getValue();
825
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000826 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
827 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000828
829 if (!CFConstantStringClassRef) {
830 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
831 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000832
833 // FIXME: This is fairly broken if
834 // __CFConstantStringClassReference is already defined, in that it
835 // will get renamed and the user will most likely see an opaque
836 // error message. This is a general issue with relying on
837 // particular names.
838 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000839 new llvm::GlobalVariable(Ty, false,
840 llvm::GlobalVariable::ExternalLinkage, 0,
841 "__CFConstantStringClassReference",
842 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000843
844 // Decay array -> ptr
845 CFConstantStringClassRef =
846 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000847 }
848
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000849 QualType CFTy = getContext().getCFConstantStringType();
850 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000851
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000852 const llvm::StructType *STy =
853 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
854
855 std::vector<llvm::Constant*> Fields;
856
857
Anders Carlsson36a04872007-08-21 00:21:21 +0000858 // Class pointer.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000859 appendFieldAndPadding(*this, Fields, 0, CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000860
861 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000862 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000863 appendFieldAndPadding(*this, Fields, 1, llvm::ConstantInt::get(Ty, 0x07C8),
864 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000865
866 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000867 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000868 C = new llvm::GlobalVariable(C->getType(), true,
869 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000870 C, ".str", &getModule());
871 appendFieldAndPadding(*this, Fields, 2,
872 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
873 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000874
875 // String length.
876 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000877 appendFieldAndPadding(*this, Fields, 3, llvm::ConstantInt::get(Ty, str.length()),
878 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000879
880 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000881 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000882 llvm::GlobalVariable *GV =
883 new llvm::GlobalVariable(C->getType(), true,
884 llvm::GlobalVariable::InternalLinkage,
885 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000886
Anders Carlsson9be009e2007-11-01 00:41:52 +0000887 GV->setSection("__DATA,__cfstring");
888 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000889
Anders Carlsson9be009e2007-11-01 00:41:52 +0000890 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000891}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000892
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000893/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000894/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000895std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000896 if (E->isWide()) {
897 ErrorUnsupported(E, "wide string");
898 return "FIXME";
899 }
900
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000901 const char *StrData = E->getStrData();
902 unsigned Len = E->getByteLength();
903
904 const ConstantArrayType *CAT =
905 getContext().getAsConstantArrayType(E->getType());
906 assert(CAT && "String isn't pointer or array!");
907
908 // Resize the string to the right size
909 // FIXME: What about wchar_t strings?
910 std::string Str(StrData, StrData+Len);
911 uint64_t RealLen = CAT->getSize().getZExtValue();
912 Str.resize(RealLen, '\0');
913
914 return Str;
915}
916
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000917/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
918/// constant array for the given string literal.
919llvm::Constant *
920CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
921 // FIXME: This can be more efficient.
922 return GetAddrOfConstantString(GetStringForStringLiteral(S));
923}
924
Chris Lattnera6dcce32008-02-11 00:02:17 +0000925/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000926static llvm::Constant *GenerateStringLiteral(const std::string &str,
927 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000928 CodeGenModule &CGM,
929 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000930 // Create Constant for this string literal. Don't add a '\0'.
931 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000932
933 // Create a global variable for this string
934 C = new llvm::GlobalVariable(C->getType(), constant,
935 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000936 C,
937 GlobalName ? GlobalName : ".str",
938 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000939
Chris Lattnerdb6be562007-11-28 05:34:05 +0000940 return C;
941}
942
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000943/// GetAddrOfConstantString - Returns a pointer to a character array
944/// containing the literal. This contents are exactly that of the
945/// given string, i.e. it will not be null terminated automatically;
946/// see GetAddrOfConstantCString. Note that whether the result is
947/// actually a pointer to an LLVM constant depends on
948/// Feature.WriteableStrings.
949///
950/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000951llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
952 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000953 // Don't share any string literals if writable-strings is turned on.
954 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000955 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000956
957 llvm::StringMapEntry<llvm::Constant *> &Entry =
958 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
959
960 if (Entry.getValue())
961 return Entry.getValue();
962
963 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000964 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000965 Entry.setValue(C);
966 return C;
967}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000968
969/// GetAddrOfConstantCString - Returns a pointer to a character
970/// array containing the literal and a terminating '\-'
971/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000972llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
973 const char *GlobalName){
974 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000975}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000976
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000977/// EmitObjCPropertyImplementations - Emit information for synthesized
978/// properties for an implementation.
979void CodeGenModule::EmitObjCPropertyImplementations(const
980 ObjCImplementationDecl *D) {
981 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
982 e = D->propimpl_end(); i != e; ++i) {
983 ObjCPropertyImplDecl *PID = *i;
984
985 // Dynamic is just for type-checking.
986 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
987 ObjCPropertyDecl *PD = PID->getPropertyDecl();
988
989 // Determine which methods need to be implemented, some may have
990 // been overridden. Note that ::isSynthesized is not the method
991 // we want, that just indicates if the decl came from a
992 // property. What we want to know is if the method is defined in
993 // this implementation.
994 if (!D->getInstanceMethod(PD->getGetterName()))
995 CodeGenFunction(*this).GenerateObjCGetter(PID);
996 if (!PD->isReadOnly() &&
997 !D->getInstanceMethod(PD->getSetterName()))
998 CodeGenFunction(*this).GenerateObjCSetter(PID);
999 }
1000 }
1001}
1002
Daniel Dunbar27250d32008-08-15 23:26:23 +00001003/// EmitTopLevelDecl - Emit code for a single top level declaration.
1004void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1005 // If an error has occurred, stop code generation, but continue
1006 // parsing and semantic analysis (to ensure all warnings and errors
1007 // are emitted).
1008 if (Diags.hasErrorOccurred())
1009 return;
1010
1011 switch (D->getKind()) {
1012 case Decl::Function:
1013 case Decl::Var:
1014 EmitGlobal(cast<ValueDecl>(D));
1015 break;
1016
1017 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001018 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001019 break;
1020
1021 // Objective-C Decls
1022
1023 // Forward declarations, no (immediate) code generation.
1024 case Decl::ObjCClass:
1025 case Decl::ObjCCategory:
1026 case Decl::ObjCForwardProtocol:
1027 case Decl::ObjCInterface:
1028 break;
1029
1030 case Decl::ObjCProtocol:
1031 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1032 break;
1033
1034 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001035 // Categories have properties but don't support synthesize so we
1036 // can ignore them here.
1037
Daniel Dunbar27250d32008-08-15 23:26:23 +00001038 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1039 break;
1040
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001041 case Decl::ObjCImplementation: {
1042 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1043 EmitObjCPropertyImplementations(OMD);
1044 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001045 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001046 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001047 case Decl::ObjCMethod: {
1048 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1049 // If this is not a prototype, emit the body.
1050 if (OMD->getBody())
1051 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1052 break;
1053 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001054 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001055 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001056 break;
1057
1058 case Decl::LinkageSpec: {
1059 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1060 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001061 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001062 // FIXME: implement C++ linkage, C linkage works mostly by C
1063 // language reuse already.
1064 break;
1065 }
1066
1067 case Decl::FileScopeAsm: {
1068 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1069 std::string AsmString(AD->getAsmString()->getStrData(),
1070 AD->getAsmString()->getByteLength());
1071
1072 const std::string &S = getModule().getModuleInlineAsm();
1073 if (S.empty())
1074 getModule().setModuleInlineAsm(AsmString);
1075 else
1076 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1077 break;
1078 }
1079
1080 default:
1081 // Make sure we handled everything we should, every other kind is
1082 // a non-top-level decl. FIXME: Would be nice to have an
1083 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1084 // that easily.
1085 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1086 }
1087}
1088