blob: 55336510c637b9f14de5066b58f3cc815bdefab8 [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 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;
43 getDiags().Report(S->getLocStart(), DiagID, &Msg, 1, &Range, 1);
44}
Chris Lattner0e4755d2007-12-02 06:27:33 +000045
46/// ReplaceMapValuesWith - This is a really slow and bad function that
47/// searches for any entries in GlobalDeclMap that point to OldVal, changing
48/// them to point to NewVal. This is badbadbad, FIXME!
49void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
50 llvm::Constant *NewVal) {
51 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
52 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
53 if (I->second == OldVal) I->second = NewVal;
54}
55
56
Chris Lattner1a3c1e22007-12-02 07:09:19 +000057llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
58 bool isDefinition) {
59 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000060 llvm::Constant *&Entry = GlobalDeclMap[D];
61 if (Entry) return Entry;
62
Chris Lattner1a3c1e22007-12-02 07:09:19 +000063 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
64
65 // Check to see if the function already exists.
66 llvm::Function *F = getModule().getFunction(D->getName());
67 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
68
69 // If it doesn't already exist, just create and return an entry.
70 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000071 // FIXME: param attributes for sext/zext etc.
72 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
73 D->getName(), &getModule());
74 }
75
Chris Lattner1a3c1e22007-12-02 07:09:19 +000076 // If the pointer type matches, just return it.
77 llvm::Type *PFTy = llvm::PointerType::get(Ty);
78 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000079
Chris Lattner1a3c1e22007-12-02 07:09:19 +000080 // If this isn't a definition, just return it casted to the right type.
81 if (!isDefinition)
82 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
83
84 // Otherwise, we have a definition after a prototype with the wrong type.
85 // F is the Function* for the one with the wrong type, we must make a new
86 // Function* and update everything that used F (a declaration) with the new
87 // Function* (which will be a definition).
88 //
89 // This happens if there is a prototype for a function (e.g. "int f()") and
90 // then a definition of a different type (e.g. "int f(int x)"). Start by
91 // making a new function of the correct type, RAUW, then steal the name.
92 llvm::Function *NewFn = new llvm::Function(FTy,
93 llvm::Function::ExternalLinkage,
94 "", &getModule());
95 NewFn->takeName(F);
96
97 // Replace uses of F with the Function we will endow with a body.
98 llvm::Constant *NewPtrForOldDecl =
99 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
100 F->replaceAllUsesWith(NewPtrForOldDecl);
101
102 // FIXME: Update the globaldeclmap for the previous decl of this name. We
103 // really want a way to walk all of these, but we don't have it yet. This
104 // is incredibly slow!
105 ReplaceMapValuesWith(F, NewPtrForOldDecl);
106
107 // Ok, delete the old function now, which is dead.
108 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
109 F->eraseFromParent();
110
111 // Return the new function which has the right type.
112 return Entry = NewFn;
113}
114
115llvm::Constant *CodeGenModule::GetAddrOfFileVarDecl(const FileVarDecl *D,
116 bool isDefinition) {
117 // See if it is already in the map.
118 llvm::Constant *&Entry = GlobalDeclMap[D];
119 if (Entry) return Entry;
120
121 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
122
123 // Check to see if the global already exists.
124 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
125
126 // If it doesn't already exist, just create and return an entry.
127 if (GV == 0) {
128 return Entry = new llvm::GlobalVariable(Ty, false,
129 llvm::GlobalValue::ExternalLinkage,
130 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000131 }
132
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000133 // If the pointer type matches, just return it.
134 llvm::Type *PTy = llvm::PointerType::get(Ty);
135 if (PTy == GV->getType()) return Entry = GV;
136
137 // If this isn't a definition, just return it casted to the right type.
138 if (!isDefinition)
139 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
140
141
142 // Otherwise, we have a definition after a prototype with the wrong type.
143 // GV is the GlobalVariable* for the one with the wrong type, we must make a
144 /// new GlobalVariable* and update everything that used GV (a declaration)
145 // with the new GlobalVariable* (which will be a definition).
146 //
147 // This happens if there is a prototype for a global (e.g. "extern int x[];")
148 // and then a definition of a different type (e.g. "int x[10];"). Start by
149 // making a new global of the correct type, RAUW, then steal the name.
150 llvm::GlobalVariable *NewGV =
151 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
152 0, D->getName(), &getModule());
153 NewGV->takeName(GV);
154
155 // Replace uses of GV with the globalvalue we will endow with a body.
156 llvm::Constant *NewPtrForOldDecl =
157 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
158 GV->replaceAllUsesWith(NewPtrForOldDecl);
159
160 // FIXME: Update the globaldeclmap for the previous decl of this name. We
161 // really want a way to walk all of these, but we don't have it yet. This
162 // is incredibly slow!
163 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
164
165 // Ok, delete the old global now, which is dead.
166 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
167 GV->eraseFromParent();
168
169 // Return the new global which has the right type.
170 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000171}
172
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000173
Chris Lattner4b009652007-07-25 00:24:17 +0000174void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
175 // If this is not a prototype, emit the body.
176 if (FD->getBody())
177 CodeGenFunction(*this).GenerateCode(FD);
178}
179
Chris Lattnercef01ec2007-11-23 22:07:55 +0000180static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000181 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000182
Chris Lattnercef01ec2007-11-23 22:07:55 +0000183/// GenerateConversionToBool - Generate comparison to zero for conversion to
184/// bool
185static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
186 QualType Source) {
187 if (Source->isRealFloatingType()) {
188 // Compare against 0.0 for fp scalars.
189 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
190 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
191 Zero);
192 }
193
194 assert((Source->isIntegerType() || Source->isPointerType()) &&
195 "Unknown scalar type to convert");
196
197 // Compare against an integer or pointer null.
198 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
199 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
200}
201
202/// GenerateConstantCast - Generates a constant cast to convert the Expression
203/// into the Target type.
204static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ab28c92007-12-09 00:36:01 +0000205 QualType Target,
206 CodeGenModule &CGM) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000207 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000208 QualType Source = Expression->getType().getCanonicalType();
209 Target = Target.getCanonicalType();
210
211 assert (!Target->isVoidType());
212
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000213 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000214
215 if (Source == Target)
216 return SubExpr;
217
218 // Handle conversions to bool first, they are special: comparisons against 0.
219 if (Target->isBooleanType())
220 return GenerateConversionToBool(SubExpr, Source);
221
222 const llvm::Type *SourceType = Types.ConvertType(Source);
223 const llvm::Type *TargetType = Types.ConvertType(Target);
224
225 // Ignore conversions like int -> uint.
226 if (SubExpr->getType() == TargetType)
227 return SubExpr;
228
229 // Handle pointer conversions next: pointers can only be converted to/from
230 // other pointers and integers.
231 if (isa<llvm::PointerType>(TargetType)) {
232 // The source value may be an integer, or a pointer.
233 if (isa<llvm::PointerType>(SubExpr->getType()))
234 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
235 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
236 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
237 }
238
239 if (isa<llvm::PointerType>(SourceType)) {
240 // Must be an ptr to int cast.
241 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
242 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
243 }
244
245 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
246 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
247 }
248
249 // Finally, we have the arithmetic types: real int/float.
250 if (isa<llvm::IntegerType>(SourceType)) {
251 bool InputSigned = Source->isSignedIntegerType();
252 if (isa<llvm::IntegerType>(TargetType))
253 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
254 InputSigned);
255 else if (InputSigned)
256 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
257 else
258 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
259 }
260
261 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
262 if (isa<llvm::IntegerType>(TargetType)) {
263 if (Target->isSignedIntegerType())
264 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
265 else
266 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
267 }
268
269 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
270 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
271 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
272 else
273 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
274
275 assert (!"Unsupported cast type in global intialiser.");
276 return 0;
277}
278
Chris Lattnercef01ec2007-11-23 22:07:55 +0000279/// GenerateAggregateInit - Generate a Constant initaliser for global array or
280/// struct typed variables.
281static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000282 CodeGenModule &CGM) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000283 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000284 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000285
286 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000287 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000288
Chris Lattnercef01ec2007-11-23 22:07:55 +0000289 const llvm::CompositeType *CType =
290 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
291 assert(CType);
292 std::vector<llvm::Constant*> Elts;
293
Christopher Lamb6db92f32007-12-02 08:49:54 +0000294 // Initialising an array requires us to automatically initialise any
295 // elements that have not been initialised explicitly
296 const llvm::ArrayType *AType = 0;
297 const llvm::Type *AElemTy = 0;
298 unsigned NumArrayElements = 0;
299
300 // If this is an array, we may have to truncate the initializer
301 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
302 NumArrayElements = AType->getNumElements();
303 AElemTy = AType->getElementType();
304 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
305 }
306
Devang Patel08a10cc2007-10-30 21:27:20 +0000307 // Copy initializer elements.
308 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000309 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000310 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000311 assert (C && "Failed to create initialiser expression");
312 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000313 }
314
Chris Lattnercef01ec2007-11-23 22:07:55 +0000315 if (ILE->getType()->isStructureType())
316 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000317
318 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000319 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000320
Chris Lattnercef01ec2007-11-23 22:07:55 +0000321 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000322 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000323 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000324
Chris Lattnercef01ec2007-11-23 22:07:55 +0000325 return llvm::ConstantArray::get(AType, Elts);
326}
327
328/// GenerateConstantExpr - Recursively builds a constant initialiser for the
329/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000330static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
331 CodeGenModule &CGM) {
332 CodeGenTypes& Types = CGM.getTypes();
333 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000334 assert ((Expression->isConstantExpr(Context, 0) ||
335 Expression->getStmtClass() == Stmt::InitListExprClass) &&
336 "Only constant global initialisers are supported.");
337
338 QualType type = Expression->getType().getCanonicalType();
339
340 if (type->isIntegerType()) {
341 llvm::APSInt
342 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
343 if (Expression->isIntegerConstantExpr(Value, Context)) {
344 return llvm::ConstantInt::get(Value);
345 }
346 }
347
348 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000349 default: break; // default emits a warning and returns bogus value.
350 case Stmt::DeclRefExprClass: {
351 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
352 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
353 return CGM.GetAddrOfFunctionDecl(FD, false);
354 break;
355 }
356
Chris Lattnercef01ec2007-11-23 22:07:55 +0000357 // Generate constant for floating point literal values.
358 case Stmt::FloatingLiteralClass: {
359 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
360 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
361 }
362
363 // Generate constant for string literal values.
364 case Stmt::StringLiteralClass: {
365 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000366 const char *StrData = SLiteral->getStrData();
367 unsigned Len = SLiteral->getByteLength();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000368 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000369 }
370
371 // Elide parenthesis.
372 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000373 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000374
375 // Generate constant for sizeof operator.
376 // FIXME: Need to support AlignOf
377 case Stmt::SizeOfAlignOfTypeExprClass: {
378 const SizeOfAlignOfTypeExpr *SOExpr =
379 cast<SizeOfAlignOfTypeExpr>(Expression);
380 assert (SOExpr->isSizeOf());
381 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
382 }
383
384 // Generate constant cast expressions.
385 case Stmt::CastExprClass:
386 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000387 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000388
389 case Stmt::ImplicitCastExprClass: {
390 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000391
392 // If this is due to array->pointer conversion, emit the array expression as
393 // an l-value.
394 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000395 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000396 // The only thing that can have array type like this is a
397 // DeclRefExpr(FileVarDecl)?
398 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
399 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
400 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
401 assert(isa<llvm::PointerType>(C->getType()) &&
402 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000403 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000404 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
405
406 llvm::Constant *Ops[] = {Idx0, Idx0};
407 return llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
408 }
409
Chris Lattner72c09732007-12-09 23:49:42 +0000410 // If this is an implicit cast of a string literal to an array type, this
411 // must be a string initializing an array. Don't emit it as the address of
412 // the string, emit the string data itself as an inline array.
413 if (const StringLiteral *String =
414 dyn_cast<StringLiteral>(ICExpr->getSubExpr()))
415 if (const ArrayType *AT = ICExpr->getType()->getAsArrayType()) {
416 // Verify that this is an array of char or wchar. Array of const char*
417 // can be initialized with a string literal, which does not expand the
418 // characters inline.
419 // FIXME: What about wchar_t??
420 if (AT->getElementType()->isCharType()) {
421 const char *StrData = String->getStrData();
422 unsigned Len = String->getByteLength();
423 llvm::Constant *C =
424 llvm::ConstantArray::get(std::string(StrData, StrData + Len));
425 // FIXME: This should return a string of the proper type: this
426 // mishandles things like 'char x[4] = "1234567";
427 return C;
428 }
429 }
430
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000431 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000432 }
433
434 // Generate a constant array access expression
435 // FIXME: Clang's semantic analysis incorrectly prevents array access in
436 // global initialisers, preventing us from testing this.
437 case Stmt::ArraySubscriptExprClass: {
438 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000439 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
440 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000441 return llvm::ConstantExpr::getExtractElement(Base, Index);
442 }
443
444 // Generate a constant expression to initialise an aggregate type, such as
445 // an array or struct.
446 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000447 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000448 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000449
450 CGM.WarnUnsupported(Expression, "initializer");
451 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000452}
453
Oliver Hunt253e0a72007-12-02 00:11:25 +0000454llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
455 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000456}
457
Chris Lattner4b009652007-07-25 00:24:17 +0000458void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000459 // If this is just a forward declaration of the variable, don't emit it now,
460 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000461 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
462 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000463
464 // Get the global, forcing it to be a direct reference.
465 llvm::GlobalVariable *GV =
466 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
467
468 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000469 llvm::Constant *Init = 0;
470 if (D->getInit() == 0) {
471 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
472 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000473 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000474 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000475 if (D->getInit()->isIntegerConstantExpr(Value, Context))
476 Init = llvm::ConstantInt::get(Value);
477 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000478
Devang Patel08a10cc2007-10-30 21:27:20 +0000479 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000480 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000481
Devang Patel08a10cc2007-10-30 21:27:20 +0000482 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000483
484 GV->setInitializer(Init);
485
486 // Set the llvm linkage type as appropriate.
487 // FIXME: This isn't right. This should handle common linkage and other
488 // stuff.
489 switch (D->getStorageClass()) {
490 case VarDecl::Auto:
491 case VarDecl::Register:
492 assert(0 && "Can't have auto or register globals");
493 case VarDecl::None:
494 case VarDecl::Extern:
495 // todo: common
496 break;
497 case VarDecl::Static:
498 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
499 break;
500 }
501}
502
503/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
504/// declarator chain.
505void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
506 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
507 EmitGlobalVar(D);
508}
509
Chris Lattnerab862cc2007-08-31 04:31:45 +0000510/// getBuiltinLibFunction
511llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
512 if (BuiltinFunctions.size() <= BuiltinID)
513 BuiltinFunctions.resize(BuiltinID);
514
515 // Already available?
516 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
517 if (FunctionSlot)
518 return FunctionSlot;
519
520 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
521
522 // Get the name, skip over the __builtin_ prefix.
523 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
524
525 // Get the type for the builtin.
526 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
527 const llvm::FunctionType *Ty =
528 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
529
530 // FIXME: This has a serious problem with code like this:
531 // void abs() {}
532 // ... __builtin_abs(x);
533 // The two versions of abs will collide. The fix is for the builtin to win,
534 // and for the existing one to be turned into a constantexpr cast of the
535 // builtin. In the case where the existing one is a static function, it
536 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000537 if (llvm::Function *Existing = getModule().getFunction(Name)) {
538 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
539 return FunctionSlot = Existing;
540 assert(Existing == 0 && "FIXME: Name collision");
541 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000542
543 // FIXME: param attributes for sext/zext etc.
544 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
545 Name, &getModule());
546}
547
548
Chris Lattner4b009652007-07-25 00:24:17 +0000549llvm::Function *CodeGenModule::getMemCpyFn() {
550 if (MemCpyFn) return MemCpyFn;
551 llvm::Intrinsic::ID IID;
552 uint64_t Size; unsigned Align;
553 Context.Target.getPointerInfo(Size, Align, SourceLocation());
554 switch (Size) {
555 default: assert(0 && "Unknown ptr width");
556 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
557 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
558 }
559 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
560}
Anders Carlsson36a04872007-08-21 00:21:21 +0000561
Chris Lattnerab862cc2007-08-31 04:31:45 +0000562llvm::Constant *CodeGenModule::
563GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000564 llvm::StringMapEntry<llvm::Constant *> &Entry =
565 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
566
567 if (Entry.getValue())
568 return Entry.getValue();
569
570 std::vector<llvm::Constant*> Fields;
571
572 if (!CFConstantStringClassRef) {
573 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
574 Ty = llvm::ArrayType::get(Ty, 0);
575
576 CFConstantStringClassRef =
577 new llvm::GlobalVariable(Ty, false,
578 llvm::GlobalVariable::ExternalLinkage, 0,
579 "__CFConstantStringClassReference",
580 &getModule());
581 }
582
583 // Class pointer.
584 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
585 llvm::Constant *Zeros[] = { Zero, Zero };
586 llvm::Constant *C =
587 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
588 Fields.push_back(C);
589
590 // Flags.
591 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
592 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
593
594 // String pointer.
595 C = llvm::ConstantArray::get(str);
596 C = new llvm::GlobalVariable(C->getType(), true,
597 llvm::GlobalValue::InternalLinkage,
598 C, ".str", &getModule());
599
600 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
601 Fields.push_back(C);
602
603 // String length.
604 Ty = getTypes().ConvertType(getContext().LongTy);
605 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
606
607 // The struct.
608 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
609 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000610 llvm::GlobalVariable *GV =
611 new llvm::GlobalVariable(C->getType(), true,
612 llvm::GlobalVariable::InternalLinkage,
613 C, "", &getModule());
614 GV->setSection("__DATA,__cfstring");
615 Entry.setValue(GV);
616 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000617}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000618
619/// GenerateWritableString -- Creates storage for a string literal
620static llvm::Constant *GenerateStringLiteral(const std::string &str,
621 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000622 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000623 // Create Constant for this string literal
624 llvm::Constant *C=llvm::ConstantArray::get(str);
625
626 // Create a global variable for this string
627 C = new llvm::GlobalVariable(C->getType(), constant,
628 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000629 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000630 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
631 llvm::Constant *Zeros[] = { Zero, Zero };
632 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
633 return C;
634}
635
636/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
637/// element of a character array containing the literal.
638llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
639 // Don't share any string literals if writable-strings is turned on.
640 if (Features.WritableStrings)
641 return GenerateStringLiteral(str, false, *this);
642
643 llvm::StringMapEntry<llvm::Constant *> &Entry =
644 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
645
646 if (Entry.getValue())
647 return Entry.getValue();
648
649 // Create a global variable for this.
650 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
651 Entry.setValue(C);
652 return C;
653}