blob: ee84f954c5632322d08790c981861d28667ca490 [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
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Basic/TargetInfo.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000025#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27using namespace CodeGen;
28
29
Chris Lattnerdb6be562007-11-28 05:34:05 +000030CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000031 llvm::Module &M, const llvm::TargetData &TD,
32 Diagnostic &diags)
33 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000034 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000035
Chris Lattnercf9c9d02007-12-02 07:19:18 +000036/// WarnUnsupported - Print out a warning that codegen doesn't support the
37/// specified stmt yet.
38void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
39 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
40 "cannot codegen this %0 yet");
41 SourceRange Range = S->getSourceRange();
42 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000043 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000044 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000045}
Chris Lattner0e4755d2007-12-02 06:27:33 +000046
Chris Lattner806a5f52008-01-12 07:05:38 +000047/// WarnUnsupported - Print out a warning that codegen doesn't support the
48/// specified decl yet.
49void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
50 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
51 "cannot codegen this %0 yet");
52 std::string Msg = Type;
53 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
54 &Msg, 1);
55}
56
Chris Lattner0e4755d2007-12-02 06:27:33 +000057/// ReplaceMapValuesWith - This is a really slow and bad function that
58/// searches for any entries in GlobalDeclMap that point to OldVal, changing
59/// them to point to NewVal. This is badbadbad, FIXME!
60void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
61 llvm::Constant *NewVal) {
62 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
63 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
64 if (I->second == OldVal) I->second = NewVal;
65}
66
67
Chris Lattner1a3c1e22007-12-02 07:09:19 +000068llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
69 bool isDefinition) {
70 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000071 llvm::Constant *&Entry = GlobalDeclMap[D];
72 if (Entry) return Entry;
73
Chris Lattner1a3c1e22007-12-02 07:09:19 +000074 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
75
76 // Check to see if the function already exists.
77 llvm::Function *F = getModule().getFunction(D->getName());
78 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
79
80 // If it doesn't already exist, just create and return an entry.
81 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000082 // FIXME: param attributes for sext/zext etc.
83 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
84 D->getName(), &getModule());
85 }
86
Chris Lattner1a3c1e22007-12-02 07:09:19 +000087 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +000088 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +000089 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000090
Chris Lattner1a3c1e22007-12-02 07:09:19 +000091 // If this isn't a definition, just return it casted to the right type.
92 if (!isDefinition)
93 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
94
95 // Otherwise, we have a definition after a prototype with the wrong type.
96 // F is the Function* for the one with the wrong type, we must make a new
97 // Function* and update everything that used F (a declaration) with the new
98 // Function* (which will be a definition).
99 //
100 // This happens if there is a prototype for a function (e.g. "int f()") and
101 // then a definition of a different type (e.g. "int f(int x)"). Start by
102 // making a new function of the correct type, RAUW, then steal the name.
103 llvm::Function *NewFn = new llvm::Function(FTy,
104 llvm::Function::ExternalLinkage,
105 "", &getModule());
106 NewFn->takeName(F);
107
108 // Replace uses of F with the Function we will endow with a body.
109 llvm::Constant *NewPtrForOldDecl =
110 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
111 F->replaceAllUsesWith(NewPtrForOldDecl);
112
113 // FIXME: Update the globaldeclmap for the previous decl of this name. We
114 // really want a way to walk all of these, but we don't have it yet. This
115 // is incredibly slow!
116 ReplaceMapValuesWith(F, NewPtrForOldDecl);
117
118 // Ok, delete the old function now, which is dead.
119 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
120 F->eraseFromParent();
121
122 // Return the new function which has the right type.
123 return Entry = NewFn;
124}
125
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000126llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
127 bool isDefinition) {
128 assert(D->hasGlobalStorage() && "Not a global variable");
129
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000130 // See if it is already in the map.
131 llvm::Constant *&Entry = GlobalDeclMap[D];
132 if (Entry) return Entry;
133
Chris Lattner43cdbf52008-01-09 18:47:25 +0000134 const llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000135
136 // Check to see if the global already exists.
137 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
138
139 // If it doesn't already exist, just create and return an entry.
140 if (GV == 0) {
141 return Entry = new llvm::GlobalVariable(Ty, false,
142 llvm::GlobalValue::ExternalLinkage,
143 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000144 }
145
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000146 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000147 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000148 if (PTy == GV->getType()) return Entry = GV;
149
150 // If this isn't a definition, just return it casted to the right type.
151 if (!isDefinition)
152 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
153
154
155 // Otherwise, we have a definition after a prototype with the wrong type.
156 // GV is the GlobalVariable* for the one with the wrong type, we must make a
157 /// new GlobalVariable* and update everything that used GV (a declaration)
158 // with the new GlobalVariable* (which will be a definition).
159 //
160 // This happens if there is a prototype for a global (e.g. "extern int x[];")
161 // and then a definition of a different type (e.g. "int x[10];"). Start by
162 // making a new global of the correct type, RAUW, then steal the name.
163 llvm::GlobalVariable *NewGV =
164 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
165 0, D->getName(), &getModule());
166 NewGV->takeName(GV);
167
168 // Replace uses of GV with the globalvalue we will endow with a body.
169 llvm::Constant *NewPtrForOldDecl =
170 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
171 GV->replaceAllUsesWith(NewPtrForOldDecl);
172
173 // FIXME: Update the globaldeclmap for the previous decl of this name. We
174 // really want a way to walk all of these, but we don't have it yet. This
175 // is incredibly slow!
176 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
177
178 // Ok, delete the old global now, which is dead.
179 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
180 GV->eraseFromParent();
181
182 // Return the new global which has the right type.
183 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000184}
185
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000186
Chris Lattner4b009652007-07-25 00:24:17 +0000187void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
188 // If this is not a prototype, emit the body.
189 if (FD->getBody())
190 CodeGenFunction(*this).GenerateCode(FD);
191}
192
Anders Carlssond76cead2008-01-26 01:36:00 +0000193llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
194 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000195}
196
Chris Lattner4b009652007-07-25 00:24:17 +0000197void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000198 // If this is just a forward declaration of the variable, don't emit it now,
199 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000200 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
201 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000202
203 // Get the global, forcing it to be a direct reference.
204 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000205 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000206
207 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000208 llvm::Constant *Init = 0;
209 if (D->getInit() == 0) {
210 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
211 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000212 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000213 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000214 if (D->getInit()->isIntegerConstantExpr(Value, Context))
215 Init = llvm::ConstantInt::get(Value);
216 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000217
Devang Patel08a10cc2007-10-30 21:27:20 +0000218 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000219 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000220
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000221 assert(GV->getType()->getElementType() == Init->getType() &&
222 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000223 GV->setInitializer(Init);
224
225 // Set the llvm linkage type as appropriate.
226 // FIXME: This isn't right. This should handle common linkage and other
227 // stuff.
228 switch (D->getStorageClass()) {
229 case VarDecl::Auto:
230 case VarDecl::Register:
231 assert(0 && "Can't have auto or register globals");
232 case VarDecl::None:
233 case VarDecl::Extern:
Steve Naroff1cbb2762008-01-25 22:14:40 +0000234 case VarDecl::PrivateExtern:
Chris Lattner4b009652007-07-25 00:24:17 +0000235 // todo: common
236 break;
237 case VarDecl::Static:
238 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
239 break;
240 }
241}
242
243/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
244/// declarator chain.
245void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
246 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
247 EmitGlobalVar(D);
248}
249
Chris Lattnerab862cc2007-08-31 04:31:45 +0000250/// getBuiltinLibFunction
251llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000252 if (BuiltinID > BuiltinFunctions.size())
253 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000254
Chris Lattner9f2d6892007-12-13 00:38:03 +0000255 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
256 // a slot for it.
257 assert(BuiltinID && "Invalid Builtin ID");
258 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000259 if (FunctionSlot)
260 return FunctionSlot;
261
262 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
263
264 // Get the name, skip over the __builtin_ prefix.
265 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
266
267 // Get the type for the builtin.
268 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
269 const llvm::FunctionType *Ty =
270 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
271
272 // FIXME: This has a serious problem with code like this:
273 // void abs() {}
274 // ... __builtin_abs(x);
275 // The two versions of abs will collide. The fix is for the builtin to win,
276 // and for the existing one to be turned into a constantexpr cast of the
277 // builtin. In the case where the existing one is a static function, it
278 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000279 if (llvm::Function *Existing = getModule().getFunction(Name)) {
280 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
281 return FunctionSlot = Existing;
282 assert(Existing == 0 && "FIXME: Name collision");
283 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000284
285 // FIXME: param attributes for sext/zext etc.
286 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
287 Name, &getModule());
288}
289
Chris Lattner4b23f942007-12-18 00:25:38 +0000290llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
291 unsigned NumTys) {
292 return llvm::Intrinsic::getDeclaration(&getModule(),
293 (llvm::Intrinsic::ID)IID, Tys, NumTys);
294}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000295
Chris Lattner4b009652007-07-25 00:24:17 +0000296llvm::Function *CodeGenModule::getMemCpyFn() {
297 if (MemCpyFn) return MemCpyFn;
298 llvm::Intrinsic::ID IID;
299 uint64_t Size; unsigned Align;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000300 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattner4b009652007-07-25 00:24:17 +0000301 switch (Size) {
302 default: assert(0 && "Unknown ptr width");
303 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
304 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
305 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000306 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000307}
Anders Carlsson36a04872007-08-21 00:21:21 +0000308
Chris Lattner4b23f942007-12-18 00:25:38 +0000309
Chris Lattnerab862cc2007-08-31 04:31:45 +0000310llvm::Constant *CodeGenModule::
311GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000312 llvm::StringMapEntry<llvm::Constant *> &Entry =
313 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
314
315 if (Entry.getValue())
316 return Entry.getValue();
317
318 std::vector<llvm::Constant*> Fields;
319
320 if (!CFConstantStringClassRef) {
321 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
322 Ty = llvm::ArrayType::get(Ty, 0);
323
324 CFConstantStringClassRef =
325 new llvm::GlobalVariable(Ty, false,
326 llvm::GlobalVariable::ExternalLinkage, 0,
327 "__CFConstantStringClassReference",
328 &getModule());
329 }
330
331 // Class pointer.
332 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
333 llvm::Constant *Zeros[] = { Zero, Zero };
334 llvm::Constant *C =
335 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
336 Fields.push_back(C);
337
338 // Flags.
339 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
340 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
341
342 // String pointer.
343 C = llvm::ConstantArray::get(str);
344 C = new llvm::GlobalVariable(C->getType(), true,
345 llvm::GlobalValue::InternalLinkage,
346 C, ".str", &getModule());
347
348 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
349 Fields.push_back(C);
350
351 // String length.
352 Ty = getTypes().ConvertType(getContext().LongTy);
353 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
354
355 // The struct.
356 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
357 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000358 llvm::GlobalVariable *GV =
359 new llvm::GlobalVariable(C->getType(), true,
360 llvm::GlobalVariable::InternalLinkage,
361 C, "", &getModule());
362 GV->setSection("__DATA,__cfstring");
363 Entry.setValue(GV);
364 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000365}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000366
367/// GenerateWritableString -- Creates storage for a string literal
368static llvm::Constant *GenerateStringLiteral(const std::string &str,
369 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000370 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000371 // Create Constant for this string literal
372 llvm::Constant *C=llvm::ConstantArray::get(str);
373
374 // Create a global variable for this string
375 C = new llvm::GlobalVariable(C->getType(), constant,
376 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000377 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000378 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
379 llvm::Constant *Zeros[] = { Zero, Zero };
380 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
381 return C;
382}
383
384/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
385/// element of a character array containing the literal.
386llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
387 // Don't share any string literals if writable-strings is turned on.
388 if (Features.WritableStrings)
389 return GenerateStringLiteral(str, false, *this);
390
391 llvm::StringMapEntry<llvm::Constant *> &Entry =
392 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
393
394 if (Entry.getValue())
395 return Entry.getValue();
396
397 // Create a global variable for this.
398 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
399 Entry.setValue(C);
400 return C;
401}