blob: 1144cf1c9155e16513901659a1d051b788dd79cd [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"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Support/Compiler.h"
Eli Friedmana8234002008-05-30 10:24:46 +000021#include "llvm/Target/TargetData.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000022using namespace clang;
23using namespace CodeGen;
24
25namespace {
Anders Carlsson84005b42008-01-26 04:30:23 +000026class VISIBILITY_HIDDEN ConstExprEmitter :
27 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000028 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000029 CodeGenFunction *CGF;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000030public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000031 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
32 : CGM(cgm), CGF(cgf) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000033 }
34
35 //===--------------------------------------------------------------------===//
36 // Visitor Methods
37 //===--------------------------------------------------------------------===//
38
39 llvm::Constant *VisitStmt(Stmt *S) {
40 CGM.WarnUnsupported(S, "constant expression");
Chris Lattner98be4942008-03-05 18:54:05 +000041 QualType T = cast<Expr>(S)->getType();
42 return llvm::UndefValue::get(CGM.getTypes().ConvertType(T));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000043 }
44
45 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
46 return Visit(PE->getSubExpr());
47 }
48
49 // Leaves
50 llvm::Constant *VisitIntegerLiteral(const IntegerLiteral *E) {
51 return llvm::ConstantInt::get(E->getValue());
52 }
53 llvm::Constant *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner59138ba2008-04-20 00:45:53 +000054 return llvm::ConstantFP::get(E->getValue());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000055 }
56 llvm::Constant *VisitCharacterLiteral(const CharacterLiteral *E) {
57 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
58 }
59 llvm::Constant *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
60 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
61 }
62
63 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
64 return Visit(E->getInitializer());
65 }
66
67 llvm::Constant *VisitCastExpr(const CastExpr* E) {
68 llvm::Constant *C = Visit(E->getSubExpr());
69
70 return EmitConversion(C, E->getSubExpr()->getType(), E->getType());
71 }
Devang Pateleae15602008-02-05 02:39:50 +000072
Chris Lattner04421082008-04-08 04:40:51 +000073 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
74 return Visit(DAE->getExpr());
75 }
76
Eli Friedmana8234002008-05-30 10:24:46 +000077 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Eli Friedman4d1c0182008-02-21 17:45:41 +000078 std::vector<llvm::Constant*> Elts;
Eli Friedmana8234002008-05-30 10:24:46 +000079 const llvm::ArrayType *AType =
80 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Eli Friedman4d1c0182008-02-21 17:45:41 +000081 unsigned NumInitElements = ILE->getNumInits();
82 // FIXME: Check for wide strings
83 if (NumInitElements > 0 && isa<StringLiteral>(ILE->getInit(0)) &&
84 ILE->getType()->getAsArrayType()->getElementType()->isCharType())
85 return Visit(ILE->getInit(0));
Devang Pateleae15602008-02-05 02:39:50 +000086 const llvm::Type *ElemTy = AType->getElementType();
87 unsigned NumElements = AType->getNumElements();
88
89 // Initialising an array requires us to automatically
90 // initialise any elements that have not been initialised explicitly
91 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
92
93 // Copy initializer elements.
94 unsigned i = 0;
95 for (; i < NumInitableElts; ++i) {
Devang Pateleae15602008-02-05 02:39:50 +000096 llvm::Constant *C = Visit(ILE->getInit(i));
Devang Pateleae15602008-02-05 02:39:50 +000097 Elts.push_back(C);
98 }
99
100 // Initialize remaining array elements.
101 for (; i < NumElements; ++i)
102 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
103
104 return llvm::ConstantArray::get(AType, Elts);
105 }
106
Eli Friedmana8234002008-05-30 10:24:46 +0000107 void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
108 FieldDecl* Field, Expr* E) {
109 // Calculate the value to insert
110 llvm::Constant *C = Visit(E);
111 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
112 if (!CI) {
113 CGM.WarnUnsupported(E, "bitfield initialization");
114 return;
115 }
116 llvm::APInt V = CI->getValue();
Devang Pateleae15602008-02-05 02:39:50 +0000117
Eli Friedmana8234002008-05-30 10:24:46 +0000118 // Calculate information about the relevant field
119 const llvm::Type* Ty = CI->getType();
120 unsigned size = CGM.getTypes().getTargetData().getTypeStoreSizeInBits(Ty);
121 unsigned fieldOffset = CGM.getTypes().getLLVMFieldNo(Field) * size;
122 CodeGenTypes::BitFieldInfo bitFieldInfo =
123 CGM.getTypes().getBitFieldInfo(Field);
124 fieldOffset += bitFieldInfo.Begin;
125
126 // Find where to start the insertion
127 // FIXME: This is O(n^2) in the number of bit-fields!
128 // FIXME: This won't work if the struct isn't completely packed!
129 unsigned offset = 0, i = 0;
130 while (offset < (fieldOffset & -8))
131 offset += CGM.getTypes().getTargetData().getTypeStoreSizeInBits(Elts[i++]->getType());
132
133 // Insert the bits into the struct
134 // FIXME: This algorthm is only correct on X86!
135 // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
136 unsigned bitsToInsert = bitFieldInfo.Size;
137 unsigned curBits = std::min(8 - (fieldOffset & 7), bitsToInsert);
138 unsigned byte = V.getLoBits(curBits).getZExtValue() << (fieldOffset & 7);
139 do {
140 llvm::Constant* byteC = llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
141 Elts[i] = llvm::ConstantExpr::getOr(Elts[i], byteC);
142 ++i;
143 V = V.lshr(curBits);
144 bitsToInsert -= curBits;
145
146 if (!bitsToInsert)
147 break;
148
149 curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
150 byte = V.getLoBits(curBits).getZExtValue();
151 } while (true);
152 }
153
154 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
155 const llvm::StructType *SType =
156 cast<llvm::StructType>(ConvertType(ILE->getType()));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000157 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
Devang Pateleae15602008-02-05 02:39:50 +0000158 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000159
Eli Friedman017cbdf2008-05-20 00:11:07 +0000160 // Initialize the whole structure to zero.
161 for (unsigned i = 0; i < SType->getNumElements(); ++i) {
Devang Pateleae15602008-02-05 02:39:50 +0000162 const llvm::Type *FieldTy = SType->getElementType(i);
163 Elts.push_back(llvm::Constant::getNullValue(FieldTy));
164 }
Eli Friedman017cbdf2008-05-20 00:11:07 +0000165
166 // Copy initializer elements. Skip padding fields.
167 unsigned EltNo = 0; // Element no in ILE
168 int FieldNo = 0; // Field no in RecordDecl
169 while (EltNo < ILE->getNumInits() && FieldNo < RD->getNumMembers()) {
170 FieldDecl* curField = RD->getMember(FieldNo);
171 FieldNo++;
172 if (!curField->getIdentifier())
173 continue;
174
Eli Friedman017cbdf2008-05-20 00:11:07 +0000175 if (curField->isBitField()) {
Eli Friedmana8234002008-05-30 10:24:46 +0000176 InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(EltNo));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000177 } else {
Eli Friedmana8234002008-05-30 10:24:46 +0000178 Elts[CGM.getTypes().getLLVMFieldNo(curField)] =
179 Visit(ILE->getInit(EltNo));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000180 }
181 EltNo++;
182 }
183
Devang Pateleae15602008-02-05 02:39:50 +0000184 return llvm::ConstantStruct::get(SType, Elts);
185 }
186
Eli Friedmana8234002008-05-30 10:24:46 +0000187 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
188 // FIXME: Need to make this work correctly for unions in structs/arrays
189 CGM.WarnUnsupported(ILE, "bitfield initialization");
190 return llvm::UndefValue::get(CGM.getTypes().ConvertType(ILE->getType()));
Devang Pateleae15602008-02-05 02:39:50 +0000191
Eli Friedmana8234002008-05-30 10:24:46 +0000192 // Following is a partial implementation; it doesn't work correctly
193 // because the parent struct/arrays don't adapt their type yet, though
194 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
195 const llvm::Type *Ty = ConvertType(ILE->getType());
196
197 // Find the field decl we're initializing, if any
198 int FieldNo = 0; // Field no in RecordDecl
199 FieldDecl* curField;
200 do {
201 curField = RD->getMember(FieldNo);
202 FieldNo++;
203 } while (!curField->getIdentifier() && FieldNo < RD->getNumMembers());
204
205 if (ILE->getNumInits() == 0 || !curField->getIdentifier())
206 return llvm::Constant::getNullValue(Ty);
207
208 if (curField->isBitField()) {
209 // Create a dummy struct for bit-field insertion
210 unsigned NumElts = CGM.getTargetData().getABITypeSize(Ty) / 8;
211 llvm::Constant* NV = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
212 std::vector<llvm::Constant*> Elts(NumElts, NV);
213
214 InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
215 const llvm::ArrayType *RetTy =
216 llvm::ArrayType::get(NV->getType(), NumElts);
217 return llvm::ConstantArray::get(RetTy, Elts);
218 }
219
220 llvm::Constant *C = Visit(ILE->getInit(0));
221
222 // Build a struct with the union sub-element as the first member,
223 // and padded to the appropriate size
224 std::vector<llvm::Constant*> Elts;
225 std::vector<const llvm::Type*> Types;
226 Elts.push_back(C);
227 Types.push_back(C->getType());
228 unsigned CurSize = CGM.getTargetData().getTypeStoreSize(C->getType());
229 unsigned TotalSize = CGM.getTargetData().getTypeStoreSize(Ty);
230 while (CurSize < TotalSize) {
231 Elts.push_back(llvm::Constant::getNullValue(llvm::Type::Int8Ty));
232 Types.push_back(llvm::Type::Int8Ty);
233 CurSize++;
234 }
235
236 // This always generates a packed struct
237 // FIXME: Try to generate an unpacked struct when we can
238 llvm::StructType* STy = llvm::StructType::get(Types, true);
239 return llvm::ConstantStruct::get(STy, Elts);
240 }
241
242 llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
243 const llvm::VectorType *VType =
244 cast<llvm::VectorType>(ConvertType(ILE->getType()));
Eli Friedmancfb313b2008-05-30 12:02:14 +0000245 const llvm::Type *ElemTy = VType->getElementType();
246 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000247 unsigned NumElements = VType->getNumElements();
Eli Friedmancfb313b2008-05-30 12:02:14 +0000248 unsigned NumInitElements = ILE->getNumInits();
Devang Pateleae15602008-02-05 02:39:50 +0000249
Eli Friedmancfb313b2008-05-30 12:02:14 +0000250 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
251
Devang Pateleae15602008-02-05 02:39:50 +0000252 // Copy initializer elements.
253 unsigned i = 0;
Eli Friedmancfb313b2008-05-30 12:02:14 +0000254 for (; i < NumInitableElts; ++i) {
Devang Pateleae15602008-02-05 02:39:50 +0000255 llvm::Constant *C = Visit(ILE->getInit(i));
Devang Pateleae15602008-02-05 02:39:50 +0000256 Elts.push_back(C);
257 }
258
Eli Friedmancfb313b2008-05-30 12:02:14 +0000259 for (; i < NumElements; ++i)
260 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
261
Devang Pateleae15602008-02-05 02:39:50 +0000262 return llvm::ConstantVector::get(VType, Elts);
263 }
264
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000265 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000266 if (ILE->getType()->isScalarType()) {
267 // We have a scalar in braces. Just use the first element.
268 if (ILE->getNumInits() > 0)
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000269 return Visit(ILE->getInit(0));
Eli Friedmana8234002008-05-30 10:24:46 +0000270
271 const llvm::Type* RetTy = CGM.getTypes().ConvertType(ILE->getType());
272 return llvm::Constant::getNullValue(RetTy);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000273 }
Devang Patel47fb6972008-01-29 23:23:18 +0000274
Eli Friedmana8234002008-05-30 10:24:46 +0000275 if (ILE->getType()->isArrayType())
276 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000277
Eli Friedmana8234002008-05-30 10:24:46 +0000278 if (ILE->getType()->isStructureType())
279 return EmitStructInitialization(ILE);
280
281 if (ILE->getType()->isUnionType())
282 return EmitUnionInitialization(ILE);
283
284 if (ILE->getType()->isVectorType())
285 return EmitVectorInitialization(ILE);
286
Devang Pateleae15602008-02-05 02:39:50 +0000287 assert(0 && "Unable to handle InitListExpr");
Chris Lattner2b94fe32008-03-01 08:45:05 +0000288 // Get rid of control reaches end of void function warning.
289 // Not reached.
290 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000291 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000292
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000293 llvm::Constant *VisitImplicitCastExpr(ImplicitCastExpr *ICExpr) {
Eli Friedman3b707e72008-02-21 17:57:49 +0000294 Expr* SExpr = ICExpr->getSubExpr();
295 QualType SType = SExpr->getType();
296 llvm::Constant *C; // the intermediate expression
297 QualType T; // the type of the intermediate expression
298 if (SType->isArrayType()) {
299 // Arrays decay to a pointer to the first element
300 // VLAs would require special handling, but they can't occur here
301 C = EmitLValue(SExpr);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000302 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000303 llvm::Constant *Ops[] = {Idx0, Idx0};
304 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
Eli Friedman3b707e72008-02-21 17:57:49 +0000305
306 QualType ElemType = SType->getAsArrayType()->getElementType();
307 T = CGM.getContext().getPointerType(ElemType);
308 } else if (SType->isFunctionType()) {
309 // Function types decay to a pointer to the function
310 C = EmitLValue(SExpr);
311 T = CGM.getContext().getPointerType(SType);
312 } else {
313 C = Visit(SExpr);
314 T = SType;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000315 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000316
317 // Perform the conversion; note that an implicit cast can both promote
318 // and convert an array/function
319 return EmitConversion(C, T, ICExpr->getType());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000320 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000321
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000322 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
323 const char *StrData = E->getStrData();
324 unsigned Len = E->getByteLength();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000325 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000326
327 // Otherwise this must be a string initializing an array in a static
328 // initializer. Don't emit it as the address of the string, emit the string
329 // data itself as an inline array.
330 const ConstantArrayType *CAT = E->getType()->getAsConstantArrayType();
331 assert(CAT && "String isn't pointer or array!");
332
333 std::string Str(StrData, StrData + Len);
334 // Null terminate the string before potentially truncating it.
335 // FIXME: What about wchar_t strings?
336 Str.push_back(0);
337
338 uint64_t RealLen = CAT->getSize().getZExtValue();
339 // String or grow the initializer to the required size.
340 if (RealLen != Str.size())
341 Str.resize(RealLen);
342
343 return llvm::ConstantArray::get(Str, false);
344 }
345
346 llvm::Constant *VisitDeclRefExpr(DeclRefExpr *E) {
347 const ValueDecl *Decl = E->getDecl();
Anders Carlssona3881fc2008-01-29 01:28:48 +0000348 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(Decl))
349 return llvm::ConstantInt::get(EC->getInitVal());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000350 assert(0 && "Unsupported decl ref type!");
351 return 0;
352 }
353
354 llvm::Constant *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
355 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
356 }
357
358 // Unary operators
359 llvm::Constant *VisitUnaryPlus(const UnaryOperator *E) {
360 return Visit(E->getSubExpr());
361 }
362 llvm::Constant *VisitUnaryMinus(const UnaryOperator *E) {
363 return llvm::ConstantExpr::getNeg(Visit(E->getSubExpr()));
364 }
365 llvm::Constant *VisitUnaryNot(const UnaryOperator *E) {
366 return llvm::ConstantExpr::getNot(Visit(E->getSubExpr()));
367 }
368 llvm::Constant *VisitUnaryLNot(const UnaryOperator *E) {
369 llvm::Constant *SubExpr = Visit(E->getSubExpr());
370
371 if (E->getSubExpr()->getType()->isRealFloatingType()) {
372 // Compare against 0.0 for fp scalars.
373 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
374 SubExpr = llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UEQ, SubExpr,
375 Zero);
376 } else {
377 assert((E->getSubExpr()->getType()->isIntegerType() ||
378 E->getSubExpr()->getType()->isPointerType()) &&
379 "Unknown scalar type to convert");
380 // Compare against an integer or pointer null.
381 llvm::Constant *Zero = llvm::Constant::getNullValue(SubExpr->getType());
382 SubExpr = llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, SubExpr,
383 Zero);
384 }
385
386 return llvm::ConstantExpr::getZExt(SubExpr, ConvertType(E->getType()));
387 }
388 llvm::Constant *VisitUnarySizeOf(const UnaryOperator *E) {
389 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
390 }
391 llvm::Constant *VisitUnaryAlignOf(const UnaryOperator *E) {
392 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
393 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000394 llvm::Constant *VisitUnaryAddrOf(const UnaryOperator *E) {
395 return EmitLValue(E->getSubExpr());
396 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000397 llvm::Constant *VisitUnaryOffsetOf(const UnaryOperator *E) {
398 int64_t Val = E->evaluateOffsetOf(CGM.getContext());
399
400 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
401
Chris Lattner98be4942008-03-05 18:54:05 +0000402 uint32_t ResultWidth =
403 static_cast<uint32_t>(CGM.getContext().getTypeSize(E->getType()));
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000404 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
405 }
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000406
407 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
408 return Visit(E->getSubExpr());
409 }
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000410
Anders Carlssonce6237e2008-01-29 01:33:32 +0000411 // Binary operators
412 llvm::Constant *VisitBinOr(const BinaryOperator *E) {
413 llvm::Constant *LHS = Visit(E->getLHS());
414 llvm::Constant *RHS = Visit(E->getRHS());
415
416 return llvm::ConstantExpr::getOr(LHS, RHS);
417 }
Anders Carlsson7be3d012008-02-05 20:54:21 +0000418 llvm::Constant *VisitBinSub(const BinaryOperator *E) {
419 llvm::Constant *LHS = Visit(E->getLHS());
420 llvm::Constant *RHS = Visit(E->getRHS());
421
422 if (!isa<llvm::PointerType>(RHS->getType())) {
423 // pointer - int
424 if (isa<llvm::PointerType>(LHS->getType())) {
425 llvm::Constant *Idx = llvm::ConstantExpr::getNeg(RHS);
426
427 return llvm::ConstantExpr::getGetElementPtr(LHS, &Idx, 1);
428 }
429
430 // int - int
431 return llvm::ConstantExpr::getSub(LHS, RHS);
432 }
433
434 assert(0 && "Unhandled bin sub case!");
435 return 0;
436 }
437
438 llvm::Constant *VisitBinShl(const BinaryOperator *E) {
439 llvm::Constant *LHS = Visit(E->getLHS());
440 llvm::Constant *RHS = Visit(E->getRHS());
Anders Carlssonce6237e2008-01-29 01:33:32 +0000441
Anders Carlsson7be3d012008-02-05 20:54:21 +0000442 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
443 // RHS to the same size as the LHS.
444 if (LHS->getType() != RHS->getType())
445 RHS = llvm::ConstantExpr::getIntegerCast(RHS, LHS->getType(), false);
446
447 return llvm::ConstantExpr::getShl(LHS, RHS);
448 }
449
450 llvm::Constant *VisitBinMul(const BinaryOperator *E) {
451 llvm::Constant *LHS = Visit(E->getLHS());
452 llvm::Constant *RHS = Visit(E->getRHS());
453
454 return llvm::ConstantExpr::getMul(LHS, RHS);
455 }
456
457 llvm::Constant *VisitBinDiv(const BinaryOperator *E) {
458 llvm::Constant *LHS = Visit(E->getLHS());
459 llvm::Constant *RHS = Visit(E->getRHS());
460
461 if (LHS->getType()->isFPOrFPVector())
462 return llvm::ConstantExpr::getFDiv(LHS, RHS);
463 else if (E->getType()->isUnsignedIntegerType())
464 return llvm::ConstantExpr::getUDiv(LHS, RHS);
465 else
466 return llvm::ConstantExpr::getSDiv(LHS, RHS);
467 }
468
469 llvm::Constant *VisitBinAdd(const BinaryOperator *E) {
470 llvm::Constant *LHS = Visit(E->getLHS());
471 llvm::Constant *RHS = Visit(E->getRHS());
472
473 if (!E->getType()->isPointerType())
474 return llvm::ConstantExpr::getAdd(LHS, RHS);
475
Anders Carlsson87a98752008-02-06 07:23:14 +0000476 llvm::Constant *Ptr, *Idx;
477 if (isa<llvm::PointerType>(LHS->getType())) { // pointer + int
478 Ptr = LHS;
479 Idx = RHS;
480 } else { // int + pointer
481 Ptr = RHS;
482 Idx = LHS;
483 }
484
485 return llvm::ConstantExpr::getGetElementPtr(Ptr, &Idx, 1);
Anders Carlsson7be3d012008-02-05 20:54:21 +0000486 }
487
488 llvm::Constant *VisitBinAnd(const BinaryOperator *E) {
489 llvm::Constant *LHS = Visit(E->getLHS());
490 llvm::Constant *RHS = Visit(E->getRHS());
491
492 return llvm::ConstantExpr::getAnd(LHS, RHS);
493 }
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000494
Eli Friedmanb8965962008-05-29 15:17:49 +0000495 llvm::Constant *EmitCmp(const BinaryOperator *E,
496 llvm::CmpInst::Predicate SignedPred,
497 llvm::CmpInst::Predicate UnsignedPred,
498 llvm::CmpInst::Predicate FloatPred) {
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000499 llvm::Constant *LHS = Visit(E->getLHS());
500 llvm::Constant *RHS = Visit(E->getRHS());
Eli Friedmanb8965962008-05-29 15:17:49 +0000501 llvm::Constant *Result;
502 if (LHS->getType()->isInteger() ||
503 isa<llvm::PointerType>(LHS->getType())) {
504 if (E->getLHS()->getType()->isSignedIntegerType())
505 Result = llvm::ConstantExpr::getICmp(SignedPred, LHS, RHS);
506 else
507 Result = llvm::ConstantExpr::getICmp(UnsignedPred, LHS, RHS);
508 } else if (LHS->getType()->isFloatingPoint()) {
509 Result = llvm::ConstantExpr::getFCmp(FloatPred, LHS, RHS);
510 } else {
511 CGM.WarnUnsupported(E, "constant expression");
512 Result = llvm::ConstantInt::getFalse();
513 }
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000514
515 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000516 return llvm::ConstantExpr::getZExtOrBitCast(Result, ResultType);
517 }
518
Eli Friedmanb8965962008-05-29 15:17:49 +0000519 llvm::Constant *VisitBinNE(const BinaryOperator *E) {
520 return EmitCmp(E, llvm::CmpInst::ICMP_NE, llvm::CmpInst::ICMP_NE,
521 llvm::CmpInst::FCMP_ONE);
522 }
523
524 llvm::Constant *VisitBinEQ(const BinaryOperator *E) {
525 return EmitCmp(E, llvm::CmpInst::ICMP_EQ, llvm::CmpInst::ICMP_EQ,
526 llvm::CmpInst::FCMP_OEQ);
527 }
528
529 llvm::Constant *VisitBinLT(const BinaryOperator *E) {
530 return EmitCmp(E, llvm::CmpInst::ICMP_SLT, llvm::CmpInst::ICMP_ULT,
531 llvm::CmpInst::FCMP_OLT);
532 }
533
534 llvm::Constant *VisitBinLE(const BinaryOperator *E) {
535 return EmitCmp(E, llvm::CmpInst::ICMP_SLE, llvm::CmpInst::ICMP_ULE,
536 llvm::CmpInst::FCMP_OLE);
537 }
538
539 llvm::Constant *VisitBinGT(const BinaryOperator *E) {
540 return EmitCmp(E, llvm::CmpInst::ICMP_SGT, llvm::CmpInst::ICMP_UGT,
541 llvm::CmpInst::FCMP_OGT);
542 }
543
544 llvm::Constant *VisitBinGE(const BinaryOperator *E) {
545 return EmitCmp(E, llvm::CmpInst::ICMP_SGE, llvm::CmpInst::ICMP_SGE,
546 llvm::CmpInst::FCMP_OGE);
547 }
548
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000549 llvm::Constant *VisitConditionalOperator(const ConditionalOperator *E) {
550 llvm::Constant *Cond = Visit(E->getCond());
551 llvm::Constant *CondVal = EmitConversionToBool(Cond, E->getType());
552 llvm::ConstantInt *CondValInt = dyn_cast<llvm::ConstantInt>(CondVal);
553 if (!CondValInt) {
554 CGM.WarnUnsupported(E, "constant expression");
555 return llvm::Constant::getNullValue(ConvertType(E->getType()));
556 }
557 if (CondValInt->isOne()) {
558 if (E->getLHS())
559 return Visit(E->getLHS());
560 return Cond;
561 }
562
563 return Visit(E->getRHS());
564 }
Anders Carlsson7be3d012008-02-05 20:54:21 +0000565
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000566 // Utility methods
567 const llvm::Type *ConvertType(QualType T) {
568 return CGM.getTypes().ConvertType(T);
569 }
570
571 llvm::Constant *EmitConversionToBool(llvm::Constant *Src, QualType SrcType) {
572 assert(SrcType->isCanonical() && "EmitConversion strips typedefs");
573
574 if (SrcType->isRealFloatingType()) {
575 // Compare against 0.0 for fp scalars.
576 llvm::Constant *Zero = llvm::Constant::getNullValue(Src->getType());
577 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Src, Zero);
578 }
579
580 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
581 "Unknown scalar type to convert");
582
583 // Compare against an integer or pointer null.
584 llvm::Constant *Zero = llvm::Constant::getNullValue(Src->getType());
585 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Src, Zero);
586 }
587
588 llvm::Constant *EmitConversion(llvm::Constant *Src, QualType SrcType,
589 QualType DstType) {
590 SrcType = SrcType.getCanonicalType();
591 DstType = DstType.getCanonicalType();
592 if (SrcType == DstType) return Src;
593
594 // Handle conversions to bool first, they are special: comparisons against 0.
595 if (DstType->isBooleanType())
596 return EmitConversionToBool(Src, SrcType);
597
598 const llvm::Type *DstTy = ConvertType(DstType);
599
600 // Ignore conversions like int -> uint.
601 if (Src->getType() == DstTy)
602 return Src;
603
604 // Handle pointer conversions next: pointers can only be converted to/from
605 // other pointers and integers.
606 if (isa<PointerType>(DstType)) {
607 // The source value may be an integer, or a pointer.
608 if (isa<llvm::PointerType>(Src->getType()))
609 return llvm::ConstantExpr::getBitCast(Src, DstTy);
Anders Carlsson84005b42008-01-26 04:30:23 +0000610 assert(SrcType->isIntegerType() &&"Not ptr->ptr or int->ptr conversion?");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000611 return llvm::ConstantExpr::getIntToPtr(Src, DstTy);
612 }
613
614 if (isa<PointerType>(SrcType)) {
615 // Must be an ptr to int cast.
616 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
617 return llvm::ConstantExpr::getPtrToInt(Src, DstTy);
618 }
619
620 // A scalar source can be splatted to a vector of the same element type
621 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
622 const llvm::VectorType *VT = cast<llvm::VectorType>(DstTy);
623 assert((VT->getElementType() == Src->getType()) &&
624 "Vector element type must match scalar type to splat.");
625 unsigned NumElements = DstType->getAsVectorType()->getNumElements();
626 llvm::SmallVector<llvm::Constant*, 16> Elements;
627 for (unsigned i = 0; i < NumElements; i++)
628 Elements.push_back(Src);
629
630 return llvm::ConstantVector::get(&Elements[0], NumElements);
631 }
632
633 if (isa<llvm::VectorType>(Src->getType()) ||
634 isa<llvm::VectorType>(DstTy)) {
635 return llvm::ConstantExpr::getBitCast(Src, DstTy);
636 }
637
638 // Finally, we have the arithmetic types: real int/float.
639 if (isa<llvm::IntegerType>(Src->getType())) {
640 bool InputSigned = SrcType->isSignedIntegerType();
641 if (isa<llvm::IntegerType>(DstTy))
642 return llvm::ConstantExpr::getIntegerCast(Src, DstTy, InputSigned);
643 else if (InputSigned)
644 return llvm::ConstantExpr::getSIToFP(Src, DstTy);
645 else
646 return llvm::ConstantExpr::getUIToFP(Src, DstTy);
647 }
648
649 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
650 if (isa<llvm::IntegerType>(DstTy)) {
651 if (DstType->isSignedIntegerType())
652 return llvm::ConstantExpr::getFPToSI(Src, DstTy);
653 else
654 return llvm::ConstantExpr::getFPToUI(Src, DstTy);
655 }
656
657 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
658 if (DstTy->getTypeID() < Src->getType()->getTypeID())
659 return llvm::ConstantExpr::getFPTrunc(Src, DstTy);
660 else
661 return llvm::ConstantExpr::getFPExtend(Src, DstTy);
662 }
663
664 llvm::Constant *EmitSizeAlignOf(QualType TypeToSize,
665 QualType RetType, bool isSizeOf) {
666 std::pair<uint64_t, unsigned> Info =
Chris Lattner98be4942008-03-05 18:54:05 +0000667 CGM.getContext().getTypeInfo(TypeToSize);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000668
669 uint64_t Val = isSizeOf ? Info.first : Info.second;
670 Val /= 8; // Return size in bytes, not bits.
671
672 assert(RetType->isIntegerType() && "Result type must be an integer!");
673
Chris Lattner98be4942008-03-05 18:54:05 +0000674 uint32_t ResultWidth =
675 static_cast<uint32_t>(CGM.getContext().getTypeSize(RetType));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000676 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
677 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000678
679 llvm::Constant *EmitLValue(Expr *E) {
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000680 switch (E->getStmtClass()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000681 default: break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000682 case Expr::ParenExprClass:
683 // Elide parenthesis
684 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
685 case Expr::CompoundLiteralExprClass: {
686 // Note that due to the nature of compound literals, this is guaranteed
687 // to be the only use of the variable, so we just generate it here.
Anders Carlsson84005b42008-01-26 04:30:23 +0000688 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
689 llvm::Constant* C = Visit(CLE->getInitializer());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000690 C = new llvm::GlobalVariable(C->getType(),E->getType().isConstQualified(),
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000691 llvm::GlobalValue::InternalLinkage,
692 C, ".compoundliteral", &CGM.getModule());
693 return C;
Anders Carlsson84005b42008-01-26 04:30:23 +0000694 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000695 case Expr::DeclRefExprClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000696 ValueDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000697 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
698 return CGM.GetAddrOfFunctionDecl(FD, false);
Steve Naroff248a7532008-04-15 22:42:06 +0000699 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
700 if (VD->isFileVarDecl())
701 return CGM.GetAddrOfGlobalVar(VD, false);
702 else if (VD->isBlockVarDecl()) {
703 assert(CGF && "Can't access static local vars without CGF");
704 return CGF->GetAddrOfStaticLocalVar(VD);
705 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000706 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000707 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000708 }
709 case Expr::MemberExprClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000710 MemberExpr* ME = cast<MemberExpr>(E);
Anders Carlsson84005b42008-01-26 04:30:23 +0000711 llvm::Constant *Base;
712 if (ME->isArrow())
713 Base = Visit(ME->getBase());
714 else
715 Base = EmitLValue(ME->getBase());
Lauro Ramos Venancio5bfe18c2008-01-30 21:23:20 +0000716
717 unsigned FieldNumber = CGM.getTypes().getLLVMFieldNo(ME->getMemberDecl());
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000718 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
719 llvm::Constant *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty,
720 FieldNumber);
721 llvm::Value *Ops[] = {Zero, Idx};
722 return llvm::ConstantExpr::getGetElementPtr(Base, Ops, 2);
723 }
724 case Expr::ArraySubscriptExprClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000725 ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(E);
726 llvm::Constant *Base = Visit(ASExpr->getBase());
727 llvm::Constant *Index = Visit(ASExpr->getIdx());
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000728 assert(!ASExpr->getBase()->getType()->isVectorType() &&
729 "Taking the address of a vector component is illegal!");
730 return llvm::ConstantExpr::getGetElementPtr(Base, &Index, 1);
731 }
732 case Expr::StringLiteralClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000733 StringLiteral *String = cast<StringLiteral>(E);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000734 assert(!String->isWide() && "Cannot codegen wide strings yet");
Anders Carlsson84005b42008-01-26 04:30:23 +0000735 const char *StrData = String->getStrData();
736 unsigned Len = String->getByteLength();
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000737
Anders Carlsson84005b42008-01-26 04:30:23 +0000738 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
739 }
740 case Expr::UnaryOperatorClass: {
741 UnaryOperator *Exp = cast<UnaryOperator>(E);
742 switch (Exp->getOpcode()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000743 default: break;
744 case UnaryOperator::Extension:
Anders Carlsson84005b42008-01-26 04:30:23 +0000745 // Extension is just a wrapper for expressions
746 return EmitLValue(Exp->getSubExpr());
747 case UnaryOperator::Real:
748 case UnaryOperator::Imag: {
749 // The address of __real or __imag is just a GEP off the address
750 // of the internal expression
751 llvm::Constant* C = EmitLValue(Exp->getSubExpr());
752 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
753 llvm::Constant *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty,
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000754 Exp->getOpcode() == UnaryOperator::Imag);
Anders Carlsson84005b42008-01-26 04:30:23 +0000755 llvm::Value *Ops[] = {Zero, Idx};
756 return llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
757 }
758 case UnaryOperator::Deref:
759 // The address of a deref is just the value of the expression
760 return Visit(Exp->getSubExpr());
761 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000762 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000763 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000764 }
765 CGM.WarnUnsupported(E, "constant l-value expression");
766 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
767 return llvm::UndefValue::get(Ty);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000768 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000769
770};
771
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000772} // end anonymous namespace.
773
774
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000775llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
776 CodeGenFunction *CGF)
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000777{
778 QualType type = E->getType().getCanonicalType();
779
780 if (type->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +0000781 llvm::APSInt Value(static_cast<uint32_t>(Context.getTypeSize(type)));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000782 if (E->isIntegerConstantExpr(Value, Context)) {
783 return llvm::ConstantInt::get(Value);
784 }
785 }
786
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000787 return ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000788}