blob: a101e389b28c732f4bcb661b39adee252b932535 [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;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000111 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000112 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000113}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000114
Daniel Dunbar9503b782008-08-16 00:56:44 +0000115/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000116/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000117void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
118 bool OmitOnError) {
119 if (OmitOnError && getDiags().hasErrorOccurred())
120 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000121 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +0000122 "cannot codegen this %0 yet");
123 std::string Msg = Type;
124 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
125 &Msg, 1);
126}
127
Daniel Dunbar27250d32008-08-15 23:26:23 +0000128/// setGlobalVisibility - Set the visibility for the given LLVM
129/// GlobalValue according to the given clang AST visibility value.
130static void setGlobalVisibility(llvm::GlobalValue *GV,
131 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000132 switch (Vis) {
133 default: assert(0 && "Unknown visibility!");
134 case VisibilityAttr::DefaultVisibility:
135 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
136 break;
137 case VisibilityAttr::HiddenVisibility:
138 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
139 break;
140 case VisibilityAttr::ProtectedVisibility:
141 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
142 break;
143 }
144}
145
Chris Lattner753d2592008-03-14 17:18:18 +0000146/// AddGlobalCtor - Add a function to the list that will be called before
147/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000148void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000149 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000150 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000151}
152
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000153/// AddGlobalDtor - Add a function to the list that will be called
154/// when the module is unloaded.
155void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
156 // TODO: Type coercion of void()* types.
157 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
158}
159
160void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
161 // Ctor function type is void()*.
162 llvm::FunctionType* CtorFTy =
163 llvm::FunctionType::get(llvm::Type::VoidTy,
164 std::vector<const llvm::Type*>(),
165 false);
166 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
167
168 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000169 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000170 llvm::StructType::get(llvm::Type::Int32Ty,
171 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000172
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000173 // Construct the constructor and destructor arrays.
174 std::vector<llvm::Constant*> Ctors;
175 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
176 std::vector<llvm::Constant*> S;
177 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
178 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
179 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000180 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000181
182 if (!Ctors.empty()) {
183 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
184 new llvm::GlobalVariable(AT, false,
185 llvm::GlobalValue::AppendingLinkage,
186 llvm::ConstantArray::get(AT, Ctors),
187 GlobalName,
188 &TheModule);
189 }
Chris Lattner753d2592008-03-14 17:18:18 +0000190}
191
Nate Begeman52da5c72008-04-18 23:43:57 +0000192void CodeGenModule::EmitAnnotations() {
193 if (Annotations.empty())
194 return;
195
196 // Create a new global variable for the ConstantStruct in the Module.
197 llvm::Constant *Array =
198 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
199 Annotations.size()),
200 Annotations);
201 llvm::GlobalValue *gv =
202 new llvm::GlobalVariable(Array->getType(), false,
203 llvm::GlobalValue::AppendingLinkage, Array,
204 "llvm.global.annotations", &TheModule);
205 gv->setSection("llvm.metadata");
206}
207
Daniel Dunbara8f02052008-09-08 21:33:45 +0000208static void SetGlobalValueAttributes(const Decl *D,
209 bool IsInternal,
210 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000211 llvm::GlobalValue *GV,
212 bool ForDefinition) {
Nuno Lopes78534382008-06-08 15:45:52 +0000213 // TODO: Set up linkage and many other things. Note, this is a simple
214 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000215 if (!ForDefinition) {
216 // Only a few attributes are set on declarations.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000217 if (D->getAttr<DLLImportAttr>())
218 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000219 } else {
220 if (IsInternal) {
221 GV->setLinkage(llvm::Function::InternalLinkage);
222 } else {
223 if (D->getAttr<DLLImportAttr>())
224 GV->setLinkage(llvm::Function::DLLImportLinkage);
225 else if (D->getAttr<DLLExportAttr>())
226 GV->setLinkage(llvm::Function::DLLExportLinkage);
227 else if (D->getAttr<WeakAttr>() || IsInline)
228 GV->setLinkage(llvm::Function::WeakLinkage);
229 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000230 }
Nuno Lopes78534382008-06-08 15:45:52 +0000231
Daniel Dunbara8f02052008-09-08 21:33:45 +0000232 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000233 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000234 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000235
Daniel Dunbara8f02052008-09-08 21:33:45 +0000236 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000237 // Prefaced with special LLVM marker to indicate that the name
238 // should not be munged.
239 GV->setName("\01" + ALA->getLabel());
240 }
Nuno Lopes78534382008-06-08 15:45:52 +0000241}
242
Devang Patela85a9ef2008-09-25 21:02:23 +0000243void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000244 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000245 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000246 AttributeListType AttributeList;
247 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
248 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000249
Devang Patela85a9ef2008-09-25 21:02:23 +0000250 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
251 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000252
253 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000254 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000255 F->setCallingConv(llvm::CallingConv::X86_FastCall);
256
257 if (D->getAttr<StdCallAttr>())
258 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000259}
260
261/// SetFunctionAttributesForDefinition - Set function attributes
262/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000263void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
264 llvm::Function *F) {
265 if (isa<ObjCMethodDecl>(D)) {
266 SetGlobalValueAttributes(D, true, false, F, true);
267 } else {
268 const FunctionDecl *FD = cast<FunctionDecl>(D);
269 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
270 FD->isInline(), F, true);
271 }
272
Daniel Dunbarf2787002008-09-04 23:41:35 +0000273 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000274 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000275
276 if (D->getAttr<AlwaysInlineAttr>())
277 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000278}
279
280void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
281 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000282 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000283
Daniel Dunbar566a6502008-09-08 23:44:31 +0000284 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000285}
286
287void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
288 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000289 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000290
Daniel Dunbar566a6502008-09-08 23:44:31 +0000291 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
292 FD->isInline(), F, false);
293}
294
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000295
Daniel Dunbar566a6502008-09-08 23:44:31 +0000296void CodeGenModule::EmitAliases() {
297 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
298 const FunctionDecl *D = Aliases[i];
299 const AliasAttr *AA = D->getAttr<AliasAttr>();
300
301 // This is something of a hack, if the FunctionDecl got overridden
302 // then its attributes will be moved to the new declaration. In
303 // this case the current decl has no alias attribute, but we will
304 // eventually see it.
305 if (!AA)
306 continue;
307
308 const std::string& aliaseeName = AA->getAliasee();
309 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
310 if (!aliasee) {
311 // FIXME: This isn't unsupported, this is just an error, which
312 // sema should catch, but...
313 ErrorUnsupported(D, "alias referencing a missing function");
314 continue;
315 }
316
317 llvm::GlobalValue *GA =
318 new llvm::GlobalAlias(aliasee->getType(),
319 llvm::Function::ExternalLinkage,
320 D->getName(),
321 aliasee,
322 &getModule());
323
324 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
325 if (Entry) {
326 // If we created a dummy function for this then replace it.
327 GA->takeName(Entry);
328
329 llvm::Value *Casted =
330 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
331 Entry->replaceAllUsesWith(Casted);
332 Entry->eraseFromParent();
333
334 Entry = GA;
335 }
336
337 // Alias should never be internal or inline.
338 SetGlobalValueAttributes(D, false, false, GA, true);
339 }
Eli Friedman9be42212008-06-01 15:54:49 +0000340}
341
Nate Begemanad320b62008-04-20 06:29:50 +0000342void CodeGenModule::EmitStatics() {
343 // Emit code for each used static decl encountered. Since a previously unused
344 // static decl may become used during the generation of code for a static
345 // function, iterate until no changes are made.
346 bool Changed;
347 do {
348 Changed = false;
349 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000350 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000351
352 // Check if we have used a decl with the same name
353 // FIXME: The AST should have some sort of aggregate decls or
354 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000355 // FIXME: This is missing some important cases. For example, we
356 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000357 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000358 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000359
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000360 // Emit the definition.
361 EmitGlobalDefinition(D);
362
Nate Begemanad320b62008-04-20 06:29:50 +0000363 // Erase the used decl from the list.
364 StaticDecls[i] = StaticDecls.back();
365 StaticDecls.pop_back();
366 --i;
367 --e;
368
369 // Remember that we made a change.
370 Changed = true;
371 }
372 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000373}
374
Nate Begeman8a704172008-04-19 04:17:09 +0000375/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
376/// annotation information for a given GlobalValue. The annotation struct is
377/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000378/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000379/// created from the AnnotateAttr's annotation. The third field is a constant
380/// string containing the name of the translation unit. The fourth field is
381/// the line number in the file of the annotated value declaration.
382///
383/// FIXME: this does not unique the annotation string constants, as llvm-gcc
384/// appears to.
385///
386llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
387 const AnnotateAttr *AA,
388 unsigned LineNo) {
389 llvm::Module *M = &getModule();
390
391 // get [N x i8] constants for the annotation string, and the filename string
392 // which are the 2nd and 3rd elements of the global annotation structure.
393 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
394 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
395 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
396 true);
397
398 // Get the two global values corresponding to the ConstantArrays we just
399 // created to hold the bytes of the strings.
400 llvm::GlobalValue *annoGV =
401 new llvm::GlobalVariable(anno->getType(), false,
402 llvm::GlobalValue::InternalLinkage, anno,
403 GV->getName() + ".str", M);
404 // translation unit name string, emitted into the llvm.metadata section.
405 llvm::GlobalValue *unitGV =
406 new llvm::GlobalVariable(unit->getType(), false,
407 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
408
409 // Create the ConstantStruct that is the global annotion.
410 llvm::Constant *Fields[4] = {
411 llvm::ConstantExpr::getBitCast(GV, SBP),
412 llvm::ConstantExpr::getBitCast(annoGV, SBP),
413 llvm::ConstantExpr::getBitCast(unitGV, SBP),
414 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
415 };
416 return llvm::ConstantStruct::get(Fields, 4, false);
417}
418
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000419void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
420 bool isDef, isStatic;
421
422 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000423 // Aliases are deferred until code for everything else has been
424 // emitted.
425 if (FD->getAttr<AliasAttr>()) {
426 assert(!FD->isThisDeclarationADefinition() &&
427 "Function alias cannot have a definition!");
428 Aliases.push_back(FD);
429 return;
430 }
431
432 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000433 isStatic = FD->getStorageClass() == FunctionDecl::Static;
434 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
435 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
436
437 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
438 isStatic = VD->getStorageClass() == VarDecl::Static;
439 } else {
440 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000441 return;
442 }
443
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000444 // Forward declarations are emitted lazily on first use.
445 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000446 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000447
448 // If the global is a static, defer code generation until later so
449 // we can easily omit unused statics.
450 if (isStatic) {
451 StaticDecls.push_back(Global);
452 return;
453 }
454
455 // Otherwise emit the definition.
456 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000457}
458
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000459void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
461 EmitGlobalFunctionDefinition(FD);
462 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
463 EmitGlobalVarDefinition(VD);
464 } else {
465 assert(0 && "Invalid argument to EmitGlobalDefinition()");
466 }
467}
468
Daniel Dunbar2188c532008-07-30 16:32:24 +0000469 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000470 assert(D->hasGlobalStorage() && "Not a global variable");
471
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000472 QualType ASTTy = D->getType();
473 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000474 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000475
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000476 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000477 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000478 if (!Entry)
479 Entry = new llvm::GlobalVariable(Ty, false,
480 llvm::GlobalValue::ExternalLinkage,
481 0, D->getName(), &getModule(), 0,
482 ASTTy.getAddressSpace());
483
Daniel Dunbar2188c532008-07-30 16:32:24 +0000484 // Make sure the result is of the correct type.
485 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000486}
487
488void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000489 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000490 QualType ASTTy = D->getType();
491 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000492
Chris Lattner4b009652007-07-25 00:24:17 +0000493 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000494 // This is a tentative definition; tentative definitions are
495 // implicitly initialized with { 0 }
496 const llvm::Type* InitTy;
497 if (ASTTy->isIncompleteArrayType()) {
498 // An incomplete array is normally [ TYPE x 0 ], but we need
499 // to fix it to [ TYPE x 1 ].
500 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
501 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
502 } else {
503 InitTy = VarTy;
504 }
505 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000506 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000507 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000508 }
509 const llvm::Type* InitType = Init->getType();
510
Daniel Dunbarad30be42008-08-25 06:18:57 +0000511 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000512 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
513
Eli Friedman43a0ce82008-05-30 19:50:47 +0000514 if (!GV) {
515 GV = new llvm::GlobalVariable(InitType, false,
516 llvm::GlobalValue::ExternalLinkage,
517 0, D->getName(), &getModule(), 0,
518 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000519 } else if (GV->getType() !=
520 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000521 // We have a definition after a prototype with the wrong type.
522 // We must make a new GlobalVariable* and update everything that used OldGV
523 // (a declaration or tentative definition) with the new GlobalVariable*
524 // (which will be a definition).
525 //
526 // This happens if there is a prototype for a global (e.g. "extern int x[];")
527 // and then a definition of a different type (e.g. "int x[10];"). This also
528 // happens when an initializer has a different type from the type of the
529 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000530 //
531 // FIXME: This also ends up happening if there's a definition followed by
532 // a tentative definition! (Although Sema rejects that construct
533 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000534
535 // Save the old global
536 llvm::GlobalVariable *OldGV = GV;
537
538 // Make a new global with the correct type
539 GV = new llvm::GlobalVariable(InitType, false,
540 llvm::GlobalValue::ExternalLinkage,
541 0, D->getName(), &getModule(), 0,
542 ASTTy.getAddressSpace());
543 // Steal the name of the old global
544 GV->takeName(OldGV);
545
546 // Replace all uses of the old global with the new global
547 llvm::Constant *NewPtrForOldDecl =
548 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
549 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000550
551 // Erase the old global, since it is no longer used.
552 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000553 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000554
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000555 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000556
Nate Begeman8a704172008-04-19 04:17:09 +0000557 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
558 SourceManager &SM = Context.getSourceManager();
559 AddAnnotation(EmitAnnotateAttr(GV, AA,
560 SM.getLogicalLineNumber(D->getLocation())));
561 }
562
Chris Lattner4b009652007-07-25 00:24:17 +0000563 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000564 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000565
Eli Friedman7008e9a2008-05-30 20:39:54 +0000566 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
567 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000568 if (const IncompleteArrayType* IAT =
569 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000570 Align = Context.getTypeAlign(IAT->getElementType());
571 else
572 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000573 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
574 Align = std::max(Align, AA->getAlignment());
575 }
576 GV->setAlignment(Align / 8);
577
Chris Lattner402b3372008-03-03 03:28:21 +0000578 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000579 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000580 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000581
582 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
583 // Prefaced with special LLVM marker to indicate that the name
584 // should not be munged.
585 GV->setName("\01" + ALA->getLabel());
586 }
Chris Lattner4b009652007-07-25 00:24:17 +0000587
588 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000589 if (D->getStorageClass() == VarDecl::Static)
590 GV->setLinkage(llvm::Function::InternalLinkage);
591 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000592 GV->setLinkage(llvm::Function::DLLImportLinkage);
593 else if (D->getAttr<DLLExportAttr>())
594 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000595 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000596 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000597 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000598 // FIXME: This isn't right. This should handle common linkage and other
599 // stuff.
600 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000601 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000602 case VarDecl::Auto:
603 case VarDecl::Register:
604 assert(0 && "Can't have auto or register globals");
605 case VarDecl::None:
606 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000607 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000608 break;
609 case VarDecl::Extern:
610 case VarDecl::PrivateExtern:
611 // todo: common
612 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000613 }
Chris Lattner4b009652007-07-25 00:24:17 +0000614 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000615
616 // Emit global variable debug information.
617 CGDebugInfo *DI = getDebugInfo();
618 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000619 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000620 DI->EmitGlobalVariable(GV, D);
621 }
Chris Lattner4b009652007-07-25 00:24:17 +0000622}
623
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000624llvm::GlobalValue *
625CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000626 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
627 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
628 llvm::Function::ExternalLinkage,
629 D->getName(), &getModule());
630 SetFunctionAttributes(D, F);
631 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000632}
633
634llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000635 QualType ASTTy = D->getType();
636 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
637 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000638
639 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000640 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000641 if (!Entry)
642 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000643
Daniel Dunbar2188c532008-07-30 16:32:24 +0000644 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000645}
646
647void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000648 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000649 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000650 Entry = EmitForwardFunctionDefinition(D);
651 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000652 // If the types mismatch then we have to rewrite the definition.
653 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
654 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000655 // Otherwise, we have a definition after a prototype with the wrong type.
656 // F is the Function* for the one with the wrong type, we must make a new
657 // Function* and update everything that used F (a declaration) with the new
658 // Function* (which will be a definition).
659 //
660 // This happens if there is a prototype for a function (e.g. "int f()") and
661 // then a definition of a different type (e.g. "int f(int x)"). Start by
662 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000663 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
664 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000665
666 // Replace uses of F with the Function we will endow with a body.
667 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000668 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
669 Entry->replaceAllUsesWith(NewPtrForOldDecl);
670
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000671 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000672 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000673 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000674
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000675 Entry = NewFn;
676 }
677 }
678
Daniel Dunbar566a6502008-09-08 23:44:31 +0000679 llvm::Function *Fn = cast<llvm::Function>(Entry);
680 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000681
Daniel Dunbar566a6502008-09-08 23:44:31 +0000682 SetFunctionAttributesForDefinition(D, Fn);
683
684 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
685 AddGlobalCtor(Fn, CA->getPriority());
686 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
687 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000688 }
689}
690
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000691llvm::Function *
692CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
693 const std::string &Name) {
694 llvm::Function *Fn = llvm::Function::Create(FTy,
695 llvm::Function::ExternalLinkage,
696 "", &TheModule);
697 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
698 return Fn;
699}
700
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000701void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
702 // Make sure that this type is translated.
703 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000704}
705
706
Chris Lattnerab862cc2007-08-31 04:31:45 +0000707/// getBuiltinLibFunction
708llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000709 if (BuiltinID > BuiltinFunctions.size())
710 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000711
Chris Lattner9f2d6892007-12-13 00:38:03 +0000712 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
713 // a slot for it.
714 assert(BuiltinID && "Invalid Builtin ID");
715 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000716 if (FunctionSlot)
717 return FunctionSlot;
718
719 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
720
721 // Get the name, skip over the __builtin_ prefix.
722 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
723
724 // Get the type for the builtin.
725 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
726 const llvm::FunctionType *Ty =
727 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
728
729 // FIXME: This has a serious problem with code like this:
730 // void abs() {}
731 // ... __builtin_abs(x);
732 // The two versions of abs will collide. The fix is for the builtin to win,
733 // and for the existing one to be turned into a constantexpr cast of the
734 // builtin. In the case where the existing one is a static function, it
735 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000736 if (llvm::Function *Existing = getModule().getFunction(Name)) {
737 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
738 return FunctionSlot = Existing;
739 assert(Existing == 0 && "FIXME: Name collision");
740 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000741
742 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000743 return FunctionSlot =
744 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
745 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000746}
747
Chris Lattner4b23f942007-12-18 00:25:38 +0000748llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
749 unsigned NumTys) {
750 return llvm::Intrinsic::getDeclaration(&getModule(),
751 (llvm::Intrinsic::ID)IID, Tys, NumTys);
752}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000753
Chris Lattner4b009652007-07-25 00:24:17 +0000754llvm::Function *CodeGenModule::getMemCpyFn() {
755 if (MemCpyFn) return MemCpyFn;
756 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000757 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000758 default: assert(0 && "Unknown ptr width");
759 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
760 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
761 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000762 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000763}
Anders Carlsson36a04872007-08-21 00:21:21 +0000764
Eli Friedman8f08a252008-05-26 12:59:39 +0000765llvm::Function *CodeGenModule::getMemMoveFn() {
766 if (MemMoveFn) return MemMoveFn;
767 llvm::Intrinsic::ID IID;
768 switch (Context.Target.getPointerWidth(0)) {
769 default: assert(0 && "Unknown ptr width");
770 case 32: IID = llvm::Intrinsic::memmove_i32; break;
771 case 64: IID = llvm::Intrinsic::memmove_i64; break;
772 }
773 return MemMoveFn = getIntrinsic(IID);
774}
775
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000776llvm::Function *CodeGenModule::getMemSetFn() {
777 if (MemSetFn) return MemSetFn;
778 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000779 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000780 default: assert(0 && "Unknown ptr width");
781 case 32: IID = llvm::Intrinsic::memset_i32; break;
782 case 64: IID = llvm::Intrinsic::memset_i64; break;
783 }
784 return MemSetFn = getIntrinsic(IID);
785}
Chris Lattner4b23f942007-12-18 00:25:38 +0000786
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000787static void appendFieldAndPadding(CodeGenModule &CGM,
788 std::vector<llvm::Constant*>& Fields,
789 int FieldNo, llvm::Constant* Field,
790 RecordDecl* RD, const llvm::StructType *STy)
791{
792 // Append the field.
793 Fields.push_back(Field);
794
795 int StructFieldNo =
796 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo));
797
798 int NextStructFieldNo;
799 if (FieldNo + 1 == RD->getNumMembers()) {
800 NextStructFieldNo = STy->getNumElements();
801 } else {
802 NextStructFieldNo =
803 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo + 1));
804 }
805
806 // Append padding
807 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
808 llvm::Constant *C =
809 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
810
811 Fields.push_back(C);
812 }
813}
814
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000815// We still need to work out the details of handling UTF-16.
816// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000817llvm::Constant *CodeGenModule::
818GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000819 llvm::StringMapEntry<llvm::Constant *> &Entry =
820 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
821
822 if (Entry.getValue())
823 return Entry.getValue();
824
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000825 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
826 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000827
828 if (!CFConstantStringClassRef) {
829 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
830 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000831
832 // FIXME: This is fairly broken if
833 // __CFConstantStringClassReference is already defined, in that it
834 // will get renamed and the user will most likely see an opaque
835 // error message. This is a general issue with relying on
836 // particular names.
837 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000838 new llvm::GlobalVariable(Ty, false,
839 llvm::GlobalVariable::ExternalLinkage, 0,
840 "__CFConstantStringClassReference",
841 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000842
843 // Decay array -> ptr
844 CFConstantStringClassRef =
845 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000846 }
847
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000848 QualType CFTy = getContext().getCFConstantStringType();
849 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000850
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000851 const llvm::StructType *STy =
852 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
853
854 std::vector<llvm::Constant*> Fields;
855
856
Anders Carlsson36a04872007-08-21 00:21:21 +0000857 // Class pointer.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000858 appendFieldAndPadding(*this, Fields, 0, CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000859
860 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000861 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000862 appendFieldAndPadding(*this, Fields, 1, llvm::ConstantInt::get(Ty, 0x07C8),
863 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000864
865 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000866 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000867 C = new llvm::GlobalVariable(C->getType(), true,
868 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000869 C, ".str", &getModule());
870 appendFieldAndPadding(*this, Fields, 2,
871 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
872 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000873
874 // String length.
875 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000876 appendFieldAndPadding(*this, Fields, 3, llvm::ConstantInt::get(Ty, str.length()),
877 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000878
879 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000880 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000881 llvm::GlobalVariable *GV =
882 new llvm::GlobalVariable(C->getType(), true,
883 llvm::GlobalVariable::InternalLinkage,
884 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000885
Anders Carlsson9be009e2007-11-01 00:41:52 +0000886 GV->setSection("__DATA,__cfstring");
887 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000888
Anders Carlsson9be009e2007-11-01 00:41:52 +0000889 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000890}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000891
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000892/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000893/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000894std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000895 if (E->isWide()) {
896 ErrorUnsupported(E, "wide string");
897 return "FIXME";
898 }
899
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000900 const char *StrData = E->getStrData();
901 unsigned Len = E->getByteLength();
902
903 const ConstantArrayType *CAT =
904 getContext().getAsConstantArrayType(E->getType());
905 assert(CAT && "String isn't pointer or array!");
906
907 // Resize the string to the right size
908 // FIXME: What about wchar_t strings?
909 std::string Str(StrData, StrData+Len);
910 uint64_t RealLen = CAT->getSize().getZExtValue();
911 Str.resize(RealLen, '\0');
912
913 return Str;
914}
915
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000916/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
917/// constant array for the given string literal.
918llvm::Constant *
919CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
920 // FIXME: This can be more efficient.
921 return GetAddrOfConstantString(GetStringForStringLiteral(S));
922}
923
Chris Lattnera6dcce32008-02-11 00:02:17 +0000924/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000925static llvm::Constant *GenerateStringLiteral(const std::string &str,
926 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000927 CodeGenModule &CGM,
928 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000929 // Create Constant for this string literal. Don't add a '\0'.
930 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000931
932 // Create a global variable for this string
933 C = new llvm::GlobalVariable(C->getType(), constant,
934 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000935 C,
936 GlobalName ? GlobalName : ".str",
937 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000938
Chris Lattnerdb6be562007-11-28 05:34:05 +0000939 return C;
940}
941
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000942/// GetAddrOfConstantString - Returns a pointer to a character array
943/// containing the literal. This contents are exactly that of the
944/// given string, i.e. it will not be null terminated automatically;
945/// see GetAddrOfConstantCString. Note that whether the result is
946/// actually a pointer to an LLVM constant depends on
947/// Feature.WriteableStrings.
948///
949/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000950llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
951 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000952 // Don't share any string literals if writable-strings is turned on.
953 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000954 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000955
956 llvm::StringMapEntry<llvm::Constant *> &Entry =
957 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
958
959 if (Entry.getValue())
960 return Entry.getValue();
961
962 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000963 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000964 Entry.setValue(C);
965 return C;
966}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000967
968/// GetAddrOfConstantCString - Returns a pointer to a character
969/// array containing the literal and a terminating '\-'
970/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000971llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
972 const char *GlobalName){
973 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000974}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000975
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000976/// EmitObjCPropertyImplementations - Emit information for synthesized
977/// properties for an implementation.
978void CodeGenModule::EmitObjCPropertyImplementations(const
979 ObjCImplementationDecl *D) {
980 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
981 e = D->propimpl_end(); i != e; ++i) {
982 ObjCPropertyImplDecl *PID = *i;
983
984 // Dynamic is just for type-checking.
985 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
986 ObjCPropertyDecl *PD = PID->getPropertyDecl();
987
988 // Determine which methods need to be implemented, some may have
989 // been overridden. Note that ::isSynthesized is not the method
990 // we want, that just indicates if the decl came from a
991 // property. What we want to know is if the method is defined in
992 // this implementation.
993 if (!D->getInstanceMethod(PD->getGetterName()))
994 CodeGenFunction(*this).GenerateObjCGetter(PID);
995 if (!PD->isReadOnly() &&
996 !D->getInstanceMethod(PD->getSetterName()))
997 CodeGenFunction(*this).GenerateObjCSetter(PID);
998 }
999 }
1000}
1001
Daniel Dunbar27250d32008-08-15 23:26:23 +00001002/// EmitTopLevelDecl - Emit code for a single top level declaration.
1003void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1004 // If an error has occurred, stop code generation, but continue
1005 // parsing and semantic analysis (to ensure all warnings and errors
1006 // are emitted).
1007 if (Diags.hasErrorOccurred())
1008 return;
1009
1010 switch (D->getKind()) {
1011 case Decl::Function:
1012 case Decl::Var:
1013 EmitGlobal(cast<ValueDecl>(D));
1014 break;
1015
1016 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001017 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001018 break;
1019
1020 // Objective-C Decls
1021
1022 // Forward declarations, no (immediate) code generation.
1023 case Decl::ObjCClass:
1024 case Decl::ObjCCategory:
1025 case Decl::ObjCForwardProtocol:
1026 case Decl::ObjCInterface:
1027 break;
1028
1029 case Decl::ObjCProtocol:
1030 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1031 break;
1032
1033 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001034 // Categories have properties but don't support synthesize so we
1035 // can ignore them here.
1036
Daniel Dunbar27250d32008-08-15 23:26:23 +00001037 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1038 break;
1039
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001040 case Decl::ObjCImplementation: {
1041 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1042 EmitObjCPropertyImplementations(OMD);
1043 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001044 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001045 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001046 case Decl::ObjCMethod: {
1047 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1048 // If this is not a prototype, emit the body.
1049 if (OMD->getBody())
1050 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1051 break;
1052 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001053 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001054 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001055 break;
1056
1057 case Decl::LinkageSpec: {
1058 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1059 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001060 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001061 // FIXME: implement C++ linkage, C linkage works mostly by C
1062 // language reuse already.
1063 break;
1064 }
1065
1066 case Decl::FileScopeAsm: {
1067 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1068 std::string AsmString(AD->getAsmString()->getStrData(),
1069 AD->getAsmString()->getByteLength());
1070
1071 const std::string &S = getModule().getModuleInlineAsm();
1072 if (S.empty())
1073 getModule().setModuleInlineAsm(AsmString);
1074 else
1075 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1076 break;
1077 }
1078
1079 default:
1080 // Make sure we handled everything we should, every other kind is
1081 // a non-top-level decl. FIXME: Would be nice to have an
1082 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1083 // that easily.
1084 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1085 }
1086}
1087