blob: aaca21bab33bb3b6fd73634e5e8c7643dec52da2 [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 Lattnercf9c9d02007-12-02 07:19:18 +000021#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000024#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000025#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000028#include "llvm/Analysis/Verifier.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 Lattnerb033c4a2008-04-30 16:05:42 +000067 // Run the verifier to check that the generated code is consistent.
Daniel Dunbar566a6502008-09-08 23:44:31 +000068 if (verifyModule(TheModule, llvm::PrintMessageAction)) {
69 TheModule.dump();
70 assert(0 && "Module failed verification!");
71 }
Chris Lattnercbfb5512008-03-01 08:45:05 +000072}
Chris Lattner4b009652007-07-25 00:24:17 +000073
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000074void CodeGenModule::BindRuntimeFunctions() {
75 // Deal with protecting runtime function names.
76 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
77 llvm::Function *Fn = RuntimeFunctions[i].first;
78 const std::string &Name = RuntimeFunctions[i].second;
79
80 // See if there is a conflict against a function.
81 llvm::Function *Conflict = TheModule.getFunction(Name);
82 if (Conflict) {
83 // Decide which version to take. If the conflict is a definition
84 // we are forced to take that, otherwise assume the runtime
85 // knows best.
86 if (!Conflict->isDeclaration()) {
87 llvm::Value *Casted =
88 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
89 Fn->replaceAllUsesWith(Casted);
90 Fn->eraseFromParent();
91 } else {
92 Fn->takeName(Conflict);
93 llvm::Value *Casted =
94 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
95 Conflict->replaceAllUsesWith(Casted);
96 Conflict->eraseFromParent();
97 }
98 } else {
99 // FIXME: There still may be conflicts with aliases and
100 // variables.
101 Fn->setName(Name);
102 }
103 }
104}
105
Daniel Dunbar9503b782008-08-16 00:56:44 +0000106/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000107/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000108void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
109 bool OmitOnError) {
110 if (OmitOnError && getDiags().hasErrorOccurred())
111 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000112 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000113 "cannot codegen this %0 yet");
114 SourceRange Range = S->getSourceRange();
115 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000116 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000117 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000118}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000119
Daniel Dunbar9503b782008-08-16 00:56:44 +0000120/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000121/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000122void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
123 bool OmitOnError) {
124 if (OmitOnError && getDiags().hasErrorOccurred())
125 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +0000127 "cannot codegen this %0 yet");
128 std::string Msg = Type;
129 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
130 &Msg, 1);
131}
132
Daniel Dunbar27250d32008-08-15 23:26:23 +0000133/// setGlobalVisibility - Set the visibility for the given LLVM
134/// GlobalValue according to the given clang AST visibility value.
135static void setGlobalVisibility(llvm::GlobalValue *GV,
136 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000137 switch (Vis) {
138 default: assert(0 && "Unknown visibility!");
139 case VisibilityAttr::DefaultVisibility:
140 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
141 break;
142 case VisibilityAttr::HiddenVisibility:
143 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
144 break;
145 case VisibilityAttr::ProtectedVisibility:
146 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
147 break;
148 }
149}
150
Chris Lattner753d2592008-03-14 17:18:18 +0000151/// AddGlobalCtor - Add a function to the list that will be called before
152/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000153void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000154 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000155 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000156}
157
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000158/// AddGlobalDtor - Add a function to the list that will be called
159/// when the module is unloaded.
160void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
161 // TODO: Type coercion of void()* types.
162 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
163}
164
165void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
166 // Ctor function type is void()*.
167 llvm::FunctionType* CtorFTy =
168 llvm::FunctionType::get(llvm::Type::VoidTy,
169 std::vector<const llvm::Type*>(),
170 false);
171 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
172
173 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000174 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000175 llvm::StructType::get(llvm::Type::Int32Ty,
176 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000177
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000178 // Construct the constructor and destructor arrays.
179 std::vector<llvm::Constant*> Ctors;
180 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
181 std::vector<llvm::Constant*> S;
182 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
183 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
184 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000185 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000186
187 if (!Ctors.empty()) {
188 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
189 new llvm::GlobalVariable(AT, false,
190 llvm::GlobalValue::AppendingLinkage,
191 llvm::ConstantArray::get(AT, Ctors),
192 GlobalName,
193 &TheModule);
194 }
Chris Lattner753d2592008-03-14 17:18:18 +0000195}
196
Nate Begeman52da5c72008-04-18 23:43:57 +0000197void CodeGenModule::EmitAnnotations() {
198 if (Annotations.empty())
199 return;
200
201 // Create a new global variable for the ConstantStruct in the Module.
202 llvm::Constant *Array =
203 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
204 Annotations.size()),
205 Annotations);
206 llvm::GlobalValue *gv =
207 new llvm::GlobalVariable(Array->getType(), false,
208 llvm::GlobalValue::AppendingLinkage, Array,
209 "llvm.global.annotations", &TheModule);
210 gv->setSection("llvm.metadata");
211}
212
Daniel Dunbara8f02052008-09-08 21:33:45 +0000213static void SetGlobalValueAttributes(const Decl *D,
214 bool IsInternal,
215 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000216 llvm::GlobalValue *GV,
217 bool ForDefinition) {
Nuno Lopes78534382008-06-08 15:45:52 +0000218 // TODO: Set up linkage and many other things. Note, this is a simple
219 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000220 if (!ForDefinition) {
221 // Only a few attributes are set on declarations.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000222 if (D->getAttr<DLLImportAttr>())
223 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000224 } else {
225 if (IsInternal) {
226 GV->setLinkage(llvm::Function::InternalLinkage);
227 } else {
228 if (D->getAttr<DLLImportAttr>())
229 GV->setLinkage(llvm::Function::DLLImportLinkage);
230 else if (D->getAttr<DLLExportAttr>())
231 GV->setLinkage(llvm::Function::DLLExportLinkage);
232 else if (D->getAttr<WeakAttr>() || IsInline)
233 GV->setLinkage(llvm::Function::WeakLinkage);
234 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000235 }
Nuno Lopes78534382008-06-08 15:45:52 +0000236
Daniel Dunbara8f02052008-09-08 21:33:45 +0000237 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000238 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000239 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000240
Daniel Dunbara8f02052008-09-08 21:33:45 +0000241 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000242 // Prefaced with special LLVM marker to indicate that the name
243 // should not be munged.
244 GV->setName("\01" + ALA->getLabel());
245 }
Nuno Lopes78534382008-06-08 15:45:52 +0000246}
247
Devang Patela85a9ef2008-09-25 21:02:23 +0000248void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000249 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000250 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000251 AttributeListType AttributeList;
252 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
253 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000254
Devang Patela85a9ef2008-09-25 21:02:23 +0000255 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
256 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000257
258 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000259 if (D->getAttr<FastCallAttr>())
Eli Friedman9be42212008-06-01 15:54:49 +0000260 F->setCallingConv(llvm::CallingConv::Fast);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000261}
262
263/// SetFunctionAttributesForDefinition - Set function attributes
264/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000265void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
266 llvm::Function *F) {
267 if (isa<ObjCMethodDecl>(D)) {
268 SetGlobalValueAttributes(D, true, false, F, true);
269 } else {
270 const FunctionDecl *FD = cast<FunctionDecl>(D);
271 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
272 FD->isInline(), F, true);
273 }
274
Daniel Dunbarf2787002008-09-04 23:41:35 +0000275 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000276 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000277
278 if (D->getAttr<AlwaysInlineAttr>())
279 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000280}
281
282void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
283 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000284 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000285
Daniel Dunbar566a6502008-09-08 23:44:31 +0000286 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000287}
288
289void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
290 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000291 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000292
Daniel Dunbar566a6502008-09-08 23:44:31 +0000293 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
294 FD->isInline(), F, false);
295}
296
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000297
Daniel Dunbar566a6502008-09-08 23:44:31 +0000298void CodeGenModule::EmitAliases() {
299 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
300 const FunctionDecl *D = Aliases[i];
301 const AliasAttr *AA = D->getAttr<AliasAttr>();
302
303 // This is something of a hack, if the FunctionDecl got overridden
304 // then its attributes will be moved to the new declaration. In
305 // this case the current decl has no alias attribute, but we will
306 // eventually see it.
307 if (!AA)
308 continue;
309
310 const std::string& aliaseeName = AA->getAliasee();
311 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
312 if (!aliasee) {
313 // FIXME: This isn't unsupported, this is just an error, which
314 // sema should catch, but...
315 ErrorUnsupported(D, "alias referencing a missing function");
316 continue;
317 }
318
319 llvm::GlobalValue *GA =
320 new llvm::GlobalAlias(aliasee->getType(),
321 llvm::Function::ExternalLinkage,
322 D->getName(),
323 aliasee,
324 &getModule());
325
326 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
327 if (Entry) {
328 // If we created a dummy function for this then replace it.
329 GA->takeName(Entry);
330
331 llvm::Value *Casted =
332 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
333 Entry->replaceAllUsesWith(Casted);
334 Entry->eraseFromParent();
335
336 Entry = GA;
337 }
338
339 // Alias should never be internal or inline.
340 SetGlobalValueAttributes(D, false, false, GA, true);
341 }
Eli Friedman9be42212008-06-01 15:54:49 +0000342}
343
Nate Begemanad320b62008-04-20 06:29:50 +0000344void CodeGenModule::EmitStatics() {
345 // Emit code for each used static decl encountered. Since a previously unused
346 // static decl may become used during the generation of code for a static
347 // function, iterate until no changes are made.
348 bool Changed;
349 do {
350 Changed = false;
351 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000352 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000353
354 // Check if we have used a decl with the same name
355 // FIXME: The AST should have some sort of aggregate decls or
356 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000357 // FIXME: This is missing some important cases. For example, we
358 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000359 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000360 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000361
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000362 // Emit the definition.
363 EmitGlobalDefinition(D);
364
Nate Begemanad320b62008-04-20 06:29:50 +0000365 // Erase the used decl from the list.
366 StaticDecls[i] = StaticDecls.back();
367 StaticDecls.pop_back();
368 --i;
369 --e;
370
371 // Remember that we made a change.
372 Changed = true;
373 }
374 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000375}
376
Nate Begeman8a704172008-04-19 04:17:09 +0000377/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
378/// annotation information for a given GlobalValue. The annotation struct is
379/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000380/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000381/// created from the AnnotateAttr's annotation. The third field is a constant
382/// string containing the name of the translation unit. The fourth field is
383/// the line number in the file of the annotated value declaration.
384///
385/// FIXME: this does not unique the annotation string constants, as llvm-gcc
386/// appears to.
387///
388llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
389 const AnnotateAttr *AA,
390 unsigned LineNo) {
391 llvm::Module *M = &getModule();
392
393 // get [N x i8] constants for the annotation string, and the filename string
394 // which are the 2nd and 3rd elements of the global annotation structure.
395 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
397 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
398 true);
399
400 // Get the two global values corresponding to the ConstantArrays we just
401 // created to hold the bytes of the strings.
402 llvm::GlobalValue *annoGV =
403 new llvm::GlobalVariable(anno->getType(), false,
404 llvm::GlobalValue::InternalLinkage, anno,
405 GV->getName() + ".str", M);
406 // translation unit name string, emitted into the llvm.metadata section.
407 llvm::GlobalValue *unitGV =
408 new llvm::GlobalVariable(unit->getType(), false,
409 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
410
411 // Create the ConstantStruct that is the global annotion.
412 llvm::Constant *Fields[4] = {
413 llvm::ConstantExpr::getBitCast(GV, SBP),
414 llvm::ConstantExpr::getBitCast(annoGV, SBP),
415 llvm::ConstantExpr::getBitCast(unitGV, SBP),
416 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
417 };
418 return llvm::ConstantStruct::get(Fields, 4, false);
419}
420
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000421void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
422 bool isDef, isStatic;
423
424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000425 // Aliases are deferred until code for everything else has been
426 // emitted.
427 if (FD->getAttr<AliasAttr>()) {
428 assert(!FD->isThisDeclarationADefinition() &&
429 "Function alias cannot have a definition!");
430 Aliases.push_back(FD);
431 return;
432 }
433
434 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000435 isStatic = FD->getStorageClass() == FunctionDecl::Static;
436 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
437 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
438
439 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
440 isStatic = VD->getStorageClass() == VarDecl::Static;
441 } else {
442 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000443 return;
444 }
445
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000446 // Forward declarations are emitted lazily on first use.
447 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000448 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000449
450 // If the global is a static, defer code generation until later so
451 // we can easily omit unused statics.
452 if (isStatic) {
453 StaticDecls.push_back(Global);
454 return;
455 }
456
457 // Otherwise emit the definition.
458 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000459}
460
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000461void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
463 EmitGlobalFunctionDefinition(FD);
464 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
465 EmitGlobalVarDefinition(VD);
466 } else {
467 assert(0 && "Invalid argument to EmitGlobalDefinition()");
468 }
469}
470
Daniel Dunbar2188c532008-07-30 16:32:24 +0000471 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000472 assert(D->hasGlobalStorage() && "Not a global variable");
473
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000474 QualType ASTTy = D->getType();
475 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000476 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000477
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000478 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000479 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000480 if (!Entry)
481 Entry = new llvm::GlobalVariable(Ty, false,
482 llvm::GlobalValue::ExternalLinkage,
483 0, D->getName(), &getModule(), 0,
484 ASTTy.getAddressSpace());
485
Daniel Dunbar2188c532008-07-30 16:32:24 +0000486 // Make sure the result is of the correct type.
487 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000488}
489
490void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000491 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000492 QualType ASTTy = D->getType();
493 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000494
Chris Lattner4b009652007-07-25 00:24:17 +0000495 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000496 // This is a tentative definition; tentative definitions are
497 // implicitly initialized with { 0 }
498 const llvm::Type* InitTy;
499 if (ASTTy->isIncompleteArrayType()) {
500 // An incomplete array is normally [ TYPE x 0 ], but we need
501 // to fix it to [ TYPE x 1 ].
502 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
503 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
504 } else {
505 InitTy = VarTy;
506 }
507 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000508 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000509 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000510 }
511 const llvm::Type* InitType = Init->getType();
512
Daniel Dunbarad30be42008-08-25 06:18:57 +0000513 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000514 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
515
Eli Friedman43a0ce82008-05-30 19:50:47 +0000516 if (!GV) {
517 GV = new llvm::GlobalVariable(InitType, false,
518 llvm::GlobalValue::ExternalLinkage,
519 0, D->getName(), &getModule(), 0,
520 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000521 } else if (GV->getType() !=
522 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000523 // We have a definition after a prototype with the wrong type.
524 // We must make a new GlobalVariable* and update everything that used OldGV
525 // (a declaration or tentative definition) with the new GlobalVariable*
526 // (which will be a definition).
527 //
528 // This happens if there is a prototype for a global (e.g. "extern int x[];")
529 // and then a definition of a different type (e.g. "int x[10];"). This also
530 // happens when an initializer has a different type from the type of the
531 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000532 //
533 // FIXME: This also ends up happening if there's a definition followed by
534 // a tentative definition! (Although Sema rejects that construct
535 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000536
537 // Save the old global
538 llvm::GlobalVariable *OldGV = GV;
539
540 // Make a new global with the correct type
541 GV = new llvm::GlobalVariable(InitType, false,
542 llvm::GlobalValue::ExternalLinkage,
543 0, D->getName(), &getModule(), 0,
544 ASTTy.getAddressSpace());
545 // Steal the name of the old global
546 GV->takeName(OldGV);
547
548 // Replace all uses of the old global with the new global
549 llvm::Constant *NewPtrForOldDecl =
550 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
551 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000552
553 // Erase the old global, since it is no longer used.
554 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000555 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000556
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000557 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000558
Nate Begeman8a704172008-04-19 04:17:09 +0000559 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
560 SourceManager &SM = Context.getSourceManager();
561 AddAnnotation(EmitAnnotateAttr(GV, AA,
562 SM.getLogicalLineNumber(D->getLocation())));
563 }
564
Chris Lattner4b009652007-07-25 00:24:17 +0000565 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000566 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000567
Eli Friedman7008e9a2008-05-30 20:39:54 +0000568 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
569 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000570 if (const IncompleteArrayType* IAT =
571 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000572 Align = Context.getTypeAlign(IAT->getElementType());
573 else
574 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000575 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
576 Align = std::max(Align, AA->getAlignment());
577 }
578 GV->setAlignment(Align / 8);
579
Chris Lattner402b3372008-03-03 03:28:21 +0000580 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000581 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000582 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000583
584 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
585 // Prefaced with special LLVM marker to indicate that the name
586 // should not be munged.
587 GV->setName("\01" + ALA->getLabel());
588 }
Chris Lattner4b009652007-07-25 00:24:17 +0000589
590 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000591 if (D->getStorageClass() == VarDecl::Static)
592 GV->setLinkage(llvm::Function::InternalLinkage);
593 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000594 GV->setLinkage(llvm::Function::DLLImportLinkage);
595 else if (D->getAttr<DLLExportAttr>())
596 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000597 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000598 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000599 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000600 // FIXME: This isn't right. This should handle common linkage and other
601 // stuff.
602 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000603 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000604 case VarDecl::Auto:
605 case VarDecl::Register:
606 assert(0 && "Can't have auto or register globals");
607 case VarDecl::None:
608 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000609 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000610 break;
611 case VarDecl::Extern:
612 case VarDecl::PrivateExtern:
613 // todo: common
614 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000615 }
Chris Lattner4b009652007-07-25 00:24:17 +0000616 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000617
618 // Emit global variable debug information.
619 CGDebugInfo *DI = getDebugInfo();
620 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000621 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000622 DI->EmitGlobalVariable(GV, D);
623 }
Chris Lattner4b009652007-07-25 00:24:17 +0000624}
625
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000626llvm::GlobalValue *
627CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000628 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
629 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
630 llvm::Function::ExternalLinkage,
631 D->getName(), &getModule());
632 SetFunctionAttributes(D, F);
633 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000634}
635
636llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000637 QualType ASTTy = D->getType();
638 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
639 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000640
641 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000642 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000643 if (!Entry)
644 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000645
Daniel Dunbar2188c532008-07-30 16:32:24 +0000646 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000647}
648
649void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000650 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000651 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000652 Entry = EmitForwardFunctionDefinition(D);
653 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000654 // If the types mismatch then we have to rewrite the definition.
655 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
656 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000657 // Otherwise, we have a definition after a prototype with the wrong type.
658 // F is the Function* for the one with the wrong type, we must make a new
659 // Function* and update everything that used F (a declaration) with the new
660 // Function* (which will be a definition).
661 //
662 // This happens if there is a prototype for a function (e.g. "int f()") and
663 // then a definition of a different type (e.g. "int f(int x)"). Start by
664 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000665 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
666 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000667
668 // Replace uses of F with the Function we will endow with a body.
669 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000670 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
671 Entry->replaceAllUsesWith(NewPtrForOldDecl);
672
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000673 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000674 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000675 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000676
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000677 Entry = NewFn;
678 }
679 }
680
Daniel Dunbar566a6502008-09-08 23:44:31 +0000681 llvm::Function *Fn = cast<llvm::Function>(Entry);
682 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000683
Daniel Dunbar566a6502008-09-08 23:44:31 +0000684 SetFunctionAttributesForDefinition(D, Fn);
685
686 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
687 AddGlobalCtor(Fn, CA->getPriority());
688 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
689 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000690 }
691}
692
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000693llvm::Function *
694CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
695 const std::string &Name) {
696 llvm::Function *Fn = llvm::Function::Create(FTy,
697 llvm::Function::ExternalLinkage,
698 "", &TheModule);
699 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
700 return Fn;
701}
702
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000703void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
704 // Make sure that this type is translated.
705 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000706}
707
708
Chris Lattnerab862cc2007-08-31 04:31:45 +0000709/// getBuiltinLibFunction
710llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000711 if (BuiltinID > BuiltinFunctions.size())
712 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000713
Chris Lattner9f2d6892007-12-13 00:38:03 +0000714 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
715 // a slot for it.
716 assert(BuiltinID && "Invalid Builtin ID");
717 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000718 if (FunctionSlot)
719 return FunctionSlot;
720
721 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
722
723 // Get the name, skip over the __builtin_ prefix.
724 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
725
726 // Get the type for the builtin.
727 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
728 const llvm::FunctionType *Ty =
729 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
730
731 // FIXME: This has a serious problem with code like this:
732 // void abs() {}
733 // ... __builtin_abs(x);
734 // The two versions of abs will collide. The fix is for the builtin to win,
735 // and for the existing one to be turned into a constantexpr cast of the
736 // builtin. In the case where the existing one is a static function, it
737 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000738 if (llvm::Function *Existing = getModule().getFunction(Name)) {
739 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
740 return FunctionSlot = Existing;
741 assert(Existing == 0 && "FIXME: Name collision");
742 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000743
744 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000745 return FunctionSlot =
746 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
747 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000748}
749
Chris Lattner4b23f942007-12-18 00:25:38 +0000750llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
751 unsigned NumTys) {
752 return llvm::Intrinsic::getDeclaration(&getModule(),
753 (llvm::Intrinsic::ID)IID, Tys, NumTys);
754}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000755
Chris Lattner4b009652007-07-25 00:24:17 +0000756llvm::Function *CodeGenModule::getMemCpyFn() {
757 if (MemCpyFn) return MemCpyFn;
758 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000759 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000760 default: assert(0 && "Unknown ptr width");
761 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
762 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
763 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000764 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000765}
Anders Carlsson36a04872007-08-21 00:21:21 +0000766
Eli Friedman8f08a252008-05-26 12:59:39 +0000767llvm::Function *CodeGenModule::getMemMoveFn() {
768 if (MemMoveFn) return MemMoveFn;
769 llvm::Intrinsic::ID IID;
770 switch (Context.Target.getPointerWidth(0)) {
771 default: assert(0 && "Unknown ptr width");
772 case 32: IID = llvm::Intrinsic::memmove_i32; break;
773 case 64: IID = llvm::Intrinsic::memmove_i64; break;
774 }
775 return MemMoveFn = getIntrinsic(IID);
776}
777
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000778llvm::Function *CodeGenModule::getMemSetFn() {
779 if (MemSetFn) return MemSetFn;
780 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000781 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000782 default: assert(0 && "Unknown ptr width");
783 case 32: IID = llvm::Intrinsic::memset_i32; break;
784 case 64: IID = llvm::Intrinsic::memset_i64; break;
785 }
786 return MemSetFn = getIntrinsic(IID);
787}
Chris Lattner4b23f942007-12-18 00:25:38 +0000788
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000789// We still need to work out the details of handling UTF-16.
790// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000791llvm::Constant *CodeGenModule::
792GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000793 llvm::StringMapEntry<llvm::Constant *> &Entry =
794 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
795
796 if (Entry.getValue())
797 return Entry.getValue();
798
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000799 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
800 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000801
802 if (!CFConstantStringClassRef) {
803 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
804 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000805
806 // FIXME: This is fairly broken if
807 // __CFConstantStringClassReference is already defined, in that it
808 // will get renamed and the user will most likely see an opaque
809 // error message. This is a general issue with relying on
810 // particular names.
811 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000812 new llvm::GlobalVariable(Ty, false,
813 llvm::GlobalVariable::ExternalLinkage, 0,
814 "__CFConstantStringClassReference",
815 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000816
817 // Decay array -> ptr
818 CFConstantStringClassRef =
819 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000820 }
821
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000822 std::vector<llvm::Constant*> Fields(4);
823
Anders Carlsson36a04872007-08-21 00:21:21 +0000824 // Class pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000825 Fields[0] = CFConstantStringClassRef;
Anders Carlsson36a04872007-08-21 00:21:21 +0000826
827 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000828 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
829 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlsson36a04872007-08-21 00:21:21 +0000830
831 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000832 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000833 C = new llvm::GlobalVariable(C->getType(), true,
834 llvm::GlobalValue::InternalLinkage,
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000835 C, ".str", &getModule());
836 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000837
838 // String length.
839 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000840 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlsson36a04872007-08-21 00:21:21 +0000841
842 // The struct.
843 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
844 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000845 llvm::GlobalVariable *GV =
846 new llvm::GlobalVariable(C->getType(), true,
847 llvm::GlobalVariable::InternalLinkage,
848 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000849
Anders Carlsson9be009e2007-11-01 00:41:52 +0000850 GV->setSection("__DATA,__cfstring");
851 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000852
Anders Carlsson9be009e2007-11-01 00:41:52 +0000853 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000854}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000855
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000856/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000857/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000858std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000859 if (E->isWide()) {
860 ErrorUnsupported(E, "wide string");
861 return "FIXME";
862 }
863
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000864 const char *StrData = E->getStrData();
865 unsigned Len = E->getByteLength();
866
867 const ConstantArrayType *CAT =
868 getContext().getAsConstantArrayType(E->getType());
869 assert(CAT && "String isn't pointer or array!");
870
871 // Resize the string to the right size
872 // FIXME: What about wchar_t strings?
873 std::string Str(StrData, StrData+Len);
874 uint64_t RealLen = CAT->getSize().getZExtValue();
875 Str.resize(RealLen, '\0');
876
877 return Str;
878}
879
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000880/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
881/// constant array for the given string literal.
882llvm::Constant *
883CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
884 // FIXME: This can be more efficient.
885 return GetAddrOfConstantString(GetStringForStringLiteral(S));
886}
887
Chris Lattnera6dcce32008-02-11 00:02:17 +0000888/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000889static llvm::Constant *GenerateStringLiteral(const std::string &str,
890 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000891 CodeGenModule &CGM,
892 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000893 // Create Constant for this string literal. Don't add a '\0'.
894 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000895
896 // Create a global variable for this string
897 C = new llvm::GlobalVariable(C->getType(), constant,
898 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000899 C,
900 GlobalName ? GlobalName : ".str",
901 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000902
Chris Lattnerdb6be562007-11-28 05:34:05 +0000903 return C;
904}
905
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000906/// GetAddrOfConstantString - Returns a pointer to a character array
907/// containing the literal. This contents are exactly that of the
908/// given string, i.e. it will not be null terminated automatically;
909/// see GetAddrOfConstantCString. Note that whether the result is
910/// actually a pointer to an LLVM constant depends on
911/// Feature.WriteableStrings.
912///
913/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000914llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
915 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000916 // Don't share any string literals if writable-strings is turned on.
917 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000918 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000919
920 llvm::StringMapEntry<llvm::Constant *> &Entry =
921 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
922
923 if (Entry.getValue())
924 return Entry.getValue();
925
926 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000927 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000928 Entry.setValue(C);
929 return C;
930}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000931
932/// GetAddrOfConstantCString - Returns a pointer to a character
933/// array containing the literal and a terminating '\-'
934/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000935llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
936 const char *GlobalName){
937 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000938}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000939
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000940/// EmitObjCPropertyImplementations - Emit information for synthesized
941/// properties for an implementation.
942void CodeGenModule::EmitObjCPropertyImplementations(const
943 ObjCImplementationDecl *D) {
944 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
945 e = D->propimpl_end(); i != e; ++i) {
946 ObjCPropertyImplDecl *PID = *i;
947
948 // Dynamic is just for type-checking.
949 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
950 ObjCPropertyDecl *PD = PID->getPropertyDecl();
951
952 // Determine which methods need to be implemented, some may have
953 // been overridden. Note that ::isSynthesized is not the method
954 // we want, that just indicates if the decl came from a
955 // property. What we want to know is if the method is defined in
956 // this implementation.
957 if (!D->getInstanceMethod(PD->getGetterName()))
958 CodeGenFunction(*this).GenerateObjCGetter(PID);
959 if (!PD->isReadOnly() &&
960 !D->getInstanceMethod(PD->getSetterName()))
961 CodeGenFunction(*this).GenerateObjCSetter(PID);
962 }
963 }
964}
965
Daniel Dunbar27250d32008-08-15 23:26:23 +0000966/// EmitTopLevelDecl - Emit code for a single top level declaration.
967void CodeGenModule::EmitTopLevelDecl(Decl *D) {
968 // If an error has occurred, stop code generation, but continue
969 // parsing and semantic analysis (to ensure all warnings and errors
970 // are emitted).
971 if (Diags.hasErrorOccurred())
972 return;
973
974 switch (D->getKind()) {
975 case Decl::Function:
976 case Decl::Var:
977 EmitGlobal(cast<ValueDecl>(D));
978 break;
979
980 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +0000981 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000982 break;
983
984 // Objective-C Decls
985
986 // Forward declarations, no (immediate) code generation.
987 case Decl::ObjCClass:
988 case Decl::ObjCCategory:
989 case Decl::ObjCForwardProtocol:
990 case Decl::ObjCInterface:
991 break;
992
993 case Decl::ObjCProtocol:
994 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
995 break;
996
997 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000998 // Categories have properties but don't support synthesize so we
999 // can ignore them here.
1000
Daniel Dunbar27250d32008-08-15 23:26:23 +00001001 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1002 break;
1003
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001004 case Decl::ObjCImplementation: {
1005 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1006 EmitObjCPropertyImplementations(OMD);
1007 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001008 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001009 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001010 case Decl::ObjCMethod: {
1011 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1012 // If this is not a prototype, emit the body.
1013 if (OMD->getBody())
1014 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1015 break;
1016 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001017 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001018 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001019 break;
1020
1021 case Decl::LinkageSpec: {
1022 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1023 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001024 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001025 // FIXME: implement C++ linkage, C linkage works mostly by C
1026 // language reuse already.
1027 break;
1028 }
1029
1030 case Decl::FileScopeAsm: {
1031 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1032 std::string AsmString(AD->getAsmString()->getStrData(),
1033 AD->getAsmString()->getByteLength());
1034
1035 const std::string &S = getModule().getModuleInlineAsm();
1036 if (S.empty())
1037 getModule().setModuleInlineAsm(AsmString);
1038 else
1039 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1040 break;
1041 }
1042
1043 default:
1044 // Make sure we handled everything we should, every other kind is
1045 // a non-top-level decl. FIXME: Would be nice to have an
1046 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1047 // that easily.
1048 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1049 }
1050}
1051