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