blob: 76bf40353ae1f4a5c1f4e880b402f4e40a38c07d [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;
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
116llvm::Constant *CodeGenModule::GetAddrOfFileVarDecl(const FileVarDecl *D,
117 bool isDefinition) {
118 // See if it is already in the map.
119 llvm::Constant *&Entry = GlobalDeclMap[D];
120 if (Entry) return Entry;
121
122 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
123
124 // Check to see if the global already exists.
125 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
126
127 // If it doesn't already exist, just create and return an entry.
128 if (GV == 0) {
129 return Entry = new llvm::GlobalVariable(Ty, false,
130 llvm::GlobalValue::ExternalLinkage,
131 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000132 }
133
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000134 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000135 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000136 if (PTy == GV->getType()) return Entry = GV;
137
138 // If this isn't a definition, just return it casted to the right type.
139 if (!isDefinition)
140 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
141
142
143 // Otherwise, we have a definition after a prototype with the wrong type.
144 // GV is the GlobalVariable* for the one with the wrong type, we must make a
145 /// new GlobalVariable* and update everything that used GV (a declaration)
146 // with the new GlobalVariable* (which will be a definition).
147 //
148 // This happens if there is a prototype for a global (e.g. "extern int x[];")
149 // and then a definition of a different type (e.g. "int x[10];"). Start by
150 // making a new global of the correct type, RAUW, then steal the name.
151 llvm::GlobalVariable *NewGV =
152 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
153 0, D->getName(), &getModule());
154 NewGV->takeName(GV);
155
156 // Replace uses of GV with the globalvalue we will endow with a body.
157 llvm::Constant *NewPtrForOldDecl =
158 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
159 GV->replaceAllUsesWith(NewPtrForOldDecl);
160
161 // FIXME: Update the globaldeclmap for the previous decl of this name. We
162 // really want a way to walk all of these, but we don't have it yet. This
163 // is incredibly slow!
164 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
165
166 // Ok, delete the old global now, which is dead.
167 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
168 GV->eraseFromParent();
169
170 // Return the new global which has the right type.
171 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000172}
173
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000174
Chris Lattner4b009652007-07-25 00:24:17 +0000175void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
176 // If this is not a prototype, emit the body.
177 if (FD->getBody())
178 CodeGenFunction(*this).GenerateCode(FD);
179}
180
Chris Lattnercef01ec2007-11-23 22:07:55 +0000181static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000182 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000183
Chris Lattnercef01ec2007-11-23 22:07:55 +0000184/// GenerateConversionToBool - Generate comparison to zero for conversion to
185/// bool
186static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
187 QualType Source) {
188 if (Source->isRealFloatingType()) {
189 // Compare against 0.0 for fp scalars.
190 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
191 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
192 Zero);
193 }
194
195 assert((Source->isIntegerType() || Source->isPointerType()) &&
196 "Unknown scalar type to convert");
197
198 // Compare against an integer or pointer null.
199 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
200 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
201}
202
203/// GenerateConstantCast - Generates a constant cast to convert the Expression
204/// into the Target type.
205static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ab28c92007-12-09 00:36:01 +0000206 QualType Target,
207 CodeGenModule &CGM) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000208 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000209 QualType Source = Expression->getType().getCanonicalType();
210 Target = Target.getCanonicalType();
211
212 assert (!Target->isVoidType());
213
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000214 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000215
216 if (Source == Target)
217 return SubExpr;
218
219 // Handle conversions to bool first, they are special: comparisons against 0.
220 if (Target->isBooleanType())
221 return GenerateConversionToBool(SubExpr, Source);
222
223 const llvm::Type *SourceType = Types.ConvertType(Source);
224 const llvm::Type *TargetType = Types.ConvertType(Target);
225
226 // Ignore conversions like int -> uint.
227 if (SubExpr->getType() == TargetType)
228 return SubExpr;
229
230 // Handle pointer conversions next: pointers can only be converted to/from
231 // other pointers and integers.
232 if (isa<llvm::PointerType>(TargetType)) {
233 // The source value may be an integer, or a pointer.
234 if (isa<llvm::PointerType>(SubExpr->getType()))
235 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
236 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
237 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
238 }
239
240 if (isa<llvm::PointerType>(SourceType)) {
241 // Must be an ptr to int cast.
242 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
243 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
244 }
245
246 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
247 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
248 }
249
250 // Finally, we have the arithmetic types: real int/float.
251 if (isa<llvm::IntegerType>(SourceType)) {
252 bool InputSigned = Source->isSignedIntegerType();
253 if (isa<llvm::IntegerType>(TargetType))
254 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
255 InputSigned);
256 else if (InputSigned)
257 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
258 else
259 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
260 }
261
262 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
263 if (isa<llvm::IntegerType>(TargetType)) {
264 if (Target->isSignedIntegerType())
265 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
266 else
267 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
268 }
269
270 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
271 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
272 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
273 else
274 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
275
276 assert (!"Unsupported cast type in global intialiser.");
277 return 0;
278}
279
Chris Lattnercef01ec2007-11-23 22:07:55 +0000280/// GenerateAggregateInit - Generate a Constant initaliser for global array or
281/// struct typed variables.
282static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000283 CodeGenModule &CGM) {
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000284 if (ILE->getType()->isVoidType()) {
285 // FIXME: Remove this when sema of initializers is finished (and the code
286 // below).
287 CGM.WarnUnsupported(ILE, "initializer");
288 return 0;
289 }
290
291 assert((ILE->getType()->isArrayType() || ILE->getType()->isStructureType()) &&
292 "Bad type for init list!");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000293 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000294
295 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000296 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000297
Chris Lattnercef01ec2007-11-23 22:07:55 +0000298 const llvm::CompositeType *CType =
299 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
300 assert(CType);
301 std::vector<llvm::Constant*> Elts;
302
Christopher Lamb6db92f32007-12-02 08:49:54 +0000303 // Initialising an array requires us to automatically initialise any
304 // elements that have not been initialised explicitly
305 const llvm::ArrayType *AType = 0;
306 const llvm::Type *AElemTy = 0;
307 unsigned NumArrayElements = 0;
308
309 // If this is an array, we may have to truncate the initializer
310 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
311 NumArrayElements = AType->getNumElements();
312 AElemTy = AType->getElementType();
313 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
314 }
315
Devang Patel08a10cc2007-10-30 21:27:20 +0000316 // Copy initializer elements.
317 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000318 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000319 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnerf93e6db2007-12-17 05:17:42 +0000320 // FIXME: Remove this when sema of initializers is finished (and the code
321 // above).
322 if (C == 0 && ILE->getInit(i)->getType()->isVoidType()) {
323 if (ILE->getType()->isVoidType()) return 0;
324 return llvm::UndefValue::get(CType);
325 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000326 assert (C && "Failed to create initialiser expression");
327 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000328 }
329
Chris Lattnercef01ec2007-11-23 22:07:55 +0000330 if (ILE->getType()->isStructureType())
331 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000332
333 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000334 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000335
Chris Lattnercef01ec2007-11-23 22:07:55 +0000336 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000337 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000338 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000339
Chris Lattnercef01ec2007-11-23 22:07:55 +0000340 return llvm::ConstantArray::get(AType, Elts);
341}
342
343/// GenerateConstantExpr - Recursively builds a constant initialiser for the
344/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000345static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
346 CodeGenModule &CGM) {
347 CodeGenTypes& Types = CGM.getTypes();
348 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000349 assert ((Expression->isConstantExpr(Context, 0) ||
350 Expression->getStmtClass() == Stmt::InitListExprClass) &&
351 "Only constant global initialisers are supported.");
352
353 QualType type = Expression->getType().getCanonicalType();
354
355 if (type->isIntegerType()) {
356 llvm::APSInt
357 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
358 if (Expression->isIntegerConstantExpr(Value, Context)) {
359 return llvm::ConstantInt::get(Value);
360 }
361 }
362
363 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000364 default: break; // default emits a warning and returns bogus value.
365 case Stmt::DeclRefExprClass: {
366 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
367 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
368 return CGM.GetAddrOfFunctionDecl(FD, false);
369 break;
370 }
371
Chris Lattnercef01ec2007-11-23 22:07:55 +0000372 // Generate constant for floating point literal values.
373 case Stmt::FloatingLiteralClass: {
374 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
375 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
376 }
377
378 // Generate constant for string literal values.
379 case Stmt::StringLiteralClass: {
Chris Lattnerff1ccb02007-12-11 01:38:45 +0000380 const StringLiteral *String = cast<StringLiteral>(Expression);
381 const char *StrData = String->getStrData();
382 unsigned Len = String->getByteLength();
383
384 // If the string has a pointer type, emit it as a global and use the pointer
385 // to the global as its value.
386 if (String->getType()->isPointerType())
387 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
388
389 // Otherwise this must be a string initializing an array in a static
390 // initializer. Don't emit it as the address of the string, emit the string
391 // data itself as an inline array.
392 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
393 assert(CAT && "String isn't pointer or array!");
394
395 std::string Str(StrData, StrData + Len);
396 // Null terminate the string before potentially truncating it.
397 // FIXME: What about wchar_t strings?
398 Str.push_back(0);
399
400 uint64_t RealLen = CAT->getSize().getZExtValue();
401 // String or grow the initializer to the required size.
402 if (RealLen != Str.size())
403 Str.resize(RealLen);
404
405 return llvm::ConstantArray::get(Str, false);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000406 }
407
408 // Elide parenthesis.
409 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000410 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000411
412 // Generate constant for sizeof operator.
413 // FIXME: Need to support AlignOf
414 case Stmt::SizeOfAlignOfTypeExprClass: {
415 const SizeOfAlignOfTypeExpr *SOExpr =
416 cast<SizeOfAlignOfTypeExpr>(Expression);
417 assert (SOExpr->isSizeOf());
418 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
419 }
420
421 // Generate constant cast expressions.
422 case Stmt::CastExprClass:
423 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000424 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000425
426 case Stmt::ImplicitCastExprClass: {
427 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000428
429 // If this is due to array->pointer conversion, emit the array expression as
430 // an l-value.
431 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000432 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000433 // The only thing that can have array type like this is a
434 // DeclRefExpr(FileVarDecl)?
435 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
436 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
437 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
438 assert(isa<llvm::PointerType>(C->getType()) &&
439 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000440 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000441 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
442
443 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000444 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
445
446 // The resultant pointer type can be implicitly casted to other pointer
447 // types as well, for example void*.
448 const llvm::Type *DestPTy = Types.ConvertType(type);
449 assert(isa<llvm::PointerType>(DestPTy) &&
450 "Only expect implicit cast to pointer");
451 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000452 }
453
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000454 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000455 }
456
457 // Generate a constant array access expression
458 // FIXME: Clang's semantic analysis incorrectly prevents array access in
459 // global initialisers, preventing us from testing this.
460 case Stmt::ArraySubscriptExprClass: {
461 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000462 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
463 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000464 return llvm::ConstantExpr::getExtractElement(Base, Index);
465 }
466
467 // Generate a constant expression to initialise an aggregate type, such as
468 // an array or struct.
469 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000470 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000471 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000472
473 CGM.WarnUnsupported(Expression, "initializer");
474 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000475}
476
Oliver Hunt253e0a72007-12-02 00:11:25 +0000477llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
478 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000479}
480
Chris Lattner4b009652007-07-25 00:24:17 +0000481void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000482 // If this is just a forward declaration of the variable, don't emit it now,
483 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000484 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
485 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000486
487 // Get the global, forcing it to be a direct reference.
488 llvm::GlobalVariable *GV =
489 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
490
491 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000492 llvm::Constant *Init = 0;
493 if (D->getInit() == 0) {
494 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
495 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000496 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000497 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000498 if (D->getInit()->isIntegerConstantExpr(Value, Context))
499 Init = llvm::ConstantInt::get(Value);
500 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000501
Devang Patel08a10cc2007-10-30 21:27:20 +0000502 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000503 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000504
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000505 assert(GV->getType()->getElementType() == Init->getType() &&
506 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000507 GV->setInitializer(Init);
508
509 // Set the llvm linkage type as appropriate.
510 // FIXME: This isn't right. This should handle common linkage and other
511 // stuff.
512 switch (D->getStorageClass()) {
513 case VarDecl::Auto:
514 case VarDecl::Register:
515 assert(0 && "Can't have auto or register globals");
516 case VarDecl::None:
517 case VarDecl::Extern:
518 // todo: common
519 break;
520 case VarDecl::Static:
521 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
522 break;
523 }
524}
525
526/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
527/// declarator chain.
528void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
529 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
530 EmitGlobalVar(D);
531}
532
Chris Lattnerab862cc2007-08-31 04:31:45 +0000533/// getBuiltinLibFunction
534llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000535 if (BuiltinID > BuiltinFunctions.size())
536 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000537
Chris Lattner9f2d6892007-12-13 00:38:03 +0000538 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
539 // a slot for it.
540 assert(BuiltinID && "Invalid Builtin ID");
541 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000542 if (FunctionSlot)
543 return FunctionSlot;
544
545 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
546
547 // Get the name, skip over the __builtin_ prefix.
548 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
549
550 // Get the type for the builtin.
551 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
552 const llvm::FunctionType *Ty =
553 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
554
555 // FIXME: This has a serious problem with code like this:
556 // void abs() {}
557 // ... __builtin_abs(x);
558 // The two versions of abs will collide. The fix is for the builtin to win,
559 // and for the existing one to be turned into a constantexpr cast of the
560 // builtin. In the case where the existing one is a static function, it
561 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000562 if (llvm::Function *Existing = getModule().getFunction(Name)) {
563 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
564 return FunctionSlot = Existing;
565 assert(Existing == 0 && "FIXME: Name collision");
566 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000567
568 // FIXME: param attributes for sext/zext etc.
569 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
570 Name, &getModule());
571}
572
573
Chris Lattner4b009652007-07-25 00:24:17 +0000574llvm::Function *CodeGenModule::getMemCpyFn() {
575 if (MemCpyFn) return MemCpyFn;
576 llvm::Intrinsic::ID IID;
577 uint64_t Size; unsigned Align;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000578 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattner4b009652007-07-25 00:24:17 +0000579 switch (Size) {
580 default: assert(0 && "Unknown ptr width");
581 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
582 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
583 }
584 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
585}
Anders Carlsson36a04872007-08-21 00:21:21 +0000586
Chris Lattnerab862cc2007-08-31 04:31:45 +0000587llvm::Constant *CodeGenModule::
588GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000589 llvm::StringMapEntry<llvm::Constant *> &Entry =
590 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
591
592 if (Entry.getValue())
593 return Entry.getValue();
594
595 std::vector<llvm::Constant*> Fields;
596
597 if (!CFConstantStringClassRef) {
598 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
599 Ty = llvm::ArrayType::get(Ty, 0);
600
601 CFConstantStringClassRef =
602 new llvm::GlobalVariable(Ty, false,
603 llvm::GlobalVariable::ExternalLinkage, 0,
604 "__CFConstantStringClassReference",
605 &getModule());
606 }
607
608 // Class pointer.
609 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
610 llvm::Constant *Zeros[] = { Zero, Zero };
611 llvm::Constant *C =
612 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
613 Fields.push_back(C);
614
615 // Flags.
616 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
617 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
618
619 // String pointer.
620 C = llvm::ConstantArray::get(str);
621 C = new llvm::GlobalVariable(C->getType(), true,
622 llvm::GlobalValue::InternalLinkage,
623 C, ".str", &getModule());
624
625 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
626 Fields.push_back(C);
627
628 // String length.
629 Ty = getTypes().ConvertType(getContext().LongTy);
630 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
631
632 // The struct.
633 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
634 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000635 llvm::GlobalVariable *GV =
636 new llvm::GlobalVariable(C->getType(), true,
637 llvm::GlobalVariable::InternalLinkage,
638 C, "", &getModule());
639 GV->setSection("__DATA,__cfstring");
640 Entry.setValue(GV);
641 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000642}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000643
644/// GenerateWritableString -- Creates storage for a string literal
645static llvm::Constant *GenerateStringLiteral(const std::string &str,
646 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000647 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000648 // Create Constant for this string literal
649 llvm::Constant *C=llvm::ConstantArray::get(str);
650
651 // Create a global variable for this string
652 C = new llvm::GlobalVariable(C->getType(), constant,
653 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000654 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000655 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
656 llvm::Constant *Zeros[] = { Zero, Zero };
657 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
658 return C;
659}
660
661/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
662/// element of a character array containing the literal.
663llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
664 // Don't share any string literals if writable-strings is turned on.
665 if (Features.WritableStrings)
666 return GenerateStringLiteral(str, false, *this);
667
668 llvm::StringMapEntry<llvm::Constant *> &Entry =
669 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
670
671 if (Entry.getValue())
672 return Entry.getValue();
673
674 // Create a global variable for this.
675 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
676 Entry.setValue(C);
677 return C;
678}