blob: 382bfe59b5b71a1d01406c4f2c8e543f47c29daa [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
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 file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CharUnits.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/ASTDiagnostic.h"
20#include "clang/Basic/Builtins.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/ADT/SmallString.h"
23#include <cstring>
24
25using namespace clang;
26using llvm::APSInt;
27using llvm::APFloat;
28
29/// EvalInfo - This is a private struct used by the evaluator to capture
30/// information about a subexpression as it is folded. It retains information
31/// about the AST context, but also maintains information about the folded
32/// expression.
33///
34/// If an expression could be evaluated, it is still possible it is not a C
35/// "integer constant expression" or constant expression. If not, this struct
36/// captures information about how and why not.
37///
38/// One bit of information passed *into* the request for constant folding
39/// indicates whether the subexpression is "evaluated" or not according to C
40/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
41/// evaluate the expression regardless of what the RHS is, but C only allows
42/// certain things in certain situations.
43struct EvalInfo {
44 ASTContext &Ctx;
45
46 /// EvalResult - Contains information about the evaluation.
47 Expr::EvalResult &EvalResult;
48
49 /// AnyLValue - Stack based LValue results are not discarded.
50 bool AnyLValue;
51
52 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
53 bool anylvalue = false)
54 : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
55};
56
57
58static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
59static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
60static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
61static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
62 EvalInfo &Info);
63static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
64static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
65
66//===----------------------------------------------------------------------===//
67// Misc utilities
68//===----------------------------------------------------------------------===//
69
70static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
71 // FIXME: Is this accurate for all kinds of bases? If not, what would
72 // the check look like?
73 Result = Value.getLValueBase() || !Value.getLValueOffset().isZero();
74 return true;
75}
76
77static bool HandleConversionToBool(const Expr* E, bool& Result,
78 EvalInfo &Info) {
79 if (E->getType()->isIntegralType()) {
80 APSInt IntResult;
81 if (!EvaluateInteger(E, IntResult, Info))
82 return false;
83 Result = IntResult != 0;
84 return true;
85 } else if (E->getType()->isRealFloatingType()) {
86 APFloat FloatResult(0.0);
87 if (!EvaluateFloat(E, FloatResult, Info))
88 return false;
89 Result = !FloatResult.isZero();
90 return true;
91 } else if (E->getType()->hasPointerRepresentation()) {
92 APValue PointerResult;
93 if (!EvaluatePointer(E, PointerResult, Info))
94 return false;
95 return EvalPointerValueAsBool(PointerResult, Result);
96 } else if (E->getType()->isAnyComplexType()) {
97 APValue ComplexResult;
98 if (!EvaluateComplex(E, ComplexResult, Info))
99 return false;
100 if (ComplexResult.isComplexFloat()) {
101 Result = !ComplexResult.getComplexFloatReal().isZero() ||
102 !ComplexResult.getComplexFloatImag().isZero();
103 } else {
104 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
105 ComplexResult.getComplexIntImag().getBoolValue();
106 }
107 return true;
108 }
109
110 return false;
111}
112
113static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
114 APFloat &Value, ASTContext &Ctx) {
115 unsigned DestWidth = Ctx.getIntWidth(DestType);
116 // Determine whether we are converting to unsigned or signed.
117 bool DestSigned = DestType->isSignedIntegerType();
118
119 // FIXME: Warning for overflow.
120 uint64_t Space[4];
121 bool ignored;
122 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
123 llvm::APFloat::rmTowardZero, &ignored);
124 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
125}
126
127static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
128 APFloat &Value, ASTContext &Ctx) {
129 bool ignored;
130 APFloat Result = Value;
131 Result.convert(Ctx.getFloatTypeSemantics(DestType),
132 APFloat::rmNearestTiesToEven, &ignored);
133 return Result;
134}
135
136static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
137 APSInt &Value, ASTContext &Ctx) {
138 unsigned DestWidth = Ctx.getIntWidth(DestType);
139 APSInt Result = Value;
140 // Figure out if this is a truncate, extend or noop cast.
141 // If the input is signed, do a sign extend, noop, or truncate.
142 Result.extOrTrunc(DestWidth);
143 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
144 return Result;
145}
146
147static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
148 APSInt &Value, ASTContext &Ctx) {
149
150 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
151 Result.convertFromAPInt(Value, Value.isSigned(),
152 APFloat::rmNearestTiesToEven);
153 return Result;
154}
155
156namespace {
157class HasSideEffect
158 : public StmtVisitor<HasSideEffect, bool> {
159 EvalInfo &Info;
160public:
161
162 HasSideEffect(EvalInfo &info) : Info(info) {}
163
164 // Unhandled nodes conservatively default to having side effects.
165 bool VisitStmt(Stmt *S) {
166 return true;
167 }
168
169 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
170 bool VisitDeclRefExpr(DeclRefExpr *E) {
171 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
172 return true;
173 return false;
174 }
175 // We don't want to evaluate BlockExprs multiple times, as they generate
176 // a ton of code.
177 bool VisitBlockExpr(BlockExpr *E) { return true; }
178 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
179 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
180 { return Visit(E->getInitializer()); }
181 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
182 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
183 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
184 bool VisitStringLiteral(StringLiteral *E) { return false; }
185 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
186 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
187 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
188 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
189 bool VisitChooseExpr(ChooseExpr *E)
190 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
191 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
192 bool VisitBinAssign(BinaryOperator *E) { return true; }
193 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
194 bool VisitBinaryOperator(BinaryOperator *E)
195 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
196 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
197 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
198 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
199 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
200 bool VisitUnaryDeref(UnaryOperator *E) {
201 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
202 return true;
203 return Visit(E->getSubExpr());
204 }
205 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
206};
207
208} // end anonymous namespace
209
210//===----------------------------------------------------------------------===//
211// LValue Evaluation
212//===----------------------------------------------------------------------===//
213namespace {
214class LValueExprEvaluator
215 : public StmtVisitor<LValueExprEvaluator, APValue> {
216 EvalInfo &Info;
217public:
218
219 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
220
221 APValue VisitStmt(Stmt *S) {
222 return APValue();
223 }
224
225 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
226 APValue VisitDeclRefExpr(DeclRefExpr *E);
227 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E); }
228 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
229 APValue VisitMemberExpr(MemberExpr *E);
230 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E); }
231 APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E); }
232 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
233 APValue VisitUnaryDeref(UnaryOperator *E);
234 APValue VisitUnaryExtension(const UnaryOperator *E)
235 { return Visit(E->getSubExpr()); }
236 APValue VisitChooseExpr(const ChooseExpr *E)
237 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
238
239 APValue VisitCastExpr(CastExpr *E) {
240 switch (E->getCastKind()) {
241 default:
242 return APValue();
243
244 case CastExpr::CK_NoOp:
245 return Visit(E->getSubExpr());
246 }
247 }
248 // FIXME: Missing: __real__, __imag__
249};
250} // end anonymous namespace
251
252static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
253 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
254 return Result.isLValue();
255}
256
257APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
258 if (isa<FunctionDecl>(E->getDecl())) {
259 return APValue(E);
260 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
261 if (!Info.AnyLValue && !VD->hasGlobalStorage())
262 return APValue();
263 if (!VD->getType()->isReferenceType())
264 return APValue(E);
265 // FIXME: Check whether VD might be overridden!
266 if (const Expr *Init = VD->getAnyInitializer())
267 return Visit(const_cast<Expr *>(Init));
268 }
269
270 return APValue();
271}
272
273APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
274 if (!Info.AnyLValue && !E->isFileScope())
275 return APValue();
276 return APValue(E);
277}
278
279APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
280 APValue result;
281 QualType Ty;
282 if (E->isArrow()) {
283 if (!EvaluatePointer(E->getBase(), result, Info))
284 return APValue();
285 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
286 } else {
287 result = Visit(E->getBase());
288 if (result.isUninit())
289 return APValue();
290 Ty = E->getBase()->getType();
291 }
292
293 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
294 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
295
296 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
297 if (!FD) // FIXME: deal with other kinds of member expressions
298 return APValue();
299
300 if (FD->getType()->isReferenceType())
301 return APValue();
302
303 // FIXME: This is linear time.
304 unsigned i = 0;
305 for (RecordDecl::field_iterator Field = RD->field_begin(),
306 FieldEnd = RD->field_end();
307 Field != FieldEnd; (void)++Field, ++i) {
308 if (*Field == FD)
309 break;
310 }
311
312 result.setLValue(result.getLValueBase(),
313 result.getLValueOffset() +
314 CharUnits::fromQuantity(RL.getFieldOffset(i) / 8));
315
316 return result;
317}
318
319APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
320 APValue Result;
321
322 if (!EvaluatePointer(E->getBase(), Result, Info))
323 return APValue();
324
325 APSInt Index;
326 if (!EvaluateInteger(E->getIdx(), Index, Info))
327 return APValue();
328
329 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
330
331 CharUnits Offset = Index.getSExtValue() * ElementSize;
332 Result.setLValue(Result.getLValueBase(),
333 Result.getLValueOffset() + Offset);
334 return Result;
335}
336
337APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
338 APValue Result;
339 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
340 return APValue();
341 return Result;
342}
343
344//===----------------------------------------------------------------------===//
345// Pointer Evaluation
346//===----------------------------------------------------------------------===//
347
348namespace {
349class PointerExprEvaluator
350 : public StmtVisitor<PointerExprEvaluator, APValue> {
351 EvalInfo &Info;
352public:
353
354 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
355
356 APValue VisitStmt(Stmt *S) {
357 return APValue();
358 }
359
360 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
361
362 APValue VisitBinaryOperator(const BinaryOperator *E);
363 APValue VisitCastExpr(CastExpr* E);
364 APValue VisitUnaryExtension(const UnaryOperator *E)
365 { return Visit(E->getSubExpr()); }
366 APValue VisitUnaryAddrOf(const UnaryOperator *E);
367 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
368 { return APValue(E); }
369 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
370 { return APValue(E); }
371 APValue VisitCallExpr(CallExpr *E);
372 APValue VisitBlockExpr(BlockExpr *E) {
373 if (!E->hasBlockDeclRefExprs())
374 return APValue(E);
375 return APValue();
376 }
377 APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
378 { return APValue((Expr*)0); }
379 APValue VisitConditionalOperator(ConditionalOperator *E);
380 APValue VisitChooseExpr(ChooseExpr *E)
381 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
382 APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
383 { return APValue((Expr*)0); }
384 // FIXME: Missing: @protocol, @selector
385};
386} // end anonymous namespace
387
388static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
389 if (!E->getType()->hasPointerRepresentation())
390 return false;
391 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
392 return Result.isLValue();
393}
394
395APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
396 if (E->getOpcode() != BinaryOperator::Add &&
397 E->getOpcode() != BinaryOperator::Sub)
398 return APValue();
399
400 const Expr *PExp = E->getLHS();
401 const Expr *IExp = E->getRHS();
402 if (IExp->getType()->isPointerType())
403 std::swap(PExp, IExp);
404
405 APValue ResultLValue;
406 if (!EvaluatePointer(PExp, ResultLValue, Info))
407 return APValue();
408
409 llvm::APSInt AdditionalOffset(32);
410 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
411 return APValue();
412
413 QualType PointeeType = PExp->getType()->getAs<PointerType>()->getPointeeType();
414 CharUnits SizeOfPointee;
415
416 // Explicitly handle GNU void* and function pointer arithmetic extensions.
417 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
418 SizeOfPointee = CharUnits::One();
419 else
420 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
421
422 CharUnits Offset = ResultLValue.getLValueOffset();
423
424 if (E->getOpcode() == BinaryOperator::Add)
425 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
426 else
427 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
428
429 return APValue(ResultLValue.getLValueBase(), Offset);
430}
431
432APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
433 APValue result;
434 if (EvaluateLValue(E->getSubExpr(), result, Info))
435 return result;
436 return APValue();
437}
438
439
440APValue PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
441 Expr* SubExpr = E->getSubExpr();
442
443 switch (E->getCastKind()) {
444 default:
445 break;
446
447 case CastExpr::CK_Unknown: {
448 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
449
450 // Check for pointer->pointer cast
451 if (SubExpr->getType()->isPointerType() ||
452 SubExpr->getType()->isObjCObjectPointerType() ||
453 SubExpr->getType()->isNullPtrType() ||
454 SubExpr->getType()->isBlockPointerType())
455 return Visit(SubExpr);
456
457 if (SubExpr->getType()->isIntegralType()) {
458 APValue Result;
459 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
460 break;
461
462 if (Result.isInt()) {
463 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
464 return APValue(0,
465 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
466 }
467
468 // Cast is of an lvalue, no need to change value.
469 return Result;
470 }
471 break;
472 }
473
474 case CastExpr::CK_NoOp:
475 case CastExpr::CK_BitCast:
476 case CastExpr::CK_AnyPointerToObjCPointerCast:
477 case CastExpr::CK_AnyPointerToBlockPointerCast:
478 return Visit(SubExpr);
479
480 case CastExpr::CK_IntegralToPointer: {
481 APValue Result;
482 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
483 break;
484
485 if (Result.isInt()) {
486 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
487 return APValue(0,
488 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
489 }
490
491 // Cast is of an lvalue, no need to change value.
492 return Result;
493 }
494 case CastExpr::CK_ArrayToPointerDecay:
495 case CastExpr::CK_FunctionToPointerDecay: {
496 APValue Result;
497 if (EvaluateLValue(SubExpr, Result, Info))
498 return Result;
499 break;
500 }
501 }
502
503 return APValue();
504}
505
506APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
507 if (E->isBuiltinCall(Info.Ctx) ==
508 Builtin::BI__builtin___CFStringMakeConstantString ||
509 E->isBuiltinCall(Info.Ctx) ==
510 Builtin::BI__builtin___NSStringMakeConstantString)
511 return APValue(E);
512 return APValue();
513}
514
515APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
516 bool BoolResult;
517 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
518 return APValue();
519
520 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
521
522 APValue Result;
523 if (EvaluatePointer(EvalExpr, Result, Info))
524 return Result;
525 return APValue();
526}
527
528//===----------------------------------------------------------------------===//
529// Vector Evaluation
530//===----------------------------------------------------------------------===//
531
532namespace {
533 class VectorExprEvaluator
534 : public StmtVisitor<VectorExprEvaluator, APValue> {
535 EvalInfo &Info;
536 APValue GetZeroVector(QualType VecType);
537 public:
538
539 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
540
541 APValue VisitStmt(Stmt *S) {
542 return APValue();
543 }
544
545 APValue VisitParenExpr(ParenExpr *E)
546 { return Visit(E->getSubExpr()); }
547 APValue VisitUnaryExtension(const UnaryOperator *E)
548 { return Visit(E->getSubExpr()); }
549 APValue VisitUnaryPlus(const UnaryOperator *E)
550 { return Visit(E->getSubExpr()); }
551 APValue VisitUnaryReal(const UnaryOperator *E)
552 { return Visit(E->getSubExpr()); }
553 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
554 { return GetZeroVector(E->getType()); }
555 APValue VisitCastExpr(const CastExpr* E);
556 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
557 APValue VisitInitListExpr(const InitListExpr *E);
558 APValue VisitConditionalOperator(const ConditionalOperator *E);
559 APValue VisitChooseExpr(const ChooseExpr *E)
560 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
561 APValue VisitUnaryImag(const UnaryOperator *E);
562 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
563 // binary comparisons, binary and/or/xor,
564 // shufflevector, ExtVectorElementExpr
565 // (Note that these require implementing conversions
566 // between vector types.)
567 };
568} // end anonymous namespace
569
570static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
571 if (!E->getType()->isVectorType())
572 return false;
573 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
574 return !Result.isUninit();
575}
576
577APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
578 const VectorType *VTy = E->getType()->getAs<VectorType>();
579 QualType EltTy = VTy->getElementType();
580 unsigned NElts = VTy->getNumElements();
581 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
582
583 const Expr* SE = E->getSubExpr();
584 QualType SETy = SE->getType();
585 APValue Result = APValue();
586
587 // Check for vector->vector bitcast and scalar->vector splat.
588 if (SETy->isVectorType()) {
589 return this->Visit(const_cast<Expr*>(SE));
590 } else if (SETy->isIntegerType()) {
591 APSInt IntResult;
592 if (!EvaluateInteger(SE, IntResult, Info))
593 return APValue();
594 Result = APValue(IntResult);
595 } else if (SETy->isRealFloatingType()) {
596 APFloat F(0.0);
597 if (!EvaluateFloat(SE, F, Info))
598 return APValue();
599 Result = APValue(F);
600 } else
601 return APValue();
602
603 // For casts of a scalar to ExtVector, convert the scalar to the element type
604 // and splat it to all elements.
605 if (E->getType()->isExtVectorType()) {
606 if (EltTy->isIntegerType() && Result.isInt())
607 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
608 Info.Ctx));
609 else if (EltTy->isIntegerType())
610 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
611 Info.Ctx));
612 else if (EltTy->isRealFloatingType() && Result.isInt())
613 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
614 Info.Ctx));
615 else if (EltTy->isRealFloatingType())
616 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
617 Info.Ctx));
618 else
619 return APValue();
620
621 // Splat and create vector APValue.
622 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
623 return APValue(&Elts[0], Elts.size());
624 }
625
626 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
627 // to the vector. To construct the APValue vector initializer, bitcast the
628 // initializing value to an APInt, and shift out the bits pertaining to each
629 // element.
630 APSInt Init;
631 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
632
633 llvm::SmallVector<APValue, 4> Elts;
634 for (unsigned i = 0; i != NElts; ++i) {
635 APSInt Tmp = Init;
636 Tmp.extOrTrunc(EltWidth);
637
638 if (EltTy->isIntegerType())
639 Elts.push_back(APValue(Tmp));
640 else if (EltTy->isRealFloatingType())
641 Elts.push_back(APValue(APFloat(Tmp)));
642 else
643 return APValue();
644
645 Init >>= EltWidth;
646 }
647 return APValue(&Elts[0], Elts.size());
648}
649
650APValue
651VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
652 return this->Visit(const_cast<Expr*>(E->getInitializer()));
653}
654
655APValue
656VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
657 const VectorType *VT = E->getType()->getAs<VectorType>();
658 unsigned NumInits = E->getNumInits();
659 unsigned NumElements = VT->getNumElements();
660
661 QualType EltTy = VT->getElementType();
662 llvm::SmallVector<APValue, 4> Elements;
663
664 for (unsigned i = 0; i < NumElements; i++) {
665 if (EltTy->isIntegerType()) {
666 llvm::APSInt sInt(32);
667 if (i < NumInits) {
668 if (!EvaluateInteger(E->getInit(i), sInt, Info))
669 return APValue();
670 } else {
671 sInt = Info.Ctx.MakeIntValue(0, EltTy);
672 }
673 Elements.push_back(APValue(sInt));
674 } else {
675 llvm::APFloat f(0.0);
676 if (i < NumInits) {
677 if (!EvaluateFloat(E->getInit(i), f, Info))
678 return APValue();
679 } else {
680 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
681 }
682 Elements.push_back(APValue(f));
683 }
684 }
685 return APValue(&Elements[0], Elements.size());
686}
687
688APValue
689VectorExprEvaluator::GetZeroVector(QualType T) {
690 const VectorType *VT = T->getAs<VectorType>();
691 QualType EltTy = VT->getElementType();
692 APValue ZeroElement;
693 if (EltTy->isIntegerType())
694 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
695 else
696 ZeroElement =
697 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
698
699 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
700 return APValue(&Elements[0], Elements.size());
701}
702
703APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
704 bool BoolResult;
705 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
706 return APValue();
707
708 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
709
710 APValue Result;
711 if (EvaluateVector(EvalExpr, Result, Info))
712 return Result;
713 return APValue();
714}
715
716APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
717 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
718 Info.EvalResult.HasSideEffects = true;
719 return GetZeroVector(E->getType());
720}
721
722//===----------------------------------------------------------------------===//
723// Integer Evaluation
724//===----------------------------------------------------------------------===//
725
726namespace {
727class IntExprEvaluator
728 : public StmtVisitor<IntExprEvaluator, bool> {
729 EvalInfo &Info;
730 APValue &Result;
731public:
732 IntExprEvaluator(EvalInfo &info, APValue &result)
733 : Info(info), Result(result) {}
734
735 bool Success(const llvm::APSInt &SI, const Expr *E) {
736 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
737 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
738 "Invalid evaluation result.");
739 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
740 "Invalid evaluation result.");
741 Result = APValue(SI);
742 return true;
743 }
744
745 bool Success(const llvm::APInt &I, const Expr *E) {
746 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
747 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
748 "Invalid evaluation result.");
749 Result = APValue(APSInt(I));
750 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
751 return true;
752 }
753
754 bool Success(uint64_t Value, const Expr *E) {
755 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
756 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
757 return true;
758 }
759
760 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
761 // Take the first error.
762 if (Info.EvalResult.Diag == 0) {
763 Info.EvalResult.DiagLoc = L;
764 Info.EvalResult.Diag = D;
765 Info.EvalResult.DiagExpr = E;
766 }
767 return false;
768 }
769
770 //===--------------------------------------------------------------------===//
771 // Visitor Methods
772 //===--------------------------------------------------------------------===//
773
774 bool VisitStmt(Stmt *) {
775 assert(0 && "This should be called on integers, stmts are not integers");
776 return false;
777 }
778
779 bool VisitExpr(Expr *E) {
780 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
781 }
782
783 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
784
785 bool VisitIntegerLiteral(const IntegerLiteral *E) {
786 return Success(E->getValue(), E);
787 }
788 bool VisitCharacterLiteral(const CharacterLiteral *E) {
789 return Success(E->getValue(), E);
790 }
791 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
792 // Per gcc docs "this built-in function ignores top level
793 // qualifiers". We need to use the canonical version to properly
794 // be able to strip CRV qualifiers from the type.
795 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
796 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
797 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
798 T1.getUnqualifiedType()),
799 E);
800 }
801
802 bool CheckReferencedDecl(const Expr *E, const Decl *D);
803 bool VisitDeclRefExpr(const DeclRefExpr *E) {
804 return CheckReferencedDecl(E, E->getDecl());
805 }
806 bool VisitMemberExpr(const MemberExpr *E) {
807 if (CheckReferencedDecl(E, E->getMemberDecl())) {
808 // Conservatively assume a MemberExpr will have side-effects
809 Info.EvalResult.HasSideEffects = true;
810 return true;
811 }
812 return false;
813 }
814
815 bool VisitCallExpr(const CallExpr *E);
816 bool VisitBinaryOperator(const BinaryOperator *E);
817 bool VisitUnaryOperator(const UnaryOperator *E);
818 bool VisitConditionalOperator(const ConditionalOperator *E);
819
820 bool VisitCastExpr(CastExpr* E);
821 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
822
823 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
824 return Success(E->getValue(), E);
825 }
826
827 bool VisitGNUNullExpr(const GNUNullExpr *E) {
828 return Success(0, E);
829 }
830
831 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
832 return Success(0, E);
833 }
834
835 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
836 return Success(0, E);
837 }
838
839 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
840 return Success(E->EvaluateTrait(Info.Ctx), E);
841 }
842
843 bool VisitChooseExpr(const ChooseExpr *E) {
844 return Visit(E->getChosenSubExpr(Info.Ctx));
845 }
846
847 bool VisitUnaryReal(const UnaryOperator *E);
848 bool VisitUnaryImag(const UnaryOperator *E);
849
850private:
851 CharUnits GetAlignOfExpr(const Expr *E);
852 CharUnits GetAlignOfType(QualType T);
853 // FIXME: Missing: array subscript of vector, member of vector
854};
855} // end anonymous namespace
856
857static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
858 if (!E->getType()->isIntegralType())
859 return false;
860
861 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
862}
863
864static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
865 APValue Val;
866 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
867 return false;
868 Result = Val.getInt();
869 return true;
870}
871
872bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
873 // Enums are integer constant exprs.
874 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
875 return Success(ECD->getInitVal(), E);
876
877 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
878 // In C, they can also be folded, although they are not ICEs.
879 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
880 == Qualifiers::Const) {
881
882 if (isa<ParmVarDecl>(D))
883 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
884
885 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
886 if (const Expr *Init = VD->getAnyInitializer()) {
887 if (APValue *V = VD->getEvaluatedValue()) {
888 if (V->isInt())
889 return Success(V->getInt(), E);
890 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
891 }
892
893 if (VD->isEvaluatingValue())
894 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
895
896 VD->setEvaluatingValue();
897
898 if (Visit(const_cast<Expr*>(Init))) {
899 // Cache the evaluated value in the variable declaration.
900 VD->setEvaluatedValue(Result);
901 return true;
902 }
903
904 VD->setEvaluatedValue(APValue());
905 return false;
906 }
907 }
908 }
909
910 // Otherwise, random variable references are not constants.
911 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
912}
913
914/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
915/// as GCC.
916static int EvaluateBuiltinClassifyType(const CallExpr *E) {
917 // The following enum mimics the values returned by GCC.
918 // FIXME: Does GCC differ between lvalue and rvalue references here?
919 enum gcc_type_class {
920 no_type_class = -1,
921 void_type_class, integer_type_class, char_type_class,
922 enumeral_type_class, boolean_type_class,
923 pointer_type_class, reference_type_class, offset_type_class,
924 real_type_class, complex_type_class,
925 function_type_class, method_type_class,
926 record_type_class, union_type_class,
927 array_type_class, string_type_class,
928 lang_type_class
929 };
930
931 // If no argument was supplied, default to "no_type_class". This isn't
932 // ideal, however it is what gcc does.
933 if (E->getNumArgs() == 0)
934 return no_type_class;
935
936 QualType ArgTy = E->getArg(0)->getType();
937 if (ArgTy->isVoidType())
938 return void_type_class;
939 else if (ArgTy->isEnumeralType())
940 return enumeral_type_class;
941 else if (ArgTy->isBooleanType())
942 return boolean_type_class;
943 else if (ArgTy->isCharType())
944 return string_type_class; // gcc doesn't appear to use char_type_class
945 else if (ArgTy->isIntegerType())
946 return integer_type_class;
947 else if (ArgTy->isPointerType())
948 return pointer_type_class;
949 else if (ArgTy->isReferenceType())
950 return reference_type_class;
951 else if (ArgTy->isRealType())
952 return real_type_class;
953 else if (ArgTy->isComplexType())
954 return complex_type_class;
955 else if (ArgTy->isFunctionType())
956 return function_type_class;
957 else if (ArgTy->isStructureType())
958 return record_type_class;
959 else if (ArgTy->isUnionType())
960 return union_type_class;
961 else if (ArgTy->isArrayType())
962 return array_type_class;
963 else if (ArgTy->isUnionType())
964 return union_type_class;
965 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
966 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
967 return -1;
968}
969
970bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
971 switch (E->isBuiltinCall(Info.Ctx)) {
972 default:
973 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
974
975 case Builtin::BI__builtin_object_size: {
976 const Expr *Arg = E->getArg(0)->IgnoreParens();
977 Expr::EvalResult Base;
978
979 // TODO: Perhaps we should let LLVM lower this?
980 if (Arg->EvaluateAsAny(Base, Info.Ctx)
981 && Base.Val.getKind() == APValue::LValue
982 && !Base.HasSideEffects)
983 if (const Expr *LVBase = Base.Val.getLValueBase())
984 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
985 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
986 if (!VD->getType()->isIncompleteType()
987 && VD->getType()->isObjectType()
988 && !VD->getType()->isVariablyModifiedType()
989 && !VD->getType()->isDependentType()) {
990 CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
991 CharUnits Offset = Base.Val.getLValueOffset();
992 if (!Offset.isNegative() && Offset <= Size)
993 Size -= Offset;
994 else
995 Size = CharUnits::Zero();
996 return Success(Size.getQuantity(), E);
997 }
998 }
999 }
1000
1001 // If evaluating the argument has side-effects we can't determine
1002 // the size of the object and lower it to unknown now.
1003 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
1004 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
1005 return Success(-1ULL, E);
1006 return Success(0, E);
1007 }
1008
1009 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1010 }
1011
1012 case Builtin::BI__builtin_classify_type:
1013 return Success(EvaluateBuiltinClassifyType(E), E);
1014
1015 case Builtin::BI__builtin_constant_p:
1016 // __builtin_constant_p always has one operand: it returns true if that
1017 // operand can be folded, false otherwise.
1018 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
1019
1020 case Builtin::BI__builtin_eh_return_data_regno: {
1021 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1022 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1023 return Success(Operand, E);
1024 }
1025 }
1026}
1027
1028bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1029 if (E->getOpcode() == BinaryOperator::Comma) {
1030 if (!Visit(E->getRHS()))
1031 return false;
1032
1033 // If we can't evaluate the LHS, it might have side effects;
1034 // conservatively mark it.
1035 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1036 Info.EvalResult.HasSideEffects = true;
1037
1038 return true;
1039 }
1040
1041 if (E->isLogicalOp()) {
1042 // These need to be handled specially because the operands aren't
1043 // necessarily integral
1044 bool lhsResult, rhsResult;
1045
1046 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1047 // We were able to evaluate the LHS, see if we can get away with not
1048 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1049 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
1050 return Success(lhsResult, E);
1051
1052 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1053 if (E->getOpcode() == BinaryOperator::LOr)
1054 return Success(lhsResult || rhsResult, E);
1055 else
1056 return Success(lhsResult && rhsResult, E);
1057 }
1058 } else {
1059 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1060 // We can't evaluate the LHS; however, sometimes the result
1061 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1062 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
1063 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
1064 // Since we weren't able to evaluate the left hand side, it
1065 // must have had side effects.
1066 Info.EvalResult.HasSideEffects = true;
1067
1068 return Success(rhsResult, E);
1069 }
1070 }
1071 }
1072
1073 return false;
1074 }
1075
1076 QualType LHSTy = E->getLHS()->getType();
1077 QualType RHSTy = E->getRHS()->getType();
1078
1079 if (LHSTy->isAnyComplexType()) {
1080 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1081 APValue LHS, RHS;
1082
1083 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1084 return false;
1085
1086 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1087 return false;
1088
1089 if (LHS.isComplexFloat()) {
1090 APFloat::cmpResult CR_r =
1091 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1092 APFloat::cmpResult CR_i =
1093 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1094
1095 if (E->getOpcode() == BinaryOperator::EQ)
1096 return Success((CR_r == APFloat::cmpEqual &&
1097 CR_i == APFloat::cmpEqual), E);
1098 else {
1099 assert(E->getOpcode() == BinaryOperator::NE &&
1100 "Invalid complex comparison.");
1101 return Success(((CR_r == APFloat::cmpGreaterThan ||
1102 CR_r == APFloat::cmpLessThan) &&
1103 (CR_i == APFloat::cmpGreaterThan ||
1104 CR_i == APFloat::cmpLessThan)), E);
1105 }
1106 } else {
1107 if (E->getOpcode() == BinaryOperator::EQ)
1108 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1109 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1110 else {
1111 assert(E->getOpcode() == BinaryOperator::NE &&
1112 "Invalid compex comparison.");
1113 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1114 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1115 }
1116 }
1117 }
1118
1119 if (LHSTy->isRealFloatingType() &&
1120 RHSTy->isRealFloatingType()) {
1121 APFloat RHS(0.0), LHS(0.0);
1122
1123 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1124 return false;
1125
1126 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1127 return false;
1128
1129 APFloat::cmpResult CR = LHS.compare(RHS);
1130
1131 switch (E->getOpcode()) {
1132 default:
1133 assert(0 && "Invalid binary operator!");
1134 case BinaryOperator::LT:
1135 return Success(CR == APFloat::cmpLessThan, E);
1136 case BinaryOperator::GT:
1137 return Success(CR == APFloat::cmpGreaterThan, E);
1138 case BinaryOperator::LE:
1139 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1140 case BinaryOperator::GE:
1141 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1142 E);
1143 case BinaryOperator::EQ:
1144 return Success(CR == APFloat::cmpEqual, E);
1145 case BinaryOperator::NE:
1146 return Success(CR == APFloat::cmpGreaterThan
1147 || CR == APFloat::cmpLessThan, E);
1148 }
1149 }
1150
1151 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1152 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
1153 APValue LHSValue;
1154 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1155 return false;
1156
1157 APValue RHSValue;
1158 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1159 return false;
1160
1161 // Reject any bases from the normal codepath; we special-case comparisons
1162 // to null.
1163 if (LHSValue.getLValueBase()) {
1164 if (!E->isEqualityOp())
1165 return false;
1166 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
1167 return false;
1168 bool bres;
1169 if (!EvalPointerValueAsBool(LHSValue, bres))
1170 return false;
1171 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1172 } else if (RHSValue.getLValueBase()) {
1173 if (!E->isEqualityOp())
1174 return false;
1175 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
1176 return false;
1177 bool bres;
1178 if (!EvalPointerValueAsBool(RHSValue, bres))
1179 return false;
1180 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1181 }
1182
1183 if (E->getOpcode() == BinaryOperator::Sub) {
1184 const QualType Type = E->getLHS()->getType();
1185 const QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1186
1187 CharUnits ElementSize = CharUnits::One();
1188 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1189 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
1190
1191 CharUnits Diff = LHSValue.getLValueOffset() -
1192 RHSValue.getLValueOffset();
1193 return Success(Diff / ElementSize, E);
1194 }
1195 bool Result;
1196 if (E->getOpcode() == BinaryOperator::EQ) {
1197 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1198 } else {
1199 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1200 }
1201 return Success(Result, E);
1202 }
1203 }
1204 if (!LHSTy->isIntegralType() ||
1205 !RHSTy->isIntegralType()) {
1206 // We can't continue from here for non-integral types, and they
1207 // could potentially confuse the following operations.
1208 return false;
1209 }
1210
1211 // The LHS of a constant expr is always evaluated and needed.
1212 if (!Visit(E->getLHS()))
1213 return false; // error in subexpression.
1214
1215 APValue RHSVal;
1216 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1217 return false;
1218
1219 // Handle cases like (unsigned long)&a + 4.
1220 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1221 CharUnits Offset = Result.getLValueOffset();
1222 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1223 RHSVal.getInt().getZExtValue());
1224 if (E->getOpcode() == BinaryOperator::Add)
1225 Offset += AdditionalOffset;
1226 else
1227 Offset -= AdditionalOffset;
1228 Result = APValue(Result.getLValueBase(), Offset);
1229 return true;
1230 }
1231
1232 // Handle cases like 4 + (unsigned long)&a
1233 if (E->getOpcode() == BinaryOperator::Add &&
1234 RHSVal.isLValue() && Result.isInt()) {
1235 CharUnits Offset = RHSVal.getLValueOffset();
1236 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1237 Result = APValue(RHSVal.getLValueBase(), Offset);
1238 return true;
1239 }
1240
1241 // All the following cases expect both operands to be an integer
1242 if (!Result.isInt() || !RHSVal.isInt())
1243 return false;
1244
1245 APSInt& RHS = RHSVal.getInt();
1246
1247 switch (E->getOpcode()) {
1248 default:
1249 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1250 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1251 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1252 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1253 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1254 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1255 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
1256 case BinaryOperator::Div:
1257 if (RHS == 0)
1258 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1259 return Success(Result.getInt() / RHS, E);
1260 case BinaryOperator::Rem:
1261 if (RHS == 0)
1262 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1263 return Success(Result.getInt() % RHS, E);
1264 case BinaryOperator::Shl: {
1265 // FIXME: Warn about out of range shift amounts!
1266 unsigned SA =
1267 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1268 return Success(Result.getInt() << SA, E);
1269 }
1270 case BinaryOperator::Shr: {
1271 unsigned SA =
1272 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1273 return Success(Result.getInt() >> SA, E);
1274 }
1275
1276 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1277 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1278 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1279 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1280 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1281 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
1282 }
1283}
1284
1285bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1286 bool Cond;
1287 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1288 return false;
1289
1290 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1291}
1292
1293CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
1294 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1295 // the result is the size of the referenced type."
1296 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1297 // result shall be the alignment of the referenced type."
1298 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1299 T = Ref->getPointeeType();
1300
1301 // Get information about the alignment.
1302 unsigned CharSize = Info.Ctx.Target.getCharWidth();
1303
1304 // __alignof is defined to return the preferred alignment.
1305 return CharUnits::fromQuantity(
1306 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
1307}
1308
1309CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1310 E = E->IgnoreParens();
1311
1312 // alignof decl is always accepted, even if it doesn't make sense: we default
1313 // to 1 in those cases.
1314 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1315 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1316 /*RefAsPointee*/true);
1317
1318 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1319 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1320 /*RefAsPointee*/true);
1321
1322 return GetAlignOfType(E->getType());
1323}
1324
1325
1326/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1327/// expression's type.
1328bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1329 // Handle alignof separately.
1330 if (!E->isSizeOf()) {
1331 if (E->isArgumentType())
1332 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
1333 else
1334 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
1335 }
1336
1337 QualType SrcTy = E->getTypeOfArgument();
1338 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1339 // the result is the size of the referenced type."
1340 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1341 // result shall be the alignment of the referenced type."
1342 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1343 SrcTy = Ref->getPointeeType();
1344
1345 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1346 // extension.
1347 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1348 return Success(1, E);
1349
1350 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1351 if (!SrcTy->isConstantSizeType())
1352 return false;
1353
1354 // Get information about the size.
1355 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
1356}
1357
1358bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1359 // Special case unary operators that do not need their subexpression
1360 // evaluated. offsetof/sizeof/alignof are all special.
1361 if (E->isOffsetOfOp()) {
1362 // The AST for offsetof is defined in such a way that we can just
1363 // directly Evaluate it as an l-value.
1364 APValue LV;
1365 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
1366 return false;
1367 if (LV.getLValueBase())
1368 return false;
1369 return Success(LV.getLValueOffset().getQuantity(), E);
1370 }
1371
1372 if (E->getOpcode() == UnaryOperator::LNot) {
1373 // LNot's operand isn't necessarily an integer, so we handle it specially.
1374 bool bres;
1375 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1376 return false;
1377 return Success(!bres, E);
1378 }
1379
1380 // Only handle integral operations...
1381 if (!E->getSubExpr()->getType()->isIntegralType())
1382 return false;
1383
1384 // Get the operand value into 'Result'.
1385 if (!Visit(E->getSubExpr()))
1386 return false;
1387
1388 switch (E->getOpcode()) {
1389 default:
1390 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1391 // See C99 6.6p3.
1392 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1393 case UnaryOperator::Extension:
1394 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1395 // If so, we could clear the diagnostic ID.
1396 return true;
1397 case UnaryOperator::Plus:
1398 // The result is always just the subexpr.
1399 return true;
1400 case UnaryOperator::Minus:
1401 if (!Result.isInt()) return false;
1402 return Success(-Result.getInt(), E);
1403 case UnaryOperator::Not:
1404 if (!Result.isInt()) return false;
1405 return Success(~Result.getInt(), E);
1406 }
1407}
1408
1409/// HandleCast - This is used to evaluate implicit or explicit casts where the
1410/// result type is integer.
1411bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1412 Expr *SubExpr = E->getSubExpr();
1413 QualType DestType = E->getType();
1414 QualType SrcType = SubExpr->getType();
1415
1416 if (DestType->isBooleanType()) {
1417 bool BoolResult;
1418 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1419 return false;
1420 return Success(BoolResult, E);
1421 }
1422
1423 // Handle simple integer->integer casts.
1424 if (SrcType->isIntegralType()) {
1425 if (!Visit(SubExpr))
1426 return false;
1427
1428 if (!Result.isInt()) {
1429 // Only allow casts of lvalues if they are lossless.
1430 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1431 }
1432
1433 return Success(HandleIntToIntCast(DestType, SrcType,
1434 Result.getInt(), Info.Ctx), E);
1435 }
1436
1437 // FIXME: Clean this up!
1438 if (SrcType->isPointerType()) {
1439 APValue LV;
1440 if (!EvaluatePointer(SubExpr, LV, Info))
1441 return false;
1442
1443 if (LV.getLValueBase()) {
1444 // Only allow based lvalue casts if they are lossless.
1445 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1446 return false;
1447
1448 Result = LV;
1449 return true;
1450 }
1451
1452 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1453 SrcType);
1454 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1455 }
1456
1457 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1458 // This handles double-conversion cases, where there's both
1459 // an l-value promotion and an implicit conversion to int.
1460 APValue LV;
1461 if (!EvaluateLValue(SubExpr, LV, Info))
1462 return false;
1463
1464 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1465 return false;
1466
1467 Result = LV;
1468 return true;
1469 }
1470
1471 if (SrcType->isAnyComplexType()) {
1472 APValue C;
1473 if (!EvaluateComplex(SubExpr, C, Info))
1474 return false;
1475 if (C.isComplexFloat())
1476 return Success(HandleFloatToIntCast(DestType, SrcType,
1477 C.getComplexFloatReal(), Info.Ctx),
1478 E);
1479 else
1480 return Success(HandleIntToIntCast(DestType, SrcType,
1481 C.getComplexIntReal(), Info.Ctx), E);
1482 }
1483 // FIXME: Handle vectors
1484
1485 if (!SrcType->isRealFloatingType())
1486 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1487
1488 APFloat F(0.0);
1489 if (!EvaluateFloat(SubExpr, F, Info))
1490 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1491
1492 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1493}
1494
1495bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1496 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1497 APValue LV;
1498 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1499 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1500 return Success(LV.getComplexIntReal(), E);
1501 }
1502
1503 return Visit(E->getSubExpr());
1504}
1505
1506bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1507 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1508 APValue LV;
1509 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1510 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1511 return Success(LV.getComplexIntImag(), E);
1512 }
1513
1514 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1515 Info.EvalResult.HasSideEffects = true;
1516 return Success(0, E);
1517}
1518
1519//===----------------------------------------------------------------------===//
1520// Float Evaluation
1521//===----------------------------------------------------------------------===//
1522
1523namespace {
1524class FloatExprEvaluator
1525 : public StmtVisitor<FloatExprEvaluator, bool> {
1526 EvalInfo &Info;
1527 APFloat &Result;
1528public:
1529 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1530 : Info(info), Result(result) {}
1531
1532 bool VisitStmt(Stmt *S) {
1533 return false;
1534 }
1535
1536 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1537 bool VisitCallExpr(const CallExpr *E);
1538
1539 bool VisitUnaryOperator(const UnaryOperator *E);
1540 bool VisitBinaryOperator(const BinaryOperator *E);
1541 bool VisitFloatingLiteral(const FloatingLiteral *E);
1542 bool VisitCastExpr(CastExpr *E);
1543 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1544 bool VisitConditionalOperator(ConditionalOperator *E);
1545
1546 bool VisitChooseExpr(const ChooseExpr *E)
1547 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1548 bool VisitUnaryExtension(const UnaryOperator *E)
1549 { return Visit(E->getSubExpr()); }
1550
1551 // FIXME: Missing: __real__/__imag__, array subscript of vector,
1552 // member of vector, ImplicitValueInitExpr
1553};
1554} // end anonymous namespace
1555
1556static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1557 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1558}
1559
1560bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1561 switch (E->isBuiltinCall(Info.Ctx)) {
1562 default: return false;
1563 case Builtin::BI__builtin_huge_val:
1564 case Builtin::BI__builtin_huge_valf:
1565 case Builtin::BI__builtin_huge_vall:
1566 case Builtin::BI__builtin_inf:
1567 case Builtin::BI__builtin_inff:
1568 case Builtin::BI__builtin_infl: {
1569 const llvm::fltSemantics &Sem =
1570 Info.Ctx.getFloatTypeSemantics(E->getType());
1571 Result = llvm::APFloat::getInf(Sem);
1572 return true;
1573 }
1574
1575 case Builtin::BI__builtin_nan:
1576 case Builtin::BI__builtin_nanf:
1577 case Builtin::BI__builtin_nanl:
1578 // If this is __builtin_nan() turn this into a nan, otherwise we
1579 // can't constant fold it.
1580 if (const StringLiteral *S =
1581 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1582 if (!S->isWide()) {
1583 const llvm::fltSemantics &Sem =
1584 Info.Ctx.getFloatTypeSemantics(E->getType());
1585 unsigned Type = 0;
1586 if (!S->getString().empty() && S->getString().getAsInteger(0, Type))
1587 return false;
1588 Result = llvm::APFloat::getNaN(Sem, false, Type);
1589 return true;
1590 }
1591 }
1592 return false;
1593
1594 case Builtin::BI__builtin_fabs:
1595 case Builtin::BI__builtin_fabsf:
1596 case Builtin::BI__builtin_fabsl:
1597 if (!EvaluateFloat(E->getArg(0), Result, Info))
1598 return false;
1599
1600 if (Result.isNegative())
1601 Result.changeSign();
1602 return true;
1603
1604 case Builtin::BI__builtin_copysign:
1605 case Builtin::BI__builtin_copysignf:
1606 case Builtin::BI__builtin_copysignl: {
1607 APFloat RHS(0.);
1608 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1609 !EvaluateFloat(E->getArg(1), RHS, Info))
1610 return false;
1611 Result.copySign(RHS);
1612 return true;
1613 }
1614 }
1615}
1616
1617bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1618 if (E->getOpcode() == UnaryOperator::Deref)
1619 return false;
1620
1621 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1622 return false;
1623
1624 switch (E->getOpcode()) {
1625 default: return false;
1626 case UnaryOperator::Plus:
1627 return true;
1628 case UnaryOperator::Minus:
1629 Result.changeSign();
1630 return true;
1631 }
1632}
1633
1634bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1635 if (E->getOpcode() == BinaryOperator::Comma) {
1636 if (!EvaluateFloat(E->getRHS(), Result, Info))
1637 return false;
1638
1639 // If we can't evaluate the LHS, it might have side effects;
1640 // conservatively mark it.
1641 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1642 Info.EvalResult.HasSideEffects = true;
1643
1644 return true;
1645 }
1646
1647 // FIXME: Diagnostics? I really don't understand how the warnings
1648 // and errors are supposed to work.
1649 APFloat RHS(0.0);
1650 if (!EvaluateFloat(E->getLHS(), Result, Info))
1651 return false;
1652 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1653 return false;
1654
1655 switch (E->getOpcode()) {
1656 default: return false;
1657 case BinaryOperator::Mul:
1658 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1659 return true;
1660 case BinaryOperator::Add:
1661 Result.add(RHS, APFloat::rmNearestTiesToEven);
1662 return true;
1663 case BinaryOperator::Sub:
1664 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1665 return true;
1666 case BinaryOperator::Div:
1667 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1668 return true;
1669 }
1670}
1671
1672bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1673 Result = E->getValue();
1674 return true;
1675}
1676
1677bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1678 Expr* SubExpr = E->getSubExpr();
1679
1680 if (SubExpr->getType()->isIntegralType()) {
1681 APSInt IntResult;
1682 if (!EvaluateInteger(SubExpr, IntResult, Info))
1683 return false;
1684 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1685 IntResult, Info.Ctx);
1686 return true;
1687 }
1688 if (SubExpr->getType()->isRealFloatingType()) {
1689 if (!Visit(SubExpr))
1690 return false;
1691 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1692 Result, Info.Ctx);
1693 return true;
1694 }
1695 // FIXME: Handle complex types
1696
1697 return false;
1698}
1699
1700bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1701 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1702 return true;
1703}
1704
1705bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1706 bool Cond;
1707 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1708 return false;
1709
1710 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1711}
1712
1713//===----------------------------------------------------------------------===//
1714// Complex Evaluation (for float and integer)
1715//===----------------------------------------------------------------------===//
1716
1717namespace {
1718class ComplexExprEvaluator
1719 : public StmtVisitor<ComplexExprEvaluator, APValue> {
1720 EvalInfo &Info;
1721
1722public:
1723 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
1724
1725 //===--------------------------------------------------------------------===//
1726 // Visitor Methods
1727 //===--------------------------------------------------------------------===//
1728
1729 APValue VisitStmt(Stmt *S) {
1730 return APValue();
1731 }
1732
1733 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1734
1735 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1736 Expr* SubExpr = E->getSubExpr();
1737
1738 if (SubExpr->getType()->isRealFloatingType()) {
1739 APFloat Result(0.0);
1740
1741 if (!EvaluateFloat(SubExpr, Result, Info))
1742 return APValue();
1743
1744 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
1745 Result);
1746 } else {
1747 assert(SubExpr->getType()->isIntegerType() &&
1748 "Unexpected imaginary literal.");
1749
1750 llvm::APSInt Result;
1751 if (!EvaluateInteger(SubExpr, Result, Info))
1752 return APValue();
1753
1754 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1755 Zero = 0;
1756 return APValue(Zero, Result);
1757 }
1758 }
1759
1760 APValue VisitCastExpr(CastExpr *E) {
1761 Expr* SubExpr = E->getSubExpr();
1762 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
1763 QualType SubType = SubExpr->getType();
1764
1765 if (SubType->isRealFloatingType()) {
1766 APFloat Result(0.0);
1767
1768 if (!EvaluateFloat(SubExpr, Result, Info))
1769 return APValue();
1770
1771 if (EltType->isRealFloatingType()) {
1772 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
1773 return APValue(Result,
1774 APFloat(Result.getSemantics(), APFloat::fcZero, false));
1775 } else {
1776 llvm::APSInt IResult;
1777 IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1778 llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1779 Zero = 0;
1780 return APValue(IResult, Zero);
1781 }
1782 } else if (SubType->isIntegerType()) {
1783 APSInt Result;
1784
1785 if (!EvaluateInteger(SubExpr, Result, Info))
1786 return APValue();
1787
1788 if (EltType->isRealFloatingType()) {
1789 APFloat FResult =
1790 HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
1791 return APValue(FResult,
1792 APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1793 } else {
1794 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1795 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1796 Zero = 0;
1797 return APValue(Result, Zero);
1798 }
1799 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
1800 APValue Src;
1801
1802 if (!EvaluateComplex(SubExpr, Src, Info))
1803 return APValue();
1804
1805 QualType SrcType = CT->getElementType();
1806
1807 if (Src.isComplexFloat()) {
1808 if (EltType->isRealFloatingType()) {
1809 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1810 Src.getComplexFloatReal(),
1811 Info.Ctx),
1812 HandleFloatToFloatCast(EltType, SrcType,
1813 Src.getComplexFloatImag(),
1814 Info.Ctx));
1815 } else {
1816 return APValue(HandleFloatToIntCast(EltType, SrcType,
1817 Src.getComplexFloatReal(),
1818 Info.Ctx),
1819 HandleFloatToIntCast(EltType, SrcType,
1820 Src.getComplexFloatImag(),
1821 Info.Ctx));
1822 }
1823 } else {
1824 assert(Src.isComplexInt() && "Invalid evaluate result.");
1825 if (EltType->isRealFloatingType()) {
1826 return APValue(HandleIntToFloatCast(EltType, SrcType,
1827 Src.getComplexIntReal(),
1828 Info.Ctx),
1829 HandleIntToFloatCast(EltType, SrcType,
1830 Src.getComplexIntImag(),
1831 Info.Ctx));
1832 } else {
1833 return APValue(HandleIntToIntCast(EltType, SrcType,
1834 Src.getComplexIntReal(),
1835 Info.Ctx),
1836 HandleIntToIntCast(EltType, SrcType,
1837 Src.getComplexIntImag(),
1838 Info.Ctx));
1839 }
1840 }
1841 }
1842
1843 // FIXME: Handle more casts.
1844 return APValue();
1845 }
1846
1847 APValue VisitBinaryOperator(const BinaryOperator *E);
1848 APValue VisitChooseExpr(const ChooseExpr *E)
1849 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1850 APValue VisitUnaryExtension(const UnaryOperator *E)
1851 { return Visit(E->getSubExpr()); }
1852 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
1853 // conditional ?:, comma
1854};
1855} // end anonymous namespace
1856
1857static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) {
1858 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1859 assert((!Result.isComplexFloat() ||
1860 (&Result.getComplexFloatReal().getSemantics() ==
1861 &Result.getComplexFloatImag().getSemantics())) &&
1862 "Invalid complex evaluation.");
1863 return Result.isComplexFloat() || Result.isComplexInt();
1864}
1865
1866APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1867 APValue Result, RHS;
1868
1869 if (!EvaluateComplex(E->getLHS(), Result, Info))
1870 return APValue();
1871
1872 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1873 return APValue();
1874
1875 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1876 "Invalid operands to binary operator.");
1877 switch (E->getOpcode()) {
1878 default: return APValue();
1879 case BinaryOperator::Add:
1880 if (Result.isComplexFloat()) {
1881 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1882 APFloat::rmNearestTiesToEven);
1883 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1884 APFloat::rmNearestTiesToEven);
1885 } else {
1886 Result.getComplexIntReal() += RHS.getComplexIntReal();
1887 Result.getComplexIntImag() += RHS.getComplexIntImag();
1888 }
1889 break;
1890 case BinaryOperator::Sub:
1891 if (Result.isComplexFloat()) {
1892 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1893 APFloat::rmNearestTiesToEven);
1894 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1895 APFloat::rmNearestTiesToEven);
1896 } else {
1897 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1898 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1899 }
1900 break;
1901 case BinaryOperator::Mul:
1902 if (Result.isComplexFloat()) {
1903 APValue LHS = Result;
1904 APFloat &LHS_r = LHS.getComplexFloatReal();
1905 APFloat &LHS_i = LHS.getComplexFloatImag();
1906 APFloat &RHS_r = RHS.getComplexFloatReal();
1907 APFloat &RHS_i = RHS.getComplexFloatImag();
1908
1909 APFloat Tmp = LHS_r;
1910 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1911 Result.getComplexFloatReal() = Tmp;
1912 Tmp = LHS_i;
1913 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1914 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1915
1916 Tmp = LHS_r;
1917 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1918 Result.getComplexFloatImag() = Tmp;
1919 Tmp = LHS_i;
1920 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1921 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1922 } else {
1923 APValue LHS = Result;
1924 Result.getComplexIntReal() =
1925 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1926 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1927 Result.getComplexIntImag() =
1928 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1929 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1930 }
1931 break;
1932 }
1933
1934 return Result;
1935}
1936
1937//===----------------------------------------------------------------------===//
1938// Top level Expr::Evaluate method.
1939//===----------------------------------------------------------------------===//
1940
1941/// Evaluate - Return true if this is a constant which we can fold using
1942/// any crazy technique (that has nothing to do with language standards) that
1943/// we want to. If this function returns true, it returns the folded constant
1944/// in Result.
1945bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1946 EvalInfo Info(Ctx, Result);
1947
1948 if (getType()->isVectorType()) {
1949 if (!EvaluateVector(this, Result.Val, Info))
1950 return false;
1951 } else if (getType()->isIntegerType()) {
1952 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1953 return false;
1954 } else if (getType()->hasPointerRepresentation()) {
1955 if (!EvaluatePointer(this, Result.Val, Info))
1956 return false;
1957 } else if (getType()->isRealFloatingType()) {
1958 llvm::APFloat f(0.0);
1959 if (!EvaluateFloat(this, f, Info))
1960 return false;
1961
1962 Result.Val = APValue(f);
1963 } else if (getType()->isAnyComplexType()) {
1964 if (!EvaluateComplex(this, Result.Val, Info))
1965 return false;
1966 } else
1967 return false;
1968
1969 return true;
1970}
1971
1972bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
1973 EvalInfo Info(Ctx, Result, true);
1974
1975 if (getType()->isVectorType()) {
1976 if (!EvaluateVector(this, Result.Val, Info))
1977 return false;
1978 } else if (getType()->isIntegerType()) {
1979 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1980 return false;
1981 } else if (getType()->hasPointerRepresentation()) {
1982 if (!EvaluatePointer(this, Result.Val, Info))
1983 return false;
1984 } else if (getType()->isRealFloatingType()) {
1985 llvm::APFloat f(0.0);
1986 if (!EvaluateFloat(this, f, Info))
1987 return false;
1988
1989 Result.Val = APValue(f);
1990 } else if (getType()->isAnyComplexType()) {
1991 if (!EvaluateComplex(this, Result.Val, Info))
1992 return false;
1993 } else
1994 return false;
1995
1996 return true;
1997}
1998
1999bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2000 EvalResult Scratch;
2001 EvalInfo Info(Ctx, Scratch);
2002
2003 return HandleConversionToBool(this, Result, Info);
2004}
2005
2006bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2007 EvalInfo Info(Ctx, Result);
2008
2009 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2010}
2011
2012bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2013 EvalInfo Info(Ctx, Result, true);
2014
2015 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2016}
2017
2018/// isEvaluatable - Call Evaluate to see if this expression can be constant
2019/// folded, but discard the result.
2020bool Expr::isEvaluatable(ASTContext &Ctx) const {
2021 EvalResult Result;
2022 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
2023}
2024
2025bool Expr::HasSideEffects(ASTContext &Ctx) const {
2026 Expr::EvalResult Result;
2027 EvalInfo Info(Ctx, Result);
2028 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2029}
2030
2031APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
2032 EvalResult EvalResult;
2033 bool Result = Evaluate(EvalResult, Ctx);
2034 Result = Result;
2035 assert(Result && "Could not evaluate expression");
2036 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
2037
2038 return EvalResult.Val.getInt();
2039}