blob: e841ee54926774406c191ea634bf91a5a91332a9 [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
Chris Lattnercef01ec2007-11-23 22:07:55 +0000193static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000194 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000195
Chris Lattnercef01ec2007-11-23 22:07:55 +0000196/// GenerateConversionToBool - Generate comparison to zero for conversion to
197/// bool
198static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
199 QualType Source) {
200 if (Source->isRealFloatingType()) {
201 // Compare against 0.0 for fp scalars.
202 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
203 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
204 Zero);
205 }
206
207 assert((Source->isIntegerType() || Source->isPointerType()) &&
208 "Unknown scalar type to convert");
209
210 // Compare against an integer or pointer null.
211 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
212 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
213}
214
215/// GenerateConstantCast - Generates a constant cast to convert the Expression
216/// into the Target type.
217static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ab28c92007-12-09 00:36:01 +0000218 QualType Target,
219 CodeGenModule &CGM) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000220 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000221 QualType Source = Expression->getType().getCanonicalType();
222 Target = Target.getCanonicalType();
223
224 assert (!Target->isVoidType());
225
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000226 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000227
228 if (Source == Target)
229 return SubExpr;
230
231 // Handle conversions to bool first, they are special: comparisons against 0.
232 if (Target->isBooleanType())
233 return GenerateConversionToBool(SubExpr, Source);
234
235 const llvm::Type *SourceType = Types.ConvertType(Source);
236 const llvm::Type *TargetType = Types.ConvertType(Target);
237
238 // Ignore conversions like int -> uint.
239 if (SubExpr->getType() == TargetType)
240 return SubExpr;
241
242 // Handle pointer conversions next: pointers can only be converted to/from
243 // other pointers and integers.
244 if (isa<llvm::PointerType>(TargetType)) {
245 // The source value may be an integer, or a pointer.
246 if (isa<llvm::PointerType>(SubExpr->getType()))
247 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
248 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
249 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
250 }
251
252 if (isa<llvm::PointerType>(SourceType)) {
253 // Must be an ptr to int cast.
254 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
255 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
256 }
257
258 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
259 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
260 }
261
262 // Finally, we have the arithmetic types: real int/float.
263 if (isa<llvm::IntegerType>(SourceType)) {
264 bool InputSigned = Source->isSignedIntegerType();
265 if (isa<llvm::IntegerType>(TargetType))
266 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
267 InputSigned);
268 else if (InputSigned)
269 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
270 else
271 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
272 }
273
274 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
275 if (isa<llvm::IntegerType>(TargetType)) {
276 if (Target->isSignedIntegerType())
277 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
278 else
279 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
280 }
281
282 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
283 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
284 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
285 else
286 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
287
288 assert (!"Unsupported cast type in global intialiser.");
289 return 0;
290}
291
Chris Lattnercef01ec2007-11-23 22:07:55 +0000292/// GenerateAggregateInit - Generate a Constant initaliser for global array or
293/// struct typed variables.
294static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000295 CodeGenModule &CGM) {
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000296 if (ILE->getType()->isVoidType()) {
297 // FIXME: Remove this when sema of initializers is finished (and the code
298 // below).
299 CGM.WarnUnsupported(ILE, "initializer");
300 return 0;
301 }
302
Nate Begemanc4e28e42008-01-25 05:34:48 +0000303 assert((ILE->getType()->isArrayType() || ILE->getType()->isStructureType() ||
304 ILE->getType()->isVectorType()) &&
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000305 "Bad type for init list!");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000306 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000307
308 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000309 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000310
Chris Lattnercef01ec2007-11-23 22:07:55 +0000311 const llvm::CompositeType *CType =
312 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
313 assert(CType);
314 std::vector<llvm::Constant*> Elts;
315
Christopher Lamb6db92f32007-12-02 08:49:54 +0000316 // Initialising an array requires us to automatically initialise any
317 // elements that have not been initialised explicitly
318 const llvm::ArrayType *AType = 0;
319 const llvm::Type *AElemTy = 0;
320 unsigned NumArrayElements = 0;
321
322 // If this is an array, we may have to truncate the initializer
323 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
324 NumArrayElements = AType->getNumElements();
325 AElemTy = AType->getElementType();
326 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
327 }
328
Devang Patel08a10cc2007-10-30 21:27:20 +0000329 // Copy initializer elements.
330 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000331 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000332 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000333 // FIXME: Remove this when sema of initializers is finished (and the code
334 // above).
335 if (C == 0 && ILE->getInit(i)->getType()->isVoidType()) {
336 if (ILE->getType()->isVoidType()) return 0;
337 return llvm::UndefValue::get(CType);
338 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000339 assert (C && "Failed to create initialiser expression");
340 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000341 }
342
Chris Lattnercef01ec2007-11-23 22:07:55 +0000343 if (ILE->getType()->isStructureType())
344 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000345
Nate Begemanc4e28e42008-01-25 05:34:48 +0000346 if (ILE->getType()->isVectorType())
347 return llvm::ConstantVector::get(cast<llvm::VectorType>(CType), Elts);
348
Christopher Lamb6db92f32007-12-02 08:49:54 +0000349 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000350 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000351
Chris Lattnercef01ec2007-11-23 22:07:55 +0000352 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000353 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000354 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000355
Chris Lattnercef01ec2007-11-23 22:07:55 +0000356 return llvm::ConstantArray::get(AType, Elts);
357}
358
359/// GenerateConstantExpr - Recursively builds a constant initialiser for the
360/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000361static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
362 CodeGenModule &CGM) {
363 CodeGenTypes& Types = CGM.getTypes();
364 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000365 assert ((Expression->isConstantExpr(Context, 0) ||
366 Expression->getStmtClass() == Stmt::InitListExprClass) &&
367 "Only constant global initialisers are supported.");
368
369 QualType type = Expression->getType().getCanonicalType();
370
371 if (type->isIntegerType()) {
372 llvm::APSInt
373 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
374 if (Expression->isIntegerConstantExpr(Value, Context)) {
375 return llvm::ConstantInt::get(Value);
376 }
377 }
378
379 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000380 default: break; // default emits a warning and returns bogus value.
381 case Stmt::DeclRefExprClass: {
382 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
383 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
384 return CGM.GetAddrOfFunctionDecl(FD, false);
385 break;
386 }
387
Chris Lattnercef01ec2007-11-23 22:07:55 +0000388 // Generate constant for floating point literal values.
389 case Stmt::FloatingLiteralClass: {
390 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
391 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
392 }
393
394 // Generate constant for string literal values.
395 case Stmt::StringLiteralClass: {
Chris Lattnerff1ccb02007-12-11 01:38:45 +0000396 const StringLiteral *String = cast<StringLiteral>(Expression);
397 const char *StrData = String->getStrData();
398 unsigned Len = String->getByteLength();
399
400 // If the string has a pointer type, emit it as a global and use the pointer
401 // to the global as its value.
402 if (String->getType()->isPointerType())
403 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
404
405 // Otherwise this must be a string initializing an array in a static
406 // initializer. Don't emit it as the address of the string, emit the string
407 // data itself as an inline array.
408 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
409 assert(CAT && "String isn't pointer or array!");
410
411 std::string Str(StrData, StrData + Len);
412 // Null terminate the string before potentially truncating it.
413 // FIXME: What about wchar_t strings?
414 Str.push_back(0);
415
416 uint64_t RealLen = CAT->getSize().getZExtValue();
417 // String or grow the initializer to the required size.
418 if (RealLen != Str.size())
419 Str.resize(RealLen);
420
421 return llvm::ConstantArray::get(Str, false);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000422 }
423
Nate Begemanc4e28e42008-01-25 05:34:48 +0000424 // Generate initializer for the CompoundLiteral
425 case Stmt::CompoundLiteralExprClass: {
426 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(Expression);
427 return GenerateConstantExpr(CLE->getInitializer(), CGM);
428 }
429
Chris Lattnercef01ec2007-11-23 22:07:55 +0000430 // Elide parenthesis.
431 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000432 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000433
434 // Generate constant for sizeof operator.
435 // FIXME: Need to support AlignOf
436 case Stmt::SizeOfAlignOfTypeExprClass: {
437 const SizeOfAlignOfTypeExpr *SOExpr =
438 cast<SizeOfAlignOfTypeExpr>(Expression);
439 assert (SOExpr->isSizeOf());
440 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
441 }
442
443 // Generate constant cast expressions.
444 case Stmt::CastExprClass:
445 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000446 CGM);
Chris Lattner62891ad2007-12-29 23:43:37 +0000447 case Stmt::UnaryOperatorClass: {
448 const UnaryOperator *Op = cast<UnaryOperator>(Expression);
449 llvm::Constant *SubExpr = GenerateConstantExpr(Op->getSubExpr(), CGM);
450 // FIXME: These aren't right for complex.
451 switch (Op->getOpcode()) {
452 default: break;
453 case UnaryOperator::Plus:
454 case UnaryOperator::Extension:
455 return SubExpr;
456 case UnaryOperator::Minus:
457 return llvm::ConstantExpr::getNeg(SubExpr);
458 case UnaryOperator::Not:
459 return llvm::ConstantExpr::getNot(SubExpr);
460 case UnaryOperator::LNot:
461 if (Op->getSubExpr()->getType()->isRealFloatingType()) {
462 // Compare against 0.0 for fp scalars.
463 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
464 SubExpr = llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, SubExpr,
465 Zero);
466 } else {
467 assert((Op->getSubExpr()->getType()->isIntegerType() ||
468 Op->getSubExpr()->getType()->isPointerType()) &&
469 "Unknown scalar type to convert");
470 // Compare against an integer or pointer null.
471 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
472 SubExpr = llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, SubExpr,
473 Zero);
474 }
475
476 return llvm::ConstantExpr::getZExt(SubExpr, Types.ConvertType(type));
477 //SizeOf, AlignOf, // [C99 6.5.3.4] Sizeof (expr, not type) operator.
478 //Real, Imag, // "__real expr"/"__imag expr" Extension.
479 //OffsetOf // __builtin_offsetof
480 }
481 break;
482 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000483 case Stmt::ImplicitCastExprClass: {
484 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000485
486 // If this is due to array->pointer conversion, emit the array expression as
487 // an l-value.
488 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000489 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000490 // The only thing that can have array type like this is a
491 // DeclRefExpr(FileVarDecl)?
492 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000493 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
494 llvm::Constant *C = CGM.GetAddrOfGlobalVar(VD, false);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000495 assert(isa<llvm::PointerType>(C->getType()) &&
496 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000497 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000498 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
499
500 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000501 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
502
503 // The resultant pointer type can be implicitly casted to other pointer
504 // types as well, for example void*.
505 const llvm::Type *DestPTy = Types.ConvertType(type);
506 assert(isa<llvm::PointerType>(DestPTy) &&
507 "Only expect implicit cast to pointer");
508 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000509 }
510
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000511 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000512 }
513
514 // Generate a constant array access expression
515 // FIXME: Clang's semantic analysis incorrectly prevents array access in
516 // global initialisers, preventing us from testing this.
517 case Stmt::ArraySubscriptExprClass: {
518 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000519 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
520 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000521 return llvm::ConstantExpr::getExtractElement(Base, Index);
522 }
523
524 // Generate a constant expression to initialise an aggregate type, such as
525 // an array or struct.
526 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000527 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000528 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000529
530 CGM.WarnUnsupported(Expression, "initializer");
531 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000532}
533
Oliver Hunt253e0a72007-12-02 00:11:25 +0000534llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
535 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000536}
537
Chris Lattner4b009652007-07-25 00:24:17 +0000538void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000539 // If this is just a forward declaration of the variable, don't emit it now,
540 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000541 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
542 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000543
544 // Get the global, forcing it to be a direct reference.
545 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000546 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000547
548 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000549 llvm::Constant *Init = 0;
550 if (D->getInit() == 0) {
551 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
552 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000553 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000554 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000555 if (D->getInit()->isIntegerConstantExpr(Value, Context))
556 Init = llvm::ConstantInt::get(Value);
557 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000558
Devang Patel08a10cc2007-10-30 21:27:20 +0000559 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000560 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000561
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000562 assert(GV->getType()->getElementType() == Init->getType() &&
563 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000564 GV->setInitializer(Init);
565
566 // Set the llvm linkage type as appropriate.
567 // FIXME: This isn't right. This should handle common linkage and other
568 // stuff.
569 switch (D->getStorageClass()) {
570 case VarDecl::Auto:
571 case VarDecl::Register:
572 assert(0 && "Can't have auto or register globals");
573 case VarDecl::None:
574 case VarDecl::Extern:
575 // todo: common
576 break;
577 case VarDecl::Static:
578 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
579 break;
580 }
581}
582
583/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
584/// declarator chain.
585void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
586 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
587 EmitGlobalVar(D);
588}
589
Chris Lattnerab862cc2007-08-31 04:31:45 +0000590/// getBuiltinLibFunction
591llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000592 if (BuiltinID > BuiltinFunctions.size())
593 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000594
Chris Lattner9f2d6892007-12-13 00:38:03 +0000595 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
596 // a slot for it.
597 assert(BuiltinID && "Invalid Builtin ID");
598 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000599 if (FunctionSlot)
600 return FunctionSlot;
601
602 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
603
604 // Get the name, skip over the __builtin_ prefix.
605 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
606
607 // Get the type for the builtin.
608 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
609 const llvm::FunctionType *Ty =
610 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
611
612 // FIXME: This has a serious problem with code like this:
613 // void abs() {}
614 // ... __builtin_abs(x);
615 // The two versions of abs will collide. The fix is for the builtin to win,
616 // and for the existing one to be turned into a constantexpr cast of the
617 // builtin. In the case where the existing one is a static function, it
618 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000619 if (llvm::Function *Existing = getModule().getFunction(Name)) {
620 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
621 return FunctionSlot = Existing;
622 assert(Existing == 0 && "FIXME: Name collision");
623 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000624
625 // FIXME: param attributes for sext/zext etc.
626 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
627 Name, &getModule());
628}
629
Chris Lattner4b23f942007-12-18 00:25:38 +0000630llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
631 unsigned NumTys) {
632 return llvm::Intrinsic::getDeclaration(&getModule(),
633 (llvm::Intrinsic::ID)IID, Tys, NumTys);
634}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000635
Chris Lattner4b009652007-07-25 00:24:17 +0000636llvm::Function *CodeGenModule::getMemCpyFn() {
637 if (MemCpyFn) return MemCpyFn;
638 llvm::Intrinsic::ID IID;
639 uint64_t Size; unsigned Align;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000640 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattner4b009652007-07-25 00:24:17 +0000641 switch (Size) {
642 default: assert(0 && "Unknown ptr width");
643 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
644 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
645 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000646 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000647}
Anders Carlsson36a04872007-08-21 00:21:21 +0000648
Chris Lattner4b23f942007-12-18 00:25:38 +0000649
Chris Lattnerab862cc2007-08-31 04:31:45 +0000650llvm::Constant *CodeGenModule::
651GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000652 llvm::StringMapEntry<llvm::Constant *> &Entry =
653 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
654
655 if (Entry.getValue())
656 return Entry.getValue();
657
658 std::vector<llvm::Constant*> Fields;
659
660 if (!CFConstantStringClassRef) {
661 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
662 Ty = llvm::ArrayType::get(Ty, 0);
663
664 CFConstantStringClassRef =
665 new llvm::GlobalVariable(Ty, false,
666 llvm::GlobalVariable::ExternalLinkage, 0,
667 "__CFConstantStringClassReference",
668 &getModule());
669 }
670
671 // Class pointer.
672 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
673 llvm::Constant *Zeros[] = { Zero, Zero };
674 llvm::Constant *C =
675 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
676 Fields.push_back(C);
677
678 // Flags.
679 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
680 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
681
682 // String pointer.
683 C = llvm::ConstantArray::get(str);
684 C = new llvm::GlobalVariable(C->getType(), true,
685 llvm::GlobalValue::InternalLinkage,
686 C, ".str", &getModule());
687
688 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
689 Fields.push_back(C);
690
691 // String length.
692 Ty = getTypes().ConvertType(getContext().LongTy);
693 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
694
695 // The struct.
696 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
697 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000698 llvm::GlobalVariable *GV =
699 new llvm::GlobalVariable(C->getType(), true,
700 llvm::GlobalVariable::InternalLinkage,
701 C, "", &getModule());
702 GV->setSection("__DATA,__cfstring");
703 Entry.setValue(GV);
704 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000705}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000706
707/// GenerateWritableString -- Creates storage for a string literal
708static llvm::Constant *GenerateStringLiteral(const std::string &str,
709 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000710 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000711 // Create Constant for this string literal
712 llvm::Constant *C=llvm::ConstantArray::get(str);
713
714 // Create a global variable for this string
715 C = new llvm::GlobalVariable(C->getType(), constant,
716 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000717 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000718 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
719 llvm::Constant *Zeros[] = { Zero, Zero };
720 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
721 return C;
722}
723
724/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
725/// element of a character array containing the literal.
726llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
727 // Don't share any string literals if writable-strings is turned on.
728 if (Features.WritableStrings)
729 return GenerateStringLiteral(str, false, *this);
730
731 llvm::StringMapEntry<llvm::Constant *> &Entry =
732 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
733
734 if (Entry.getValue())
735 return Entry.getValue();
736
737 // Create a global variable for this.
738 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
739 Entry.setValue(C);
740 return C;
741}