blob: 3f52175745f25579639d63865ef39a6fed47a5e7 [file] [log] [blame]
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Constant Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Chris Lattnerf6b24ea2008-10-06 05:59:01 +000017#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/StmtVisitor.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Support/Compiler.h"
Eli Friedmana8234002008-05-30 10:24:46 +000024#include "llvm/Target/TargetData.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000025using namespace clang;
26using namespace CodeGen;
27
28namespace {
Anders Carlsson84005b42008-01-26 04:30:23 +000029class VISIBILITY_HIDDEN ConstExprEmitter :
30 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000031 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000032 CodeGenFunction *CGF;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000033public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000034 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
35 : CGM(cgm), CGF(cgf) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000036 }
37
38 //===--------------------------------------------------------------------===//
39 // Visitor Methods
40 //===--------------------------------------------------------------------===//
41
42 llvm::Constant *VisitStmt(Stmt *S) {
Anders Carlsson069880e2009-03-03 16:43:34 +000043 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000044 }
45
46 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
47 return Visit(PE->getSubExpr());
48 }
Anders Carlssonbcf62252008-11-22 02:34:39 +000049
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000050 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
51 return Visit(E->getInitializer());
52 }
53
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +000054 llvm::Constant *VisitCastExpr(CastExpr* E) {
Nuno Lopes81e51e22009-01-17 00:48:48 +000055 // GCC cast to union extension
56 if (E->getType()->isUnionType()) {
57 const llvm::Type *Ty = ConvertType(E->getType());
58 return EmitUnion(CGM.EmitConstantExpr(E->getSubExpr(), CGF), Ty);
59 }
Eli Friedmanddd2b6e2009-02-22 07:29:04 +000060 if (CGM.getContext().getCanonicalType(E->getSubExpr()->getType()) ==
61 CGM.getContext().getCanonicalType(E->getType())) {
62 return Visit(E->getSubExpr());
63 }
64 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000065 }
Devang Pateleae15602008-02-05 02:39:50 +000066
Chris Lattner04421082008-04-08 04:40:51 +000067 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
68 return Visit(DAE->getExpr());
69 }
70
Eli Friedmana8234002008-05-30 10:24:46 +000071 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Eli Friedman4d1c0182008-02-21 17:45:41 +000072 std::vector<llvm::Constant*> Elts;
Eli Friedmana8234002008-05-30 10:24:46 +000073 const llvm::ArrayType *AType =
74 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Eli Friedman4d1c0182008-02-21 17:45:41 +000075 unsigned NumInitElements = ILE->getNumInits();
76 // FIXME: Check for wide strings
Chris Lattnereaf2bb82009-02-24 22:18:39 +000077 // FIXME: Check for NumInitElements exactly equal to 1??
78 if (NumInitElements > 0 &&
79 (isa<StringLiteral>(ILE->getInit(0)) ||
80 isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
Chris Lattnerc63a1f22008-08-04 07:31:14 +000081 ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
Eli Friedman4d1c0182008-02-21 17:45:41 +000082 return Visit(ILE->getInit(0));
Devang Pateleae15602008-02-05 02:39:50 +000083 const llvm::Type *ElemTy = AType->getElementType();
84 unsigned NumElements = AType->getNumElements();
85
86 // Initialising an array requires us to automatically
87 // initialise any elements that have not been initialised explicitly
88 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
89
90 // Copy initializer elements.
91 unsigned i = 0;
Eli Friedmana04a1532008-05-30 19:58:50 +000092 bool RewriteType = false;
Devang Pateleae15602008-02-05 02:39:50 +000093 for (; i < NumInitableElts; ++i) {
Anders Carlssonaa432562008-11-17 01:58:55 +000094 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(i), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +000095 if (!C)
96 return 0;
Eli Friedmana04a1532008-05-30 19:58:50 +000097 RewriteType |= (C->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +000098 Elts.push_back(C);
99 }
Eli Friedmana04a1532008-05-30 19:58:50 +0000100
Devang Pateleae15602008-02-05 02:39:50 +0000101 // Initialize remaining array elements.
102 for (; i < NumElements; ++i)
103 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
104
Eli Friedmana04a1532008-05-30 19:58:50 +0000105 if (RewriteType) {
106 // FIXME: Try to avoid packing the array
107 std::vector<const llvm::Type*> Types;
108 for (unsigned i = 0; i < Elts.size(); ++i)
109 Types.push_back(Elts[i]->getType());
110 const llvm::StructType *SType = llvm::StructType::get(Types, true);
111 return llvm::ConstantStruct::get(SType, Elts);
112 }
113
Devang Pateleae15602008-02-05 02:39:50 +0000114 return llvm::ConstantArray::get(AType, Elts);
115 }
116
Eli Friedmana8234002008-05-30 10:24:46 +0000117 void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
118 FieldDecl* Field, Expr* E) {
119 // Calculate the value to insert
Anders Carlssonaa432562008-11-17 01:58:55 +0000120 llvm::Constant *C = CGM.EmitConstantExpr(E, CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000121 if (!C)
122 return;
123
Eli Friedmana8234002008-05-30 10:24:46 +0000124 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
125 if (!CI) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000126 CGM.ErrorUnsupported(E, "bitfield initialization");
Eli Friedmana8234002008-05-30 10:24:46 +0000127 return;
128 }
129 llvm::APInt V = CI->getValue();
Devang Pateleae15602008-02-05 02:39:50 +0000130
Eli Friedmana8234002008-05-30 10:24:46 +0000131 // Calculate information about the relevant field
132 const llvm::Type* Ty = CI->getType();
Daniel Dunbar9ca8bb02008-08-10 07:00:24 +0000133 const llvm::TargetData &TD = CGM.getTypes().getTargetData();
Eli Friedman7f5221b2009-02-01 08:12:19 +0000134 unsigned size = TD.getTypePaddedSizeInBits(Ty);
Eli Friedmana8234002008-05-30 10:24:46 +0000135 unsigned fieldOffset = CGM.getTypes().getLLVMFieldNo(Field) * size;
136 CodeGenTypes::BitFieldInfo bitFieldInfo =
137 CGM.getTypes().getBitFieldInfo(Field);
138 fieldOffset += bitFieldInfo.Begin;
139
140 // Find where to start the insertion
141 // FIXME: This is O(n^2) in the number of bit-fields!
142 // FIXME: This won't work if the struct isn't completely packed!
143 unsigned offset = 0, i = 0;
144 while (offset < (fieldOffset & -8))
Eli Friedman7f5221b2009-02-01 08:12:19 +0000145 offset += TD.getTypePaddedSizeInBits(Elts[i++]->getType());
Daniel Dunbar9ca8bb02008-08-10 07:00:24 +0000146
147 // Advance over 0 sized elements (must terminate in bounds since
148 // the bitfield must have a size).
Eli Friedman7f5221b2009-02-01 08:12:19 +0000149 while (TD.getTypePaddedSizeInBits(Elts[i]->getType()) == 0)
Daniel Dunbar9ca8bb02008-08-10 07:00:24 +0000150 ++i;
Eli Friedmana8234002008-05-30 10:24:46 +0000151
Daniel Dunbar1f3846e2008-07-17 21:07:48 +0000152 // Promote the size of V if necessary
153 // FIXME: This should never occur, but currently it can because
154 // initializer constants are cast to bool, and because clang is
155 // not enforcing bitfield width limits.
156 if (bitFieldInfo.Size > V.getBitWidth())
157 V.zext(bitFieldInfo.Size);
158
Eli Friedmana8234002008-05-30 10:24:46 +0000159 // Insert the bits into the struct
160 // FIXME: This algorthm is only correct on X86!
161 // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
162 unsigned bitsToInsert = bitFieldInfo.Size;
163 unsigned curBits = std::min(8 - (fieldOffset & 7), bitsToInsert);
164 unsigned byte = V.getLoBits(curBits).getZExtValue() << (fieldOffset & 7);
165 do {
166 llvm::Constant* byteC = llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
167 Elts[i] = llvm::ConstantExpr::getOr(Elts[i], byteC);
168 ++i;
169 V = V.lshr(curBits);
170 bitsToInsert -= curBits;
171
172 if (!bitsToInsert)
173 break;
174
175 curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
176 byte = V.getLoBits(curBits).getZExtValue();
177 } while (true);
178 }
179
180 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
181 const llvm::StructType *SType =
182 cast<llvm::StructType>(ConvertType(ILE->getType()));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000183 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
Devang Pateleae15602008-02-05 02:39:50 +0000184 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000185
Eli Friedman017cbdf2008-05-20 00:11:07 +0000186 // Initialize the whole structure to zero.
187 for (unsigned i = 0; i < SType->getNumElements(); ++i) {
Devang Pateleae15602008-02-05 02:39:50 +0000188 const llvm::Type *FieldTy = SType->getElementType(i);
189 Elts.push_back(llvm::Constant::getNullValue(FieldTy));
190 }
Eli Friedman017cbdf2008-05-20 00:11:07 +0000191
192 // Copy initializer elements. Skip padding fields.
193 unsigned EltNo = 0; // Element no in ILE
194 int FieldNo = 0; // Field no in RecordDecl
Eli Friedmana04a1532008-05-30 19:58:50 +0000195 bool RewriteType = false;
Douglas Gregor44b43212008-12-11 16:49:14 +0000196 for (RecordDecl::field_iterator Field = RD->field_begin(),
197 FieldEnd = RD->field_end();
198 EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) {
Eli Friedman017cbdf2008-05-20 00:11:07 +0000199 FieldNo++;
Douglas Gregor44b43212008-12-11 16:49:14 +0000200 if (!Field->getIdentifier())
Eli Friedman017cbdf2008-05-20 00:11:07 +0000201 continue;
202
Douglas Gregor44b43212008-12-11 16:49:14 +0000203 if (Field->isBitField()) {
204 InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000205 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000206 unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field);
Anders Carlssonaa432562008-11-17 01:58:55 +0000207 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000208 if (!C) return 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000209 RewriteType |= (C->getType() != Elts[FieldNo]->getType());
210 Elts[FieldNo] = C;
Eli Friedman017cbdf2008-05-20 00:11:07 +0000211 }
212 EltNo++;
213 }
214
Eli Friedmana04a1532008-05-30 19:58:50 +0000215 if (RewriteType) {
216 // FIXME: Make this work for non-packed structs
217 assert(SType->isPacked() && "Cannot recreate unpacked structs");
218 std::vector<const llvm::Type*> Types;
219 for (unsigned i = 0; i < Elts.size(); ++i)
220 Types.push_back(Elts[i]->getType());
221 SType = llvm::StructType::get(Types, true);
222 }
223
Devang Pateleae15602008-02-05 02:39:50 +0000224 return llvm::ConstantStruct::get(SType, Elts);
225 }
226
Nuno Lopes81e51e22009-01-17 00:48:48 +0000227 llvm::Constant *EmitUnion(llvm::Constant *C, const llvm::Type *Ty) {
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000228 if (!C)
229 return 0;
230
Nuno Lopes81e51e22009-01-17 00:48:48 +0000231 // Build a struct with the union sub-element as the first member,
232 // and padded to the appropriate size
233 std::vector<llvm::Constant*> Elts;
234 std::vector<const llvm::Type*> Types;
235 Elts.push_back(C);
236 Types.push_back(C->getType());
Eli Friedman7f5221b2009-02-01 08:12:19 +0000237 unsigned CurSize = CGM.getTargetData().getTypePaddedSize(C->getType());
238 unsigned TotalSize = CGM.getTargetData().getTypePaddedSize(Ty);
Nuno Lopes81e51e22009-01-17 00:48:48 +0000239 while (CurSize < TotalSize) {
240 Elts.push_back(llvm::Constant::getNullValue(llvm::Type::Int8Ty));
241 Types.push_back(llvm::Type::Int8Ty);
242 CurSize++;
243 }
244
245 // This always generates a packed struct
246 // FIXME: Try to generate an unpacked struct when we can
247 llvm::StructType* STy = llvm::StructType::get(Types, true);
248 return llvm::ConstantStruct::get(STy, Elts);
249 }
250
Eli Friedmana8234002008-05-30 10:24:46 +0000251 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000252 const llvm::Type *Ty = ConvertType(ILE->getType());
253
Douglas Gregor0bb76892009-01-29 16:53:55 +0000254 // If this is an empty initializer list, we value-initialize the
255 // union.
256 if (ILE->getNumInits() == 0)
257 return llvm::Constant::getNullValue(Ty);
Douglas Gregor34e79462009-01-28 23:36:17 +0000258
Douglas Gregor0bb76892009-01-29 16:53:55 +0000259 FieldDecl* curField = ILE->getInitializedFieldInUnion();
260 if (!curField) {
Douglas Gregor0bb76892009-01-29 16:53:55 +0000261 // There's no field to initialize, so value-initialize the union.
262#ifndef NDEBUG
263 // Make sure that it's really an empty and not a failure of
264 // semantic analysis.
Douglas Gregor71d81742009-02-11 16:17:49 +0000265 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
Douglas Gregor0bb76892009-01-29 16:53:55 +0000266 for (RecordDecl::field_iterator Field = RD->field_begin(),
267 FieldEnd = RD->field_end();
268 Field != FieldEnd; ++Field)
269 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
270#endif
Eli Friedmana8234002008-05-30 10:24:46 +0000271 return llvm::Constant::getNullValue(Ty);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000272 }
Eli Friedmana8234002008-05-30 10:24:46 +0000273
274 if (curField->isBitField()) {
275 // Create a dummy struct for bit-field insertion
Daniel Dunbar491c7b72009-01-12 21:08:18 +0000276 unsigned NumElts = CGM.getTargetData().getTypePaddedSize(Ty) / 8;
Eli Friedmana8234002008-05-30 10:24:46 +0000277 llvm::Constant* NV = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
278 std::vector<llvm::Constant*> Elts(NumElts, NV);
279
280 InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
281 const llvm::ArrayType *RetTy =
282 llvm::ArrayType::get(NV->getType(), NumElts);
283 return llvm::ConstantArray::get(RetTy, Elts);
284 }
285
Nuno Lopes81e51e22009-01-17 00:48:48 +0000286 return EmitUnion(CGM.EmitConstantExpr(ILE->getInit(0), CGF), Ty);
Eli Friedmana8234002008-05-30 10:24:46 +0000287 }
288
289 llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
290 const llvm::VectorType *VType =
291 cast<llvm::VectorType>(ConvertType(ILE->getType()));
Eli Friedmancfb313b2008-05-30 12:02:14 +0000292 const llvm::Type *ElemTy = VType->getElementType();
293 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000294 unsigned NumElements = VType->getNumElements();
Eli Friedmancfb313b2008-05-30 12:02:14 +0000295 unsigned NumInitElements = ILE->getNumInits();
Devang Pateleae15602008-02-05 02:39:50 +0000296
Eli Friedmancfb313b2008-05-30 12:02:14 +0000297 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
298
Devang Pateleae15602008-02-05 02:39:50 +0000299 // Copy initializer elements.
300 unsigned i = 0;
Eli Friedmancfb313b2008-05-30 12:02:14 +0000301 for (; i < NumInitableElts; ++i) {
Anders Carlssonaa432562008-11-17 01:58:55 +0000302 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(i), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000303 if (!C)
304 return 0;
Devang Pateleae15602008-02-05 02:39:50 +0000305 Elts.push_back(C);
306 }
307
Eli Friedmancfb313b2008-05-30 12:02:14 +0000308 for (; i < NumElements; ++i)
309 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
310
Devang Pateleae15602008-02-05 02:39:50 +0000311 return llvm::ConstantVector::get(VType, Elts);
312 }
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000313
314 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
315 const llvm::Type* RetTy = CGM.getTypes().ConvertType(E->getType());
316 return llvm::Constant::getNullValue(RetTy);
317 }
318
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000319 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000320 if (ILE->getType()->isScalarType()) {
321 // We have a scalar in braces. Just use the first element.
322 if (ILE->getNumInits() > 0)
Anders Carlssonaa432562008-11-17 01:58:55 +0000323 return CGM.EmitConstantExpr(ILE->getInit(0), CGF);
Eli Friedmana8234002008-05-30 10:24:46 +0000324
325 const llvm::Type* RetTy = CGM.getTypes().ConvertType(ILE->getType());
326 return llvm::Constant::getNullValue(RetTy);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000327 }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000328
Eli Friedmana8234002008-05-30 10:24:46 +0000329 if (ILE->getType()->isArrayType())
330 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000331
Eli Friedmana8234002008-05-30 10:24:46 +0000332 if (ILE->getType()->isStructureType())
333 return EmitStructInitialization(ILE);
334
335 if (ILE->getType()->isUnionType())
336 return EmitUnionInitialization(ILE);
337
338 if (ILE->getType()->isVectorType())
339 return EmitVectorInitialization(ILE);
340
Devang Pateleae15602008-02-05 02:39:50 +0000341 assert(0 && "Unable to handle InitListExpr");
Chris Lattner2b94fe32008-03-01 08:45:05 +0000342 // Get rid of control reaches end of void function warning.
343 // Not reached.
344 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000345 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000346
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000347 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000348 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000349
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000350 // This must be a string initializing an array in a static initializer.
351 // Don't emit it as the address of the string, emit the string data itself
352 // as an inline array.
Daniel Dunbar61432932008-08-13 23:20:05 +0000353 return llvm::ConstantArray::get(CGM.GetStringForStringLiteral(E), false);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000354 }
355
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000356 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
357 // This must be an @encode initializing an array in a static initializer.
358 // Don't emit it as the address of the string, emit the string data itself
359 // as an inline array.
360 std::string Str;
361 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
362 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
363
364 // Resize the string to the right size, adding zeros at the end, or
365 // truncating as needed.
366 Str.resize(CAT->getSize().getZExtValue(), '\0');
367 return llvm::ConstantArray::get(Str, false);
368 }
369
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000370 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
371 return Visit(E->getSubExpr());
372 }
Mike Stumpb83d2872009-02-19 22:01:56 +0000373
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000374 // Utility methods
375 const llvm::Type *ConvertType(QualType T) {
376 return CGM.getTypes().ConvertType(T);
377 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000378
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000379public:
Anders Carlsson84005b42008-01-26 04:30:23 +0000380 llvm::Constant *EmitLValue(Expr *E) {
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000381 switch (E->getStmtClass()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000382 default: break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000383 case Expr::CompoundLiteralExprClass: {
384 // Note that due to the nature of compound literals, this is guaranteed
385 // to be the only use of the variable, so we just generate it here.
Anders Carlsson84005b42008-01-26 04:30:23 +0000386 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
387 llvm::Constant* C = Visit(CLE->getInitializer());
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000388 // FIXME: "Leaked" on failure.
389 if (C)
390 C = new llvm::GlobalVariable(C->getType(),
391 E->getType().isConstQualified(),
392 llvm::GlobalValue::InternalLinkage,
393 C, ".compoundliteral", &CGM.getModule());
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000394 return C;
Anders Carlsson84005b42008-01-26 04:30:23 +0000395 }
Douglas Gregor1a49af92009-01-06 05:10:23 +0000396 case Expr::DeclRefExprClass:
397 case Expr::QualifiedDeclRefExprClass: {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000398 NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000399 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000400 return CGM.GetAddrOfFunction(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000401 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000402 // We can never refer to a variable with local storage.
403 if (!VD->hasLocalStorage()) {
404 if (VD->isFileVarDecl() || VD->hasExternalStorage())
405 return CGM.GetAddrOfGlobalVar(VD);
406 else if (VD->isBlockVarDecl()) {
407 assert(CGF && "Can't access static local vars without CGF");
408 return CGF->GetAddrOfStaticLocalVar(VD);
409 }
Steve Naroff248a7532008-04-15 22:42:06 +0000410 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000411 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000412 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000413 }
Daniel Dunbar61432932008-08-13 23:20:05 +0000414 case Expr::StringLiteralClass:
415 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000416 case Expr::ObjCEncodeExprClass:
417 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000418 case Expr::ObjCStringLiteralClass: {
419 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
420 std::string S(SL->getString()->getStrData(),
421 SL->getString()->getByteLength());
422 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(S);
423 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
424 }
Chris Lattner35345642008-12-12 05:18:02 +0000425 case Expr::PredefinedExprClass: {
426 // __func__/__FUNCTION__ -> "". __PRETTY_FUNCTION__ -> "top level".
427 std::string Str;
428 if (cast<PredefinedExpr>(E)->getIdentType() ==
429 PredefinedExpr::PrettyFunction)
430 Str = "top level";
431
432 return CGM.GetAddrOfConstantCString(Str, ".tmp");
433 }
Eli Friedmanf0115892009-01-25 01:21:06 +0000434 case Expr::AddrLabelExprClass: {
435 assert(CGF && "Invalid address of label expression outside function.");
436 unsigned id = CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
437 llvm::Constant *C = llvm::ConstantInt::get(llvm::Type::Int32Ty, id);
438 return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType()));
439 }
Eli Friedman3941b182009-01-25 01:54:01 +0000440 case Expr::CallExprClass: {
441 CallExpr* CE = cast<CallExpr>(E);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000442 if (CE->isBuiltinCall(CGM.getContext()) !=
443 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000444 break;
445 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
446 const StringLiteral *Literal = cast<StringLiteral>(Arg);
447 std::string S(Literal->getStrData(), Literal->getByteLength());
448 return CGM.GetAddrOfConstantCFString(S);
449 }
Mike Stumpbd65cac2009-02-19 01:01:04 +0000450 case Expr::BlockExprClass: {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000451 std::string FunctionName;
452 if (CGF)
453 FunctionName = CGF->CurFn->getName();
454 else
455 FunctionName = "global";
456
457 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
Mike Stumpbd65cac2009-02-19 01:01:04 +0000458 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000459 }
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000460
461 return 0;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000462 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000463};
464
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000465} // end anonymous namespace.
466
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000467llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
Chris Lattner96196622008-07-26 22:37:01 +0000468 CodeGenFunction *CGF) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000469 Expr::EvalResult Result;
470
471 if (E->Evaluate(Result, Context)) {
472 assert(!Result.HasSideEffects &&
473 "Constant expr should not have any side effects!");
474 switch (Result.Val.getKind()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +0000475 case APValue::Uninitialized:
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000476 assert(0 && "Constant expressions should be initialized.");
477 return 0;
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000478 case APValue::LValue: {
Daniel Dunbare20de512009-02-19 21:44:24 +0000479 const llvm::Type *DestType = getTypes().ConvertTypeForMem(E->getType());
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000480 llvm::Constant *Offset =
481 llvm::ConstantInt::get(llvm::Type::Int64Ty,
482 Result.Val.getLValueOffset());
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000483
Daniel Dunbare20de512009-02-19 21:44:24 +0000484 llvm::Constant *C;
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000485 if (const Expr *LVBase = Result.Val.getLValueBase()) {
Daniel Dunbare20de512009-02-19 21:44:24 +0000486 C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000487
Daniel Dunbare20de512009-02-19 21:44:24 +0000488 // Apply offset if necessary.
489 if (!Offset->isNullValue()) {
490 const llvm::Type *Type =
491 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
492 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
493 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
494 C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
495 }
496
497 // Convert to the appropriate type; this could be an lvalue for
498 // an integer.
499 if (isa<llvm::PointerType>(DestType))
500 return llvm::ConstantExpr::getBitCast(C, DestType);
501
502 return llvm::ConstantExpr::getPtrToInt(C, DestType);
503 } else {
504 C = Offset;
505
506 // Convert to the appropriate type; this could be an lvalue for
507 // an integer.
508 if (isa<llvm::PointerType>(DestType))
509 return llvm::ConstantExpr::getIntToPtr(C, DestType);
510
511 // If the types don't match this should only be a truncate.
512 if (C->getType() != DestType)
513 return llvm::ConstantExpr::getTrunc(C, DestType);
514
515 return C;
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000516 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000517 }
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000518 case APValue::Int: {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000519 llvm::Constant *C = llvm::ConstantInt::get(Result.Val.getInt());
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000520
521 if (C->getType() == llvm::Type::Int1Ty) {
522 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
523 C = llvm::ConstantExpr::getZExt(C, BoolTy);
524 }
525 return C;
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000526 }
Daniel Dunbara5fd07b2009-01-28 22:24:07 +0000527 case APValue::ComplexInt: {
528 llvm::Constant *Complex[2];
529
530 Complex[0] = llvm::ConstantInt::get(Result.Val.getComplexIntReal());
531 Complex[1] = llvm::ConstantInt::get(Result.Val.getComplexIntImag());
532
533 return llvm::ConstantStruct::get(Complex, 2);
534 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000535 case APValue::Float:
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000536 return llvm::ConstantFP::get(Result.Val.getFloat());
Anders Carlssonaa432562008-11-17 01:58:55 +0000537 case APValue::ComplexFloat: {
538 llvm::Constant *Complex[2];
539
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000540 Complex[0] = llvm::ConstantFP::get(Result.Val.getComplexFloatReal());
541 Complex[1] = llvm::ConstantFP::get(Result.Val.getComplexFloatImag());
Anders Carlssonaa432562008-11-17 01:58:55 +0000542
543 return llvm::ConstantStruct::get(Complex, 2);
544 }
Nate Begeman3d309f92009-01-18 01:01:34 +0000545 case APValue::Vector: {
546 llvm::SmallVector<llvm::Constant *, 4> Inits;
547 unsigned NumElts = Result.Val.getVectorLength();
548
549 for (unsigned i = 0; i != NumElts; ++i) {
550 APValue &Elt = Result.Val.getVectorElt(i);
551 if (Elt.isInt())
552 Inits.push_back(llvm::ConstantInt::get(Elt.getInt()));
553 else
554 Inits.push_back(llvm::ConstantFP::get(Elt.getFloat()));
555 }
556 return llvm::ConstantVector::get(&Inits[0], Inits.size());
557 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000558 }
559 }
Eli Friedman7dfa6392008-06-01 15:31:44 +0000560
561 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000562 if (C && C->getType() == llvm::Type::Int1Ty) {
Eli Friedman7dfa6392008-06-01 15:31:44 +0000563 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
564 C = llvm::ConstantExpr::getZExt(C, BoolTy);
565 }
566 return C;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000567}