blob: bd4df467f6421c603154cf83eba5ec781e6daf81 [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: {
Chris Lattnerff1ccb02007-12-11 01:38:45 +0000365 const StringLiteral *String = cast<StringLiteral>(Expression);
366 const char *StrData = String->getStrData();
367 unsigned Len = String->getByteLength();
368
369 // If the string has a pointer type, emit it as a global and use the pointer
370 // to the global as its value.
371 if (String->getType()->isPointerType())
372 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
373
374 // Otherwise this must be a string initializing an array in a static
375 // initializer. Don't emit it as the address of the string, emit the string
376 // data itself as an inline array.
377 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
378 assert(CAT && "String isn't pointer or array!");
379
380 std::string Str(StrData, StrData + Len);
381 // Null terminate the string before potentially truncating it.
382 // FIXME: What about wchar_t strings?
383 Str.push_back(0);
384
385 uint64_t RealLen = CAT->getSize().getZExtValue();
386 // String or grow the initializer to the required size.
387 if (RealLen != Str.size())
388 Str.resize(RealLen);
389
390 return llvm::ConstantArray::get(Str, false);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000391 }
392
393 // Elide parenthesis.
394 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000395 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000396
397 // Generate constant for sizeof operator.
398 // FIXME: Need to support AlignOf
399 case Stmt::SizeOfAlignOfTypeExprClass: {
400 const SizeOfAlignOfTypeExpr *SOExpr =
401 cast<SizeOfAlignOfTypeExpr>(Expression);
402 assert (SOExpr->isSizeOf());
403 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
404 }
405
406 // Generate constant cast expressions.
407 case Stmt::CastExprClass:
408 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000409 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000410
411 case Stmt::ImplicitCastExprClass: {
412 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000413
414 // If this is due to array->pointer conversion, emit the array expression as
415 // an l-value.
416 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000417 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000418 // The only thing that can have array type like this is a
419 // DeclRefExpr(FileVarDecl)?
420 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
421 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
422 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
423 assert(isa<llvm::PointerType>(C->getType()) &&
424 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000425 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000426 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
427
428 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000429 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
430
431 // The resultant pointer type can be implicitly casted to other pointer
432 // types as well, for example void*.
433 const llvm::Type *DestPTy = Types.ConvertType(type);
434 assert(isa<llvm::PointerType>(DestPTy) &&
435 "Only expect implicit cast to pointer");
436 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000437 }
438
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000439 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000440 }
441
442 // Generate a constant array access expression
443 // FIXME: Clang's semantic analysis incorrectly prevents array access in
444 // global initialisers, preventing us from testing this.
445 case Stmt::ArraySubscriptExprClass: {
446 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000447 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
448 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000449 return llvm::ConstantExpr::getExtractElement(Base, Index);
450 }
451
452 // Generate a constant expression to initialise an aggregate type, such as
453 // an array or struct.
454 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000455 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000456 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000457
458 CGM.WarnUnsupported(Expression, "initializer");
459 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000460}
461
Oliver Hunt253e0a72007-12-02 00:11:25 +0000462llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
463 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000464}
465
Chris Lattner4b009652007-07-25 00:24:17 +0000466void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000467 // If this is just a forward declaration of the variable, don't emit it now,
468 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000469 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
470 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000471
472 // Get the global, forcing it to be a direct reference.
473 llvm::GlobalVariable *GV =
474 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
475
476 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000477 llvm::Constant *Init = 0;
478 if (D->getInit() == 0) {
479 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
480 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000481 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000482 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000483 if (D->getInit()->isIntegerConstantExpr(Value, Context))
484 Init = llvm::ConstantInt::get(Value);
485 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000486
Devang Patel08a10cc2007-10-30 21:27:20 +0000487 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000488 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000489
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000490 assert(GV->getType()->getElementType() == Init->getType() &&
491 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000492 GV->setInitializer(Init);
493
494 // Set the llvm linkage type as appropriate.
495 // FIXME: This isn't right. This should handle common linkage and other
496 // stuff.
497 switch (D->getStorageClass()) {
498 case VarDecl::Auto:
499 case VarDecl::Register:
500 assert(0 && "Can't have auto or register globals");
501 case VarDecl::None:
502 case VarDecl::Extern:
503 // todo: common
504 break;
505 case VarDecl::Static:
506 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
507 break;
508 }
509}
510
511/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
512/// declarator chain.
513void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
514 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
515 EmitGlobalVar(D);
516}
517
Chris Lattnerab862cc2007-08-31 04:31:45 +0000518/// getBuiltinLibFunction
519llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
520 if (BuiltinFunctions.size() <= BuiltinID)
521 BuiltinFunctions.resize(BuiltinID);
522
523 // Already available?
524 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
525 if (FunctionSlot)
526 return FunctionSlot;
527
528 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
529
530 // Get the name, skip over the __builtin_ prefix.
531 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
532
533 // Get the type for the builtin.
534 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
535 const llvm::FunctionType *Ty =
536 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
537
538 // FIXME: This has a serious problem with code like this:
539 // void abs() {}
540 // ... __builtin_abs(x);
541 // The two versions of abs will collide. The fix is for the builtin to win,
542 // and for the existing one to be turned into a constantexpr cast of the
543 // builtin. In the case where the existing one is a static function, it
544 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000545 if (llvm::Function *Existing = getModule().getFunction(Name)) {
546 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
547 return FunctionSlot = Existing;
548 assert(Existing == 0 && "FIXME: Name collision");
549 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000550
551 // FIXME: param attributes for sext/zext etc.
552 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
553 Name, &getModule());
554}
555
556
Chris Lattner4b009652007-07-25 00:24:17 +0000557llvm::Function *CodeGenModule::getMemCpyFn() {
558 if (MemCpyFn) return MemCpyFn;
559 llvm::Intrinsic::ID IID;
560 uint64_t Size; unsigned Align;
561 Context.Target.getPointerInfo(Size, Align, SourceLocation());
562 switch (Size) {
563 default: assert(0 && "Unknown ptr width");
564 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
565 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
566 }
567 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
568}
Anders Carlsson36a04872007-08-21 00:21:21 +0000569
Chris Lattnerab862cc2007-08-31 04:31:45 +0000570llvm::Constant *CodeGenModule::
571GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000572 llvm::StringMapEntry<llvm::Constant *> &Entry =
573 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
574
575 if (Entry.getValue())
576 return Entry.getValue();
577
578 std::vector<llvm::Constant*> Fields;
579
580 if (!CFConstantStringClassRef) {
581 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
582 Ty = llvm::ArrayType::get(Ty, 0);
583
584 CFConstantStringClassRef =
585 new llvm::GlobalVariable(Ty, false,
586 llvm::GlobalVariable::ExternalLinkage, 0,
587 "__CFConstantStringClassReference",
588 &getModule());
589 }
590
591 // Class pointer.
592 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
593 llvm::Constant *Zeros[] = { Zero, Zero };
594 llvm::Constant *C =
595 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
596 Fields.push_back(C);
597
598 // Flags.
599 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
600 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
601
602 // String pointer.
603 C = llvm::ConstantArray::get(str);
604 C = new llvm::GlobalVariable(C->getType(), true,
605 llvm::GlobalValue::InternalLinkage,
606 C, ".str", &getModule());
607
608 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
609 Fields.push_back(C);
610
611 // String length.
612 Ty = getTypes().ConvertType(getContext().LongTy);
613 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
614
615 // The struct.
616 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
617 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000618 llvm::GlobalVariable *GV =
619 new llvm::GlobalVariable(C->getType(), true,
620 llvm::GlobalVariable::InternalLinkage,
621 C, "", &getModule());
622 GV->setSection("__DATA,__cfstring");
623 Entry.setValue(GV);
624 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000625}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000626
627/// GenerateWritableString -- Creates storage for a string literal
628static llvm::Constant *GenerateStringLiteral(const std::string &str,
629 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000630 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000631 // Create Constant for this string literal
632 llvm::Constant *C=llvm::ConstantArray::get(str);
633
634 // Create a global variable for this string
635 C = new llvm::GlobalVariable(C->getType(), constant,
636 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000637 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000638 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
639 llvm::Constant *Zeros[] = { Zero, Zero };
640 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
641 return C;
642}
643
644/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
645/// element of a character array containing the literal.
646llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
647 // Don't share any string literals if writable-strings is turned on.
648 if (Features.WritableStrings)
649 return GenerateStringLiteral(str, false, *this);
650
651 llvm::StringMapEntry<llvm::Constant *> &Entry =
652 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
653
654 if (Entry.getValue())
655 return Entry.getValue();
656
657 // Create a global variable for this.
658 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
659 Entry.setValue(C);
660 return C;
661}