blob: 54009b0e4235b60263f07f80473fe0ef698d023d [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Lattnerdb6be562007-11-28 05:34:05 +000018#include "clang/Basic/LangOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Basic/TargetInfo.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000022#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "llvm/Intrinsics.h"
24using namespace clang;
25using namespace CodeGen;
26
27
Chris Lattnerdb6be562007-11-28 05:34:05 +000028CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000029 llvm::Module &M, const llvm::TargetData &TD,
30 Diagnostic &diags)
31 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000032 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000033
Steve Naroffcb597472007-09-13 21:41:19 +000034llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +000035 // See if it is already in the map.
36 llvm::Constant *&Entry = GlobalDeclMap[D];
37 if (Entry) return Entry;
38
39 QualType ASTTy = cast<ValueDecl>(D)->getType();
40 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
41 if (isa<FunctionDecl>(D)) {
42 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
43 // FIXME: param attributes for sext/zext etc.
44 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
45 D->getName(), &getModule());
46 }
47
48 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
49
50 return Entry = new llvm::GlobalVariable(Ty, false,
51 llvm::GlobalValue::ExternalLinkage,
52 0, D->getName(), &getModule());
53}
54
55void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
56 // If this is not a prototype, emit the body.
57 if (FD->getBody())
58 CodeGenFunction(*this).GenerateCode(FD);
59}
60
Chris Lattnercef01ec2007-11-23 22:07:55 +000061static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
62 CodeGenModule& CGModule);
Devang Patel08a10cc2007-10-30 21:27:20 +000063
Chris Lattnercef01ec2007-11-23 22:07:55 +000064/// GenerateConversionToBool - Generate comparison to zero for conversion to
65/// bool
66static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
67 QualType Source) {
68 if (Source->isRealFloatingType()) {
69 // Compare against 0.0 for fp scalars.
70 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
71 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
72 Zero);
73 }
74
75 assert((Source->isIntegerType() || Source->isPointerType()) &&
76 "Unknown scalar type to convert");
77
78 // Compare against an integer or pointer null.
79 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
80 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
81}
82
83/// GenerateConstantCast - Generates a constant cast to convert the Expression
84/// into the Target type.
85static llvm::Constant *GenerateConstantCast(const Expr *Expression,
86 QualType Target,
87 CodeGenModule& CGModule) {
88 CodeGenTypes& Types = CGModule.getTypes();
89 QualType Source = Expression->getType().getCanonicalType();
90 Target = Target.getCanonicalType();
91
92 assert (!Target->isVoidType());
93
94 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGModule);
95
96 if (Source == Target)
97 return SubExpr;
98
99 // Handle conversions to bool first, they are special: comparisons against 0.
100 if (Target->isBooleanType())
101 return GenerateConversionToBool(SubExpr, Source);
102
103 const llvm::Type *SourceType = Types.ConvertType(Source);
104 const llvm::Type *TargetType = Types.ConvertType(Target);
105
106 // Ignore conversions like int -> uint.
107 if (SubExpr->getType() == TargetType)
108 return SubExpr;
109
110 // Handle pointer conversions next: pointers can only be converted to/from
111 // other pointers and integers.
112 if (isa<llvm::PointerType>(TargetType)) {
113 // The source value may be an integer, or a pointer.
114 if (isa<llvm::PointerType>(SubExpr->getType()))
115 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
116 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
117 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
118 }
119
120 if (isa<llvm::PointerType>(SourceType)) {
121 // Must be an ptr to int cast.
122 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
123 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
124 }
125
126 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
127 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
128 }
129
130 // Finally, we have the arithmetic types: real int/float.
131 if (isa<llvm::IntegerType>(SourceType)) {
132 bool InputSigned = Source->isSignedIntegerType();
133 if (isa<llvm::IntegerType>(TargetType))
134 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
135 InputSigned);
136 else if (InputSigned)
137 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
138 else
139 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
140 }
141
142 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
143 if (isa<llvm::IntegerType>(TargetType)) {
144 if (Target->isSignedIntegerType())
145 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
146 else
147 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
148 }
149
150 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
151 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
152 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
153 else
154 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
155
156 assert (!"Unsupported cast type in global intialiser.");
157 return 0;
158}
159
Chris Lattnercef01ec2007-11-23 22:07:55 +0000160/// GenerateAggregateInit - Generate a Constant initaliser for global array or
161/// struct typed variables.
162static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
163 CodeGenModule& CGModule) {
164 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
165 CodeGenTypes& Types = CGModule.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000166
167 unsigned NumInitElements = ILE->getNumInits();
168
Chris Lattnercef01ec2007-11-23 22:07:55 +0000169 const llvm::CompositeType *CType =
170 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
171 assert(CType);
172 std::vector<llvm::Constant*> Elts;
173
Devang Patel08a10cc2007-10-30 21:27:20 +0000174 // Copy initializer elements.
175 unsigned i = 0;
176 for (i = 0; i < NumInitElements; ++i) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000177 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGModule);
178 assert (C && "Failed to create initialiser expression");
179 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000180 }
181
Chris Lattnercef01ec2007-11-23 22:07:55 +0000182 if (ILE->getType()->isStructureType())
183 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
184
185 // Initialising an array requires us to automatically initialise any
186 // elements that have not been initialised explicitly
187 const llvm::ArrayType *AType = cast<llvm::ArrayType>(CType);
188 assert(AType);
Devang Patel08a10cc2007-10-30 21:27:20 +0000189 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000190 unsigned NumArrayElements = AType->getNumElements();
191 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000192 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000193 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel08a10cc2007-10-30 21:27:20 +0000194
Chris Lattnercef01ec2007-11-23 22:07:55 +0000195 return llvm::ConstantArray::get(AType, Elts);
196}
197
198/// GenerateConstantExpr - Recursively builds a constant initialiser for the
199/// given expression.
200static llvm::Constant *GenerateConstantExpr(const Expr* Expression,
201 CodeGenModule& CGModule) {
202 CodeGenTypes& Types = CGModule.getTypes();
203 ASTContext& Context = CGModule.getContext();
204 assert ((Expression->isConstantExpr(Context, 0) ||
205 Expression->getStmtClass() == Stmt::InitListExprClass) &&
206 "Only constant global initialisers are supported.");
207
208 QualType type = Expression->getType().getCanonicalType();
209
210 if (type->isIntegerType()) {
211 llvm::APSInt
212 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
213 if (Expression->isIntegerConstantExpr(Value, Context)) {
214 return llvm::ConstantInt::get(Value);
215 }
216 }
217
218 switch (Expression->getStmtClass()) {
219 // Generate constant for floating point literal values.
220 case Stmt::FloatingLiteralClass: {
221 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
222 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
223 }
224
225 // Generate constant for string literal values.
226 case Stmt::StringLiteralClass: {
227 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000228 const char *StrData = SLiteral->getStrData();
229 unsigned Len = SLiteral->getByteLength();
230 return CGModule.GetAddrOfConstantString(std::string(StrData,
231 StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000232 }
233
234 // Elide parenthesis.
235 case Stmt::ParenExprClass:
236 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(),
237 CGModule);
238
239 // Generate constant for sizeof operator.
240 // FIXME: Need to support AlignOf
241 case Stmt::SizeOfAlignOfTypeExprClass: {
242 const SizeOfAlignOfTypeExpr *SOExpr =
243 cast<SizeOfAlignOfTypeExpr>(Expression);
244 assert (SOExpr->isSizeOf());
245 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
246 }
247
248 // Generate constant cast expressions.
249 case Stmt::CastExprClass:
250 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
251 CGModule);
252
253 case Stmt::ImplicitCastExprClass: {
254 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
255 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGModule);
256 }
257
258 // Generate a constant array access expression
259 // FIXME: Clang's semantic analysis incorrectly prevents array access in
260 // global initialisers, preventing us from testing this.
261 case Stmt::ArraySubscriptExprClass: {
262 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
263 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGModule);
264 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGModule);
265 return llvm::ConstantExpr::getExtractElement(Base, Index);
266 }
267
268 // Generate a constant expression to initialise an aggregate type, such as
269 // an array or struct.
270 case Stmt::InitListExprClass:
271 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGModule);
272
273 default:
274 assert (!"Unsupported expression in global initialiser.");
275 }
276 return 0;
277}
278
Oliver Hunt253e0a72007-12-02 00:11:25 +0000279llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
280 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000281}
282
Chris Lattner4b009652007-07-25 00:24:17 +0000283void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
284 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
285
286 // If the storage class is external and there is no initializer, just leave it
287 // as a declaration.
288 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
289 return;
290
291 // Otherwise, convert the initializer, or use zero if appropriate.
292 llvm::Constant *Init = 0;
293 if (D->getInit() == 0) {
294 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
295 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000296 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000297 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000298 if (D->getInit()->isIntegerConstantExpr(Value, Context))
299 Init = llvm::ConstantInt::get(Value);
300 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000301
Devang Patel08a10cc2007-10-30 21:27:20 +0000302 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000303 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000304
Devang Patel08a10cc2007-10-30 21:27:20 +0000305 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000306
307 GV->setInitializer(Init);
308
309 // Set the llvm linkage type as appropriate.
310 // FIXME: This isn't right. This should handle common linkage and other
311 // stuff.
312 switch (D->getStorageClass()) {
313 case VarDecl::Auto:
314 case VarDecl::Register:
315 assert(0 && "Can't have auto or register globals");
316 case VarDecl::None:
317 case VarDecl::Extern:
318 // todo: common
319 break;
320 case VarDecl::Static:
321 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
322 break;
323 }
324}
325
326/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
327/// declarator chain.
328void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
329 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
330 EmitGlobalVar(D);
331}
332
Chris Lattnerab862cc2007-08-31 04:31:45 +0000333/// getBuiltinLibFunction
334llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
335 if (BuiltinFunctions.size() <= BuiltinID)
336 BuiltinFunctions.resize(BuiltinID);
337
338 // Already available?
339 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
340 if (FunctionSlot)
341 return FunctionSlot;
342
343 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
344
345 // Get the name, skip over the __builtin_ prefix.
346 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
347
348 // Get the type for the builtin.
349 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
350 const llvm::FunctionType *Ty =
351 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
352
353 // FIXME: This has a serious problem with code like this:
354 // void abs() {}
355 // ... __builtin_abs(x);
356 // The two versions of abs will collide. The fix is for the builtin to win,
357 // and for the existing one to be turned into a constantexpr cast of the
358 // builtin. In the case where the existing one is a static function, it
359 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000360 if (llvm::Function *Existing = getModule().getFunction(Name)) {
361 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
362 return FunctionSlot = Existing;
363 assert(Existing == 0 && "FIXME: Name collision");
364 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000365
366 // FIXME: param attributes for sext/zext etc.
367 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
368 Name, &getModule());
369}
370
371
Chris Lattner4b009652007-07-25 00:24:17 +0000372llvm::Function *CodeGenModule::getMemCpyFn() {
373 if (MemCpyFn) return MemCpyFn;
374 llvm::Intrinsic::ID IID;
375 uint64_t Size; unsigned Align;
376 Context.Target.getPointerInfo(Size, Align, SourceLocation());
377 switch (Size) {
378 default: assert(0 && "Unknown ptr width");
379 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
380 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
381 }
382 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
383}
Anders Carlsson36a04872007-08-21 00:21:21 +0000384
Chris Lattnerab862cc2007-08-31 04:31:45 +0000385llvm::Constant *CodeGenModule::
386GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000387 llvm::StringMapEntry<llvm::Constant *> &Entry =
388 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
389
390 if (Entry.getValue())
391 return Entry.getValue();
392
393 std::vector<llvm::Constant*> Fields;
394
395 if (!CFConstantStringClassRef) {
396 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
397 Ty = llvm::ArrayType::get(Ty, 0);
398
399 CFConstantStringClassRef =
400 new llvm::GlobalVariable(Ty, false,
401 llvm::GlobalVariable::ExternalLinkage, 0,
402 "__CFConstantStringClassReference",
403 &getModule());
404 }
405
406 // Class pointer.
407 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
408 llvm::Constant *Zeros[] = { Zero, Zero };
409 llvm::Constant *C =
410 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
411 Fields.push_back(C);
412
413 // Flags.
414 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
415 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
416
417 // String pointer.
418 C = llvm::ConstantArray::get(str);
419 C = new llvm::GlobalVariable(C->getType(), true,
420 llvm::GlobalValue::InternalLinkage,
421 C, ".str", &getModule());
422
423 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
424 Fields.push_back(C);
425
426 // String length.
427 Ty = getTypes().ConvertType(getContext().LongTy);
428 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
429
430 // The struct.
431 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
432 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000433 llvm::GlobalVariable *GV =
434 new llvm::GlobalVariable(C->getType(), true,
435 llvm::GlobalVariable::InternalLinkage,
436 C, "", &getModule());
437 GV->setSection("__DATA,__cfstring");
438 Entry.setValue(GV);
439 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000440}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000441
442/// GenerateWritableString -- Creates storage for a string literal
443static llvm::Constant *GenerateStringLiteral(const std::string &str,
444 bool constant,
445 CodeGenModule& CGModule) {
446 // Create Constant for this string literal
447 llvm::Constant *C=llvm::ConstantArray::get(str);
448
449 // Create a global variable for this string
450 C = new llvm::GlobalVariable(C->getType(), constant,
451 llvm::GlobalValue::InternalLinkage,
452 C, ".str", &CGModule.getModule());
453 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
454 llvm::Constant *Zeros[] = { Zero, Zero };
455 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
456 return C;
457}
458
459/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
460/// element of a character array containing the literal.
461llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
462 // Don't share any string literals if writable-strings is turned on.
463 if (Features.WritableStrings)
464 return GenerateStringLiteral(str, false, *this);
465
466 llvm::StringMapEntry<llvm::Constant *> &Entry =
467 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
468
469 if (Entry.getValue())
470 return Entry.getValue();
471
472 // Create a global variable for this.
473 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
474 Entry.setValue(C);
475 return C;
476}