blob: 30e154755896a97f8e61b8587ef5c61c0a46491c [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.
78 llvm::Type *PFTy = llvm::PointerType::get(Ty);
79 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.
135 llvm::Type *PTy = llvm::PointerType::get(Ty);
136 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 Lattnercef01ec2007-11-23 22:07:55 +0000284 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000285 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000286
287 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000288 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000289
Chris Lattnercef01ec2007-11-23 22:07:55 +0000290 const llvm::CompositeType *CType =
291 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
292 assert(CType);
293 std::vector<llvm::Constant*> Elts;
294
Christopher Lamb6db92f32007-12-02 08:49:54 +0000295 // Initialising an array requires us to automatically initialise any
296 // elements that have not been initialised explicitly
297 const llvm::ArrayType *AType = 0;
298 const llvm::Type *AElemTy = 0;
299 unsigned NumArrayElements = 0;
300
301 // If this is an array, we may have to truncate the initializer
302 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
303 NumArrayElements = AType->getNumElements();
304 AElemTy = AType->getElementType();
305 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
306 }
307
Devang Patel08a10cc2007-10-30 21:27:20 +0000308 // Copy initializer elements.
309 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000310 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000311 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000312 assert (C && "Failed to create initialiser expression");
313 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000314 }
315
Chris Lattnercef01ec2007-11-23 22:07:55 +0000316 if (ILE->getType()->isStructureType())
317 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000318
319 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000320 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000321
Chris Lattnercef01ec2007-11-23 22:07:55 +0000322 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000323 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000324 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000325
Chris Lattnercef01ec2007-11-23 22:07:55 +0000326 return llvm::ConstantArray::get(AType, Elts);
327}
328
329/// GenerateConstantExpr - Recursively builds a constant initialiser for the
330/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000331static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
332 CodeGenModule &CGM) {
333 CodeGenTypes& Types = CGM.getTypes();
334 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000335 assert ((Expression->isConstantExpr(Context, 0) ||
336 Expression->getStmtClass() == Stmt::InitListExprClass) &&
337 "Only constant global initialisers are supported.");
338
339 QualType type = Expression->getType().getCanonicalType();
340
341 if (type->isIntegerType()) {
342 llvm::APSInt
343 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
344 if (Expression->isIntegerConstantExpr(Value, Context)) {
345 return llvm::ConstantInt::get(Value);
346 }
347 }
348
349 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000350 default: break; // default emits a warning and returns bogus value.
351 case Stmt::DeclRefExprClass: {
352 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
353 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
354 return CGM.GetAddrOfFunctionDecl(FD, false);
355 break;
356 }
357
Chris Lattnercef01ec2007-11-23 22:07:55 +0000358 // Generate constant for floating point literal values.
359 case Stmt::FloatingLiteralClass: {
360 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
361 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
362 }
363
364 // Generate constant for string literal values.
365 case Stmt::StringLiteralClass: {
Chris Lattnerff1ccb02007-12-11 01:38:45 +0000366 const StringLiteral *String = cast<StringLiteral>(Expression);
367 const char *StrData = String->getStrData();
368 unsigned Len = String->getByteLength();
369
370 // If the string has a pointer type, emit it as a global and use the pointer
371 // to the global as its value.
372 if (String->getType()->isPointerType())
373 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
374
375 // Otherwise this must be a string initializing an array in a static
376 // initializer. Don't emit it as the address of the string, emit the string
377 // data itself as an inline array.
378 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
379 assert(CAT && "String isn't pointer or array!");
380
381 std::string Str(StrData, StrData + Len);
382 // Null terminate the string before potentially truncating it.
383 // FIXME: What about wchar_t strings?
384 Str.push_back(0);
385
386 uint64_t RealLen = CAT->getSize().getZExtValue();
387 // String or grow the initializer to the required size.
388 if (RealLen != Str.size())
389 Str.resize(RealLen);
390
391 return llvm::ConstantArray::get(Str, false);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000392 }
393
394 // Elide parenthesis.
395 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000396 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000397
398 // Generate constant for sizeof operator.
399 // FIXME: Need to support AlignOf
400 case Stmt::SizeOfAlignOfTypeExprClass: {
401 const SizeOfAlignOfTypeExpr *SOExpr =
402 cast<SizeOfAlignOfTypeExpr>(Expression);
403 assert (SOExpr->isSizeOf());
404 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
405 }
406
407 // Generate constant cast expressions.
408 case Stmt::CastExprClass:
409 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000410 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000411
412 case Stmt::ImplicitCastExprClass: {
413 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000414
415 // If this is due to array->pointer conversion, emit the array expression as
416 // an l-value.
417 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000418 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000419 // The only thing that can have array type like this is a
420 // DeclRefExpr(FileVarDecl)?
421 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
422 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
423 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
424 assert(isa<llvm::PointerType>(C->getType()) &&
425 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000426 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000427 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
428
429 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000430 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
431
432 // The resultant pointer type can be implicitly casted to other pointer
433 // types as well, for example void*.
434 const llvm::Type *DestPTy = Types.ConvertType(type);
435 assert(isa<llvm::PointerType>(DestPTy) &&
436 "Only expect implicit cast to pointer");
437 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000438 }
439
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000440 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000441 }
442
443 // Generate a constant array access expression
444 // FIXME: Clang's semantic analysis incorrectly prevents array access in
445 // global initialisers, preventing us from testing this.
446 case Stmt::ArraySubscriptExprClass: {
447 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000448 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
449 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000450 return llvm::ConstantExpr::getExtractElement(Base, Index);
451 }
452
453 // Generate a constant expression to initialise an aggregate type, such as
454 // an array or struct.
455 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000456 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000457 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000458
459 CGM.WarnUnsupported(Expression, "initializer");
460 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000461}
462
Oliver Hunt253e0a72007-12-02 00:11:25 +0000463llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
464 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000465}
466
Chris Lattner4b009652007-07-25 00:24:17 +0000467void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000468 // If this is just a forward declaration of the variable, don't emit it now,
469 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000470 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
471 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000472
473 // Get the global, forcing it to be a direct reference.
474 llvm::GlobalVariable *GV =
475 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
476
477 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000478 llvm::Constant *Init = 0;
479 if (D->getInit() == 0) {
480 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
481 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000482 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000483 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000484 if (D->getInit()->isIntegerConstantExpr(Value, Context))
485 Init = llvm::ConstantInt::get(Value);
486 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000487
Devang Patel08a10cc2007-10-30 21:27:20 +0000488 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000489 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000490
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000491 assert(GV->getType()->getElementType() == Init->getType() &&
492 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000493 GV->setInitializer(Init);
494
495 // Set the llvm linkage type as appropriate.
496 // FIXME: This isn't right. This should handle common linkage and other
497 // stuff.
498 switch (D->getStorageClass()) {
499 case VarDecl::Auto:
500 case VarDecl::Register:
501 assert(0 && "Can't have auto or register globals");
502 case VarDecl::None:
503 case VarDecl::Extern:
504 // todo: common
505 break;
506 case VarDecl::Static:
507 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
508 break;
509 }
510}
511
512/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
513/// declarator chain.
514void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
515 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
516 EmitGlobalVar(D);
517}
518
Chris Lattnerab862cc2007-08-31 04:31:45 +0000519/// getBuiltinLibFunction
520llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
521 if (BuiltinFunctions.size() <= BuiltinID)
522 BuiltinFunctions.resize(BuiltinID);
523
524 // Already available?
525 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
526 if (FunctionSlot)
527 return FunctionSlot;
528
529 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
530
531 // Get the name, skip over the __builtin_ prefix.
532 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
533
534 // Get the type for the builtin.
535 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
536 const llvm::FunctionType *Ty =
537 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
538
539 // FIXME: This has a serious problem with code like this:
540 // void abs() {}
541 // ... __builtin_abs(x);
542 // The two versions of abs will collide. The fix is for the builtin to win,
543 // and for the existing one to be turned into a constantexpr cast of the
544 // builtin. In the case where the existing one is a static function, it
545 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000546 if (llvm::Function *Existing = getModule().getFunction(Name)) {
547 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
548 return FunctionSlot = Existing;
549 assert(Existing == 0 && "FIXME: Name collision");
550 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000551
552 // FIXME: param attributes for sext/zext etc.
553 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
554 Name, &getModule());
555}
556
557
Chris Lattner4b009652007-07-25 00:24:17 +0000558llvm::Function *CodeGenModule::getMemCpyFn() {
559 if (MemCpyFn) return MemCpyFn;
560 llvm::Intrinsic::ID IID;
561 uint64_t Size; unsigned Align;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000562 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattner4b009652007-07-25 00:24:17 +0000563 switch (Size) {
564 default: assert(0 && "Unknown ptr width");
565 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
566 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
567 }
568 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
569}
Anders Carlsson36a04872007-08-21 00:21:21 +0000570
Chris Lattnerab862cc2007-08-31 04:31:45 +0000571llvm::Constant *CodeGenModule::
572GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000573 llvm::StringMapEntry<llvm::Constant *> &Entry =
574 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
575
576 if (Entry.getValue())
577 return Entry.getValue();
578
579 std::vector<llvm::Constant*> Fields;
580
581 if (!CFConstantStringClassRef) {
582 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
583 Ty = llvm::ArrayType::get(Ty, 0);
584
585 CFConstantStringClassRef =
586 new llvm::GlobalVariable(Ty, false,
587 llvm::GlobalVariable::ExternalLinkage, 0,
588 "__CFConstantStringClassReference",
589 &getModule());
590 }
591
592 // Class pointer.
593 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
594 llvm::Constant *Zeros[] = { Zero, Zero };
595 llvm::Constant *C =
596 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
597 Fields.push_back(C);
598
599 // Flags.
600 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
601 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
602
603 // String pointer.
604 C = llvm::ConstantArray::get(str);
605 C = new llvm::GlobalVariable(C->getType(), true,
606 llvm::GlobalValue::InternalLinkage,
607 C, ".str", &getModule());
608
609 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
610 Fields.push_back(C);
611
612 // String length.
613 Ty = getTypes().ConvertType(getContext().LongTy);
614 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
615
616 // The struct.
617 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
618 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000619 llvm::GlobalVariable *GV =
620 new llvm::GlobalVariable(C->getType(), true,
621 llvm::GlobalVariable::InternalLinkage,
622 C, "", &getModule());
623 GV->setSection("__DATA,__cfstring");
624 Entry.setValue(GV);
625 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000626}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000627
628/// GenerateWritableString -- Creates storage for a string literal
629static llvm::Constant *GenerateStringLiteral(const std::string &str,
630 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000631 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000632 // Create Constant for this string literal
633 llvm::Constant *C=llvm::ConstantArray::get(str);
634
635 // Create a global variable for this string
636 C = new llvm::GlobalVariable(C->getType(), constant,
637 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000638 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000639 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
640 llvm::Constant *Zeros[] = { Zero, Zero };
641 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
642 return C;
643}
644
645/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
646/// element of a character array containing the literal.
647llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
648 // Don't share any string literals if writable-strings is turned on.
649 if (Features.WritableStrings)
650 return GenerateStringLiteral(str, false, *this);
651
652 llvm::StringMapEntry<llvm::Constant *> &Entry =
653 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
654
655 if (Entry.getValue())
656 return Entry.getValue();
657
658 // Create a global variable for this.
659 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
660 Entry.setValue(C);
661 return C;
662}