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