blob: 866ba47b2a59f88e6e2aae32d393548dc9515a29 [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
47/// ReplaceMapValuesWith - This is a really slow and bad function that
48/// searches for any entries in GlobalDeclMap that point to OldVal, changing
49/// them to point to NewVal. This is badbadbad, FIXME!
50void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
51 llvm::Constant *NewVal) {
52 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
53 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
54 if (I->second == OldVal) I->second = NewVal;
55}
56
57
Chris Lattner1a3c1e22007-12-02 07:09:19 +000058llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
59 bool isDefinition) {
60 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000061 llvm::Constant *&Entry = GlobalDeclMap[D];
62 if (Entry) return Entry;
63
Chris Lattner1a3c1e22007-12-02 07:09:19 +000064 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
65
66 // Check to see if the function already exists.
67 llvm::Function *F = getModule().getFunction(D->getName());
68 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
69
70 // If it doesn't already exist, just create and return an entry.
71 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000072 // FIXME: param attributes for sext/zext etc.
73 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
74 D->getName(), &getModule());
75 }
76
Chris Lattner1a3c1e22007-12-02 07:09:19 +000077 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +000078 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +000079 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000080
Chris Lattner1a3c1e22007-12-02 07:09:19 +000081 // If this isn't a definition, just return it casted to the right type.
82 if (!isDefinition)
83 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
84
85 // Otherwise, we have a definition after a prototype with the wrong type.
86 // F is the Function* for the one with the wrong type, we must make a new
87 // Function* and update everything that used F (a declaration) with the new
88 // Function* (which will be a definition).
89 //
90 // This happens if there is a prototype for a function (e.g. "int f()") and
91 // then a definition of a different type (e.g. "int f(int x)"). Start by
92 // making a new function of the correct type, RAUW, then steal the name.
93 llvm::Function *NewFn = new llvm::Function(FTy,
94 llvm::Function::ExternalLinkage,
95 "", &getModule());
96 NewFn->takeName(F);
97
98 // Replace uses of F with the Function we will endow with a body.
99 llvm::Constant *NewPtrForOldDecl =
100 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
101 F->replaceAllUsesWith(NewPtrForOldDecl);
102
103 // FIXME: Update the globaldeclmap for the previous decl of this name. We
104 // really want a way to walk all of these, but we don't have it yet. This
105 // is incredibly slow!
106 ReplaceMapValuesWith(F, NewPtrForOldDecl);
107
108 // Ok, delete the old function now, which is dead.
109 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
110 F->eraseFromParent();
111
112 // Return the new function which has the right type.
113 return Entry = NewFn;
114}
115
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000116llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
117 bool isDefinition) {
118 assert(D->hasGlobalStorage() && "Not a global variable");
119
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000120 // See if it is already in the map.
121 llvm::Constant *&Entry = GlobalDeclMap[D];
122 if (Entry) return Entry;
123
124 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
125
126 // Check to see if the global already exists.
127 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
128
129 // If it doesn't already exist, just create and return an entry.
130 if (GV == 0) {
131 return Entry = new llvm::GlobalVariable(Ty, false,
132 llvm::GlobalValue::ExternalLinkage,
133 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000134 }
135
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000136 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000137 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000138 if (PTy == GV->getType()) return Entry = GV;
139
140 // If this isn't a definition, just return it casted to the right type.
141 if (!isDefinition)
142 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
143
144
145 // Otherwise, we have a definition after a prototype with the wrong type.
146 // GV is the GlobalVariable* for the one with the wrong type, we must make a
147 /// new GlobalVariable* and update everything that used GV (a declaration)
148 // with the new GlobalVariable* (which will be a definition).
149 //
150 // This happens if there is a prototype for a global (e.g. "extern int x[];")
151 // and then a definition of a different type (e.g. "int x[10];"). Start by
152 // making a new global of the correct type, RAUW, then steal the name.
153 llvm::GlobalVariable *NewGV =
154 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
155 0, D->getName(), &getModule());
156 NewGV->takeName(GV);
157
158 // Replace uses of GV with the globalvalue we will endow with a body.
159 llvm::Constant *NewPtrForOldDecl =
160 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
161 GV->replaceAllUsesWith(NewPtrForOldDecl);
162
163 // FIXME: Update the globaldeclmap for the previous decl of this name. We
164 // really want a way to walk all of these, but we don't have it yet. This
165 // is incredibly slow!
166 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
167
168 // Ok, delete the old global now, which is dead.
169 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
170 GV->eraseFromParent();
171
172 // Return the new global which has the right type.
173 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000174}
175
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000176
Chris Lattner4b009652007-07-25 00:24:17 +0000177void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
178 // If this is not a prototype, emit the body.
179 if (FD->getBody())
180 CodeGenFunction(*this).GenerateCode(FD);
181}
182
Chris Lattnercef01ec2007-11-23 22:07:55 +0000183static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000184 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000185
Chris Lattnercef01ec2007-11-23 22:07:55 +0000186/// GenerateConversionToBool - Generate comparison to zero for conversion to
187/// bool
188static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
189 QualType Source) {
190 if (Source->isRealFloatingType()) {
191 // Compare against 0.0 for fp scalars.
192 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
193 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
194 Zero);
195 }
196
197 assert((Source->isIntegerType() || Source->isPointerType()) &&
198 "Unknown scalar type to convert");
199
200 // Compare against an integer or pointer null.
201 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
202 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
203}
204
205/// GenerateConstantCast - Generates a constant cast to convert the Expression
206/// into the Target type.
207static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ab28c92007-12-09 00:36:01 +0000208 QualType Target,
209 CodeGenModule &CGM) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000210 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000211 QualType Source = Expression->getType().getCanonicalType();
212 Target = Target.getCanonicalType();
213
214 assert (!Target->isVoidType());
215
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000216 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000217
218 if (Source == Target)
219 return SubExpr;
220
221 // Handle conversions to bool first, they are special: comparisons against 0.
222 if (Target->isBooleanType())
223 return GenerateConversionToBool(SubExpr, Source);
224
225 const llvm::Type *SourceType = Types.ConvertType(Source);
226 const llvm::Type *TargetType = Types.ConvertType(Target);
227
228 // Ignore conversions like int -> uint.
229 if (SubExpr->getType() == TargetType)
230 return SubExpr;
231
232 // Handle pointer conversions next: pointers can only be converted to/from
233 // other pointers and integers.
234 if (isa<llvm::PointerType>(TargetType)) {
235 // The source value may be an integer, or a pointer.
236 if (isa<llvm::PointerType>(SubExpr->getType()))
237 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
238 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
239 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
240 }
241
242 if (isa<llvm::PointerType>(SourceType)) {
243 // Must be an ptr to int cast.
244 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
245 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
246 }
247
248 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
249 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
250 }
251
252 // Finally, we have the arithmetic types: real int/float.
253 if (isa<llvm::IntegerType>(SourceType)) {
254 bool InputSigned = Source->isSignedIntegerType();
255 if (isa<llvm::IntegerType>(TargetType))
256 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
257 InputSigned);
258 else if (InputSigned)
259 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
260 else
261 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
262 }
263
264 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
265 if (isa<llvm::IntegerType>(TargetType)) {
266 if (Target->isSignedIntegerType())
267 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
268 else
269 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
270 }
271
272 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
273 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
274 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
275 else
276 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
277
278 assert (!"Unsupported cast type in global intialiser.");
279 return 0;
280}
281
Chris Lattnercef01ec2007-11-23 22:07:55 +0000282/// GenerateAggregateInit - Generate a Constant initaliser for global array or
283/// struct typed variables.
284static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000285 CodeGenModule &CGM) {
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000286 if (ILE->getType()->isVoidType()) {
287 // FIXME: Remove this when sema of initializers is finished (and the code
288 // below).
289 CGM.WarnUnsupported(ILE, "initializer");
290 return 0;
291 }
292
293 assert((ILE->getType()->isArrayType() || ILE->getType()->isStructureType()) &&
294 "Bad type for init list!");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000295 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000296
297 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000298 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000299
Chris Lattnercef01ec2007-11-23 22:07:55 +0000300 const llvm::CompositeType *CType =
301 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
302 assert(CType);
303 std::vector<llvm::Constant*> Elts;
304
Christopher Lamb6db92f32007-12-02 08:49:54 +0000305 // Initialising an array requires us to automatically initialise any
306 // elements that have not been initialised explicitly
307 const llvm::ArrayType *AType = 0;
308 const llvm::Type *AElemTy = 0;
309 unsigned NumArrayElements = 0;
310
311 // If this is an array, we may have to truncate the initializer
312 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
313 NumArrayElements = AType->getNumElements();
314 AElemTy = AType->getElementType();
315 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
316 }
317
Devang Patel08a10cc2007-10-30 21:27:20 +0000318 // Copy initializer elements.
319 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000320 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000321 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000322 // FIXME: Remove this when sema of initializers is finished (and the code
323 // above).
324 if (C == 0 && ILE->getInit(i)->getType()->isVoidType()) {
325 if (ILE->getType()->isVoidType()) return 0;
326 return llvm::UndefValue::get(CType);
327 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000328 assert (C && "Failed to create initialiser expression");
329 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000330 }
331
Chris Lattnercef01ec2007-11-23 22:07:55 +0000332 if (ILE->getType()->isStructureType())
333 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000334
335 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000336 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000337
Chris Lattnercef01ec2007-11-23 22:07:55 +0000338 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000339 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000340 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000341
Chris Lattnercef01ec2007-11-23 22:07:55 +0000342 return llvm::ConstantArray::get(AType, Elts);
343}
344
345/// GenerateConstantExpr - Recursively builds a constant initialiser for the
346/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000347static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
348 CodeGenModule &CGM) {
349 CodeGenTypes& Types = CGM.getTypes();
350 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000351 assert ((Expression->isConstantExpr(Context, 0) ||
352 Expression->getStmtClass() == Stmt::InitListExprClass) &&
353 "Only constant global initialisers are supported.");
354
355 QualType type = Expression->getType().getCanonicalType();
356
357 if (type->isIntegerType()) {
358 llvm::APSInt
359 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
360 if (Expression->isIntegerConstantExpr(Value, Context)) {
361 return llvm::ConstantInt::get(Value);
362 }
363 }
364
365 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000366 default: break; // default emits a warning and returns bogus value.
367 case Stmt::DeclRefExprClass: {
368 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
370 return CGM.GetAddrOfFunctionDecl(FD, false);
371 break;
372 }
373
Chris Lattnercef01ec2007-11-23 22:07:55 +0000374 // Generate constant for floating point literal values.
375 case Stmt::FloatingLiteralClass: {
376 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
377 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
378 }
379
380 // Generate constant for string literal values.
381 case Stmt::StringLiteralClass: {
Chris Lattnerff1ccb02007-12-11 01:38:45 +0000382 const StringLiteral *String = cast<StringLiteral>(Expression);
383 const char *StrData = String->getStrData();
384 unsigned Len = String->getByteLength();
385
386 // If the string has a pointer type, emit it as a global and use the pointer
387 // to the global as its value.
388 if (String->getType()->isPointerType())
389 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
390
391 // Otherwise this must be a string initializing an array in a static
392 // initializer. Don't emit it as the address of the string, emit the string
393 // data itself as an inline array.
394 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
395 assert(CAT && "String isn't pointer or array!");
396
397 std::string Str(StrData, StrData + Len);
398 // Null terminate the string before potentially truncating it.
399 // FIXME: What about wchar_t strings?
400 Str.push_back(0);
401
402 uint64_t RealLen = CAT->getSize().getZExtValue();
403 // String or grow the initializer to the required size.
404 if (RealLen != Str.size())
405 Str.resize(RealLen);
406
407 return llvm::ConstantArray::get(Str, false);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000408 }
409
410 // Elide parenthesis.
411 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000412 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000413
414 // Generate constant for sizeof operator.
415 // FIXME: Need to support AlignOf
416 case Stmt::SizeOfAlignOfTypeExprClass: {
417 const SizeOfAlignOfTypeExpr *SOExpr =
418 cast<SizeOfAlignOfTypeExpr>(Expression);
419 assert (SOExpr->isSizeOf());
420 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
421 }
422
423 // Generate constant cast expressions.
424 case Stmt::CastExprClass:
425 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000426 CGM);
Chris Lattner62891ad2007-12-29 23:43:37 +0000427 case Stmt::UnaryOperatorClass: {
428 const UnaryOperator *Op = cast<UnaryOperator>(Expression);
429 llvm::Constant *SubExpr = GenerateConstantExpr(Op->getSubExpr(), CGM);
430 // FIXME: These aren't right for complex.
431 switch (Op->getOpcode()) {
432 default: break;
433 case UnaryOperator::Plus:
434 case UnaryOperator::Extension:
435 return SubExpr;
436 case UnaryOperator::Minus:
437 return llvm::ConstantExpr::getNeg(SubExpr);
438 case UnaryOperator::Not:
439 return llvm::ConstantExpr::getNot(SubExpr);
440 case UnaryOperator::LNot:
441 if (Op->getSubExpr()->getType()->isRealFloatingType()) {
442 // Compare against 0.0 for fp scalars.
443 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
444 SubExpr = llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, SubExpr,
445 Zero);
446 } else {
447 assert((Op->getSubExpr()->getType()->isIntegerType() ||
448 Op->getSubExpr()->getType()->isPointerType()) &&
449 "Unknown scalar type to convert");
450 // Compare against an integer or pointer null.
451 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
452 SubExpr = llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, SubExpr,
453 Zero);
454 }
455
456 return llvm::ConstantExpr::getZExt(SubExpr, Types.ConvertType(type));
457 //SizeOf, AlignOf, // [C99 6.5.3.4] Sizeof (expr, not type) operator.
458 //Real, Imag, // "__real expr"/"__imag expr" Extension.
459 //OffsetOf // __builtin_offsetof
460 }
461 break;
462 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000463 case Stmt::ImplicitCastExprClass: {
464 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000465
466 // If this is due to array->pointer conversion, emit the array expression as
467 // an l-value.
468 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000469 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000470 // The only thing that can have array type like this is a
471 // DeclRefExpr(FileVarDecl)?
472 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000473 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
474 llvm::Constant *C = CGM.GetAddrOfGlobalVar(VD, false);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000475 assert(isa<llvm::PointerType>(C->getType()) &&
476 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000477 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000478 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
479
480 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000481 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
482
483 // The resultant pointer type can be implicitly casted to other pointer
484 // types as well, for example void*.
485 const llvm::Type *DestPTy = Types.ConvertType(type);
486 assert(isa<llvm::PointerType>(DestPTy) &&
487 "Only expect implicit cast to pointer");
488 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000489 }
490
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000491 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000492 }
493
494 // Generate a constant array access expression
495 // FIXME: Clang's semantic analysis incorrectly prevents array access in
496 // global initialisers, preventing us from testing this.
497 case Stmt::ArraySubscriptExprClass: {
498 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000499 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
500 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000501 return llvm::ConstantExpr::getExtractElement(Base, Index);
502 }
503
504 // Generate a constant expression to initialise an aggregate type, such as
505 // an array or struct.
506 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000507 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000508 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000509
510 CGM.WarnUnsupported(Expression, "initializer");
511 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000512}
513
Oliver Hunt253e0a72007-12-02 00:11:25 +0000514llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
515 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000516}
517
Chris Lattner4b009652007-07-25 00:24:17 +0000518void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000519 // If this is just a forward declaration of the variable, don't emit it now,
520 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000521 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
522 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000523
524 // Get the global, forcing it to be a direct reference.
525 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000526 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000527
528 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000529 llvm::Constant *Init = 0;
530 if (D->getInit() == 0) {
531 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
532 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000533 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000534 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000535 if (D->getInit()->isIntegerConstantExpr(Value, Context))
536 Init = llvm::ConstantInt::get(Value);
537 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000538
Devang Patel08a10cc2007-10-30 21:27:20 +0000539 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000540 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000541
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000542 assert(GV->getType()->getElementType() == Init->getType() &&
543 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000544 GV->setInitializer(Init);
545
546 // Set the llvm linkage type as appropriate.
547 // FIXME: This isn't right. This should handle common linkage and other
548 // stuff.
549 switch (D->getStorageClass()) {
550 case VarDecl::Auto:
551 case VarDecl::Register:
552 assert(0 && "Can't have auto or register globals");
553 case VarDecl::None:
554 case VarDecl::Extern:
555 // todo: common
556 break;
557 case VarDecl::Static:
558 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
559 break;
560 }
561}
562
563/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
564/// declarator chain.
565void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
566 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
567 EmitGlobalVar(D);
568}
569
Chris Lattnerab862cc2007-08-31 04:31:45 +0000570/// getBuiltinLibFunction
571llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000572 if (BuiltinID > BuiltinFunctions.size())
573 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000574
Chris Lattner9f2d6892007-12-13 00:38:03 +0000575 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
576 // a slot for it.
577 assert(BuiltinID && "Invalid Builtin ID");
578 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000579 if (FunctionSlot)
580 return FunctionSlot;
581
582 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
583
584 // Get the name, skip over the __builtin_ prefix.
585 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
586
587 // Get the type for the builtin.
588 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
589 const llvm::FunctionType *Ty =
590 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
591
592 // FIXME: This has a serious problem with code like this:
593 // void abs() {}
594 // ... __builtin_abs(x);
595 // The two versions of abs will collide. The fix is for the builtin to win,
596 // and for the existing one to be turned into a constantexpr cast of the
597 // builtin. In the case where the existing one is a static function, it
598 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000599 if (llvm::Function *Existing = getModule().getFunction(Name)) {
600 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
601 return FunctionSlot = Existing;
602 assert(Existing == 0 && "FIXME: Name collision");
603 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000604
605 // FIXME: param attributes for sext/zext etc.
606 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
607 Name, &getModule());
608}
609
Chris Lattner4b23f942007-12-18 00:25:38 +0000610llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
611 unsigned NumTys) {
612 return llvm::Intrinsic::getDeclaration(&getModule(),
613 (llvm::Intrinsic::ID)IID, Tys, NumTys);
614}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000615
Chris Lattner4b009652007-07-25 00:24:17 +0000616llvm::Function *CodeGenModule::getMemCpyFn() {
617 if (MemCpyFn) return MemCpyFn;
618 llvm::Intrinsic::ID IID;
619 uint64_t Size; unsigned Align;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000620 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattner4b009652007-07-25 00:24:17 +0000621 switch (Size) {
622 default: assert(0 && "Unknown ptr width");
623 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
624 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
625 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000626 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000627}
Anders Carlsson36a04872007-08-21 00:21:21 +0000628
Chris Lattner4b23f942007-12-18 00:25:38 +0000629
Chris Lattnerab862cc2007-08-31 04:31:45 +0000630llvm::Constant *CodeGenModule::
631GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000632 llvm::StringMapEntry<llvm::Constant *> &Entry =
633 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
634
635 if (Entry.getValue())
636 return Entry.getValue();
637
638 std::vector<llvm::Constant*> Fields;
639
640 if (!CFConstantStringClassRef) {
641 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
642 Ty = llvm::ArrayType::get(Ty, 0);
643
644 CFConstantStringClassRef =
645 new llvm::GlobalVariable(Ty, false,
646 llvm::GlobalVariable::ExternalLinkage, 0,
647 "__CFConstantStringClassReference",
648 &getModule());
649 }
650
651 // Class pointer.
652 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
653 llvm::Constant *Zeros[] = { Zero, Zero };
654 llvm::Constant *C =
655 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
656 Fields.push_back(C);
657
658 // Flags.
659 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
660 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
661
662 // String pointer.
663 C = llvm::ConstantArray::get(str);
664 C = new llvm::GlobalVariable(C->getType(), true,
665 llvm::GlobalValue::InternalLinkage,
666 C, ".str", &getModule());
667
668 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
669 Fields.push_back(C);
670
671 // String length.
672 Ty = getTypes().ConvertType(getContext().LongTy);
673 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
674
675 // The struct.
676 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
677 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000678 llvm::GlobalVariable *GV =
679 new llvm::GlobalVariable(C->getType(), true,
680 llvm::GlobalVariable::InternalLinkage,
681 C, "", &getModule());
682 GV->setSection("__DATA,__cfstring");
683 Entry.setValue(GV);
684 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000685}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000686
687/// GenerateWritableString -- Creates storage for a string literal
688static llvm::Constant *GenerateStringLiteral(const std::string &str,
689 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000690 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000691 // Create Constant for this string literal
692 llvm::Constant *C=llvm::ConstantArray::get(str);
693
694 // Create a global variable for this string
695 C = new llvm::GlobalVariable(C->getType(), constant,
696 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000697 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000698 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
699 llvm::Constant *Zeros[] = { Zero, Zero };
700 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
701 return C;
702}
703
704/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
705/// element of a character array containing the literal.
706llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
707 // Don't share any string literals if writable-strings is turned on.
708 if (Features.WritableStrings)
709 return GenerateStringLiteral(str, false, *this);
710
711 llvm::StringMapEntry<llvm::Constant *> &Entry =
712 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
713
714 if (Entry.getValue())
715 return Entry.getValue();
716
717 // Create a global variable for this.
718 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
719 Entry.setValue(C);
720 return C;
721}