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 // Constant expression evaluation produces four main results:
13 //
14 //  * A success/failure flag indicating whether constant folding was successful.
15 //    This is the 'bool' return value used by most of the code in this file. A
16 //    'false' return value indicates that constant folding has failed, and any
17 //    appropriate diagnostic has already been produced.
18 //
19 //  * An evaluated result, valid only if constant folding has not failed.
20 //
21 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 //    where it is possible to determine the evaluated result regardless.
24 //
25 //  * A set of notes indicating why the evaluation was not a constant expression
26 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 //    too, why the expression could not be folded.
28 //
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using llvm::APSInt;
53 using llvm::APFloat;
54 
55 static bool IsGlobalLValue(APValue::LValueBase B);
56 
57 namespace {
58   struct LValue;
59   struct CallStackFrame;
60   struct EvalInfo;
61 
62   static QualType getType(APValue::LValueBase B) {
63     if (!B) return QualType();
64     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65       return D->getType();
66 
67     const Expr *Base = B.get<const Expr*>();
68 
69     // For a materialized temporary, the type of the temporary we materialized
70     // may not be the type of the expression.
71     if (const MaterializeTemporaryExpr *MTE =
72             dyn_cast<MaterializeTemporaryExpr>(Base)) {
73       SmallVector<const Expr *, 2> CommaLHSs;
74       SmallVector<SubobjectAdjustment, 2> Adjustments;
75       const Expr *Temp = MTE->GetTemporaryExpr();
76       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77                                                                Adjustments);
78       // Keep any cv-qualifiers from the reference if we generated a temporary
79       // for it.
80       if (Inner != Temp)
81         return Inner->getType();
82     }
83 
84     return Base->getType();
85   }
86 
87   /// Get an LValue path entry, which is known to not be an array index, as a
88   /// field or base class.
89   static
90   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91     APValue::BaseOrMemberType Value;
92     Value.setFromOpaqueValue(E.BaseOrMember);
93     return Value;
94   }
95 
96   /// Get an LValue path entry, which is known to not be an array index, as a
97   /// field declaration.
98   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100   }
101   /// Get an LValue path entry, which is known to not be an array index, as a
102   /// base class declaration.
103   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105   }
106   /// Determine whether this LValue path entry for a base class names a virtual
107   /// base class.
108   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109     return getAsBaseOrMember(E).getInt();
110   }
111 
112   /// Find the path length and type of the most-derived subobject in the given
113   /// path, and find the size of the containing array, if any.
114   static
115   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116                                     ArrayRef<APValue::LValuePathEntry> Path,
117                                     uint64_t &ArraySize, QualType &Type) {
118     unsigned MostDerivedLength = 0;
119     Type = Base;
120     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121       if (Type->isArrayType()) {
122         const ConstantArrayType *CAT =
123           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124         Type = CAT->getElementType();
125         ArraySize = CAT->getSize().getZExtValue();
126         MostDerivedLength = I + 1;
127       } else if (Type->isAnyComplexType()) {
128         const ComplexType *CT = Type->castAs<ComplexType>();
129         Type = CT->getElementType();
130         ArraySize = 2;
131         MostDerivedLength = I + 1;
132       } else if (const FieldDecl *FD = getAsField(Path[I])) {
133         Type = FD->getType();
134         ArraySize = 0;
135         MostDerivedLength = I + 1;
136       } else {
137         // Path[I] describes a base class.
138         ArraySize = 0;
139       }
140     }
141     return MostDerivedLength;
142   }
143 
144   // The order of this enum is important for diagnostics.
145   enum CheckSubobjectKind {
146     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147     CSK_This, CSK_Real, CSK_Imag
148   };
149 
150   /// A path from a glvalue to a subobject of that glvalue.
151   struct SubobjectDesignator {
152     /// True if the subobject was named in a manner not supported by C++11. Such
153     /// lvalues can still be folded, but they are not core constant expressions
154     /// and we cannot perform lvalue-to-rvalue conversions on them.
155     bool Invalid : 1;
156 
157     /// Is this a pointer one past the end of an object?
158     bool IsOnePastTheEnd : 1;
159 
160     /// The length of the path to the most-derived object of which this is a
161     /// subobject.
162     unsigned MostDerivedPathLength : 30;
163 
164     /// The size of the array of which the most-derived object is an element, or
165     /// 0 if the most-derived object is not an array element.
166     uint64_t MostDerivedArraySize;
167 
168     /// The type of the most derived object referred to by this address.
169     QualType MostDerivedType;
170 
171     typedef APValue::LValuePathEntry PathEntry;
172 
173     /// The entries on the path from the glvalue to the designated subobject.
174     SmallVector<PathEntry, 8> Entries;
175 
176     SubobjectDesignator() : Invalid(true) {}
177 
178     explicit SubobjectDesignator(QualType T)
179       : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180         MostDerivedArraySize(0), MostDerivedType(T) {}
181 
182     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183       : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184         MostDerivedPathLength(0), MostDerivedArraySize(0) {
185       if (!Invalid) {
186         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187         ArrayRef<PathEntry> VEntries = V.getLValuePath();
188         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189         if (V.getLValueBase())
190           MostDerivedPathLength =
191               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192                                        V.getLValuePath(), MostDerivedArraySize,
193                                        MostDerivedType);
194       }
195     }
196 
197     void setInvalid() {
198       Invalid = true;
199       Entries.clear();
200     }
201 
202     /// Determine whether this is a one-past-the-end pointer.
203     bool isOnePastTheEnd() const {
204       if (IsOnePastTheEnd)
205         return true;
206       if (MostDerivedArraySize &&
207           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
208         return true;
209       return false;
210     }
211 
212     /// Check that this refers to a valid subobject.
213     bool isValidSubobject() const {
214       if (Invalid)
215         return false;
216       return !isOnePastTheEnd();
217     }
218     /// Check that this refers to a valid subobject, and if not, produce a
219     /// relevant diagnostic and set the designator as invalid.
220     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
221 
222     /// Update this designator to refer to the first element within this array.
223     void addArrayUnchecked(const ConstantArrayType *CAT) {
224       PathEntry Entry;
225       Entry.ArrayIndex = 0;
226       Entries.push_back(Entry);
227 
228       // This is a most-derived object.
229       MostDerivedType = CAT->getElementType();
230       MostDerivedArraySize = CAT->getSize().getZExtValue();
231       MostDerivedPathLength = Entries.size();
232     }
233     /// Update this designator to refer to the given base or member of this
234     /// object.
235     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
236       PathEntry Entry;
237       APValue::BaseOrMemberType Value(D, Virtual);
238       Entry.BaseOrMember = Value.getOpaqueValue();
239       Entries.push_back(Entry);
240 
241       // If this isn't a base class, it's a new most-derived object.
242       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243         MostDerivedType = FD->getType();
244         MostDerivedArraySize = 0;
245         MostDerivedPathLength = Entries.size();
246       }
247     }
248     /// Update this designator to refer to the given complex component.
249     void addComplexUnchecked(QualType EltTy, bool Imag) {
250       PathEntry Entry;
251       Entry.ArrayIndex = Imag;
252       Entries.push_back(Entry);
253 
254       // This is technically a most-derived object, though in practice this
255       // is unlikely to matter.
256       MostDerivedType = EltTy;
257       MostDerivedArraySize = 2;
258       MostDerivedPathLength = Entries.size();
259     }
260     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
261     /// Add N to the address of this subobject.
262     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
263       if (Invalid) return;
264       if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
265         Entries.back().ArrayIndex += N;
266         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
268           setInvalid();
269         }
270         return;
271       }
272       // [expr.add]p4: For the purposes of these operators, a pointer to a
273       // nonarray object behaves the same as a pointer to the first element of
274       // an array of length one with the type of the object as its element type.
275       if (IsOnePastTheEnd && N == (uint64_t)-1)
276         IsOnePastTheEnd = false;
277       else if (!IsOnePastTheEnd && N == 1)
278         IsOnePastTheEnd = true;
279       else if (N != 0) {
280         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
281         setInvalid();
282       }
283     }
284   };
285 
286   /// A stack frame in the constexpr call stack.
287   struct CallStackFrame {
288     EvalInfo &Info;
289 
290     /// Parent - The caller of this stack frame.
291     CallStackFrame *Caller;
292 
293     /// CallLoc - The location of the call expression for this call.
294     SourceLocation CallLoc;
295 
296     /// Callee - The function which was called.
297     const FunctionDecl *Callee;
298 
299     /// Index - The call index of this call.
300     unsigned Index;
301 
302     /// This - The binding for the this pointer in this call, if any.
303     const LValue *This;
304 
305     /// Arguments - Parameter bindings for this function call, indexed by
306     /// parameters' function scope indices.
307     APValue *Arguments;
308 
309     // Note that we intentionally use std::map here so that references to
310     // values are stable.
311     typedef std::map<const void*, APValue> MapTy;
312     typedef MapTy::const_iterator temp_iterator;
313     /// Temporaries - Temporary lvalues materialized within this stack frame.
314     MapTy Temporaries;
315 
316     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317                    const FunctionDecl *Callee, const LValue *This,
318                    APValue *Arguments);
319     ~CallStackFrame();
320 
321     APValue *getTemporary(const void *Key) {
322       MapTy::iterator I = Temporaries.find(Key);
323       return I == Temporaries.end() ? 0 : &I->second;
324     }
325     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
326   };
327 
328   /// Temporarily override 'this'.
329   class ThisOverrideRAII {
330   public:
331     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332         : Frame(Frame), OldThis(Frame.This) {
333       if (Enable)
334         Frame.This = NewThis;
335     }
336     ~ThisOverrideRAII() {
337       Frame.This = OldThis;
338     }
339   private:
340     CallStackFrame &Frame;
341     const LValue *OldThis;
342   };
343 
344   /// A partial diagnostic which we might know in advance that we are not going
345   /// to emit.
346   class OptionalDiagnostic {
347     PartialDiagnostic *Diag;
348 
349   public:
350     explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
351 
352     template<typename T>
353     OptionalDiagnostic &operator<<(const T &v) {
354       if (Diag)
355         *Diag << v;
356       return *this;
357     }
358 
359     OptionalDiagnostic &operator<<(const APSInt &I) {
360       if (Diag) {
361         SmallVector<char, 32> Buffer;
362         I.toString(Buffer);
363         *Diag << StringRef(Buffer.data(), Buffer.size());
364       }
365       return *this;
366     }
367 
368     OptionalDiagnostic &operator<<(const APFloat &F) {
369       if (Diag) {
370         // FIXME: Force the precision of the source value down so we don't
371         // print digits which are usually useless (we don't really care here if
372         // we truncate a digit by accident in edge cases).  Ideally,
373         // APFloat::toString would automatically print the shortest
374         // representation which rounds to the correct value, but it's a bit
375         // tricky to implement.
376         unsigned precision =
377             llvm::APFloat::semanticsPrecision(F.getSemantics());
378         precision = (precision * 59 + 195) / 196;
379         SmallVector<char, 32> Buffer;
380         F.toString(Buffer, precision);
381         *Diag << StringRef(Buffer.data(), Buffer.size());
382       }
383       return *this;
384     }
385   };
386 
387   /// A cleanup, and a flag indicating whether it is lifetime-extended.
388   class Cleanup {
389     llvm::PointerIntPair<APValue*, 1, bool> Value;
390 
391   public:
392     Cleanup(APValue *Val, bool IsLifetimeExtended)
393         : Value(Val, IsLifetimeExtended) {}
394 
395     bool isLifetimeExtended() const { return Value.getInt(); }
396     void endLifetime() {
397       *Value.getPointer() = APValue();
398     }
399   };
400 
401   /// EvalInfo - This is a private struct used by the evaluator to capture
402   /// information about a subexpression as it is folded.  It retains information
403   /// about the AST context, but also maintains information about the folded
404   /// expression.
405   ///
406   /// If an expression could be evaluated, it is still possible it is not a C
407   /// "integer constant expression" or constant expression.  If not, this struct
408   /// captures information about how and why not.
409   ///
410   /// One bit of information passed *into* the request for constant folding
411   /// indicates whether the subexpression is "evaluated" or not according to C
412   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
413   /// evaluate the expression regardless of what the RHS is, but C only allows
414   /// certain things in certain situations.
415   struct EvalInfo {
416     ASTContext &Ctx;
417 
418     /// EvalStatus - Contains information about the evaluation.
419     Expr::EvalStatus &EvalStatus;
420 
421     /// CurrentCall - The top of the constexpr call stack.
422     CallStackFrame *CurrentCall;
423 
424     /// CallStackDepth - The number of calls in the call stack right now.
425     unsigned CallStackDepth;
426 
427     /// NextCallIndex - The next call index to assign.
428     unsigned NextCallIndex;
429 
430     /// StepsLeft - The remaining number of evaluation steps we're permitted
431     /// to perform. This is essentially a limit for the number of statements
432     /// we will evaluate.
433     unsigned StepsLeft;
434 
435     /// BottomFrame - The frame in which evaluation started. This must be
436     /// initialized after CurrentCall and CallStackDepth.
437     CallStackFrame BottomFrame;
438 
439     /// A stack of values whose lifetimes end at the end of some surrounding
440     /// evaluation frame.
441     llvm::SmallVector<Cleanup, 16> CleanupStack;
442 
443     /// EvaluatingDecl - This is the declaration whose initializer is being
444     /// evaluated, if any.
445     APValue::LValueBase EvaluatingDecl;
446 
447     /// EvaluatingDeclValue - This is the value being constructed for the
448     /// declaration whose initializer is being evaluated, if any.
449     APValue *EvaluatingDeclValue;
450 
451     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452     /// notes attached to it will also be stored, otherwise they will not be.
453     bool HasActiveDiagnostic;
454 
455     enum EvaluationMode {
456       /// Evaluate as a constant expression. Stop if we find that the expression
457       /// is not a constant expression.
458       EM_ConstantExpression,
459 
460       /// Evaluate as a potential constant expression. Keep going if we hit a
461       /// construct that we can't evaluate yet (because we don't yet know the
462       /// value of something) but stop if we hit something that could never be
463       /// a constant expression.
464       EM_PotentialConstantExpression,
465 
466       /// Fold the expression to a constant. Stop if we hit a side-effect that
467       /// we can't model.
468       EM_ConstantFold,
469 
470       /// Evaluate the expression looking for integer overflow and similar
471       /// issues. Don't worry about side-effects, and try to visit all
472       /// subexpressions.
473       EM_EvaluateForOverflow,
474 
475       /// Evaluate in any way we know how. Don't worry about side-effects that
476       /// can't be modeled.
477       EM_IgnoreSideEffects,
478 
479       /// Evaluate as a constant expression. Stop if we find that the expression
480       /// is not a constant expression. Some expressions can be retried in the
481       /// optimizer if we don't constant fold them here, but in an unevaluated
482       /// context we try to fold them immediately since the optimizer never
483       /// gets a chance to look at it.
484       EM_ConstantExpressionUnevaluated,
485 
486       /// Evaluate as a potential constant expression. Keep going if we hit a
487       /// construct that we can't evaluate yet (because we don't yet know the
488       /// value of something) but stop if we hit something that could never be
489       /// a constant expression. Some expressions can be retried in the
490       /// optimizer if we don't constant fold them here, but in an unevaluated
491       /// context we try to fold them immediately since the optimizer never
492       /// gets a chance to look at it.
493       EM_PotentialConstantExpressionUnevaluated
494     } EvalMode;
495 
496     /// Are we checking whether the expression is a potential constant
497     /// expression?
498     bool checkingPotentialConstantExpression() const {
499       return EvalMode == EM_PotentialConstantExpression ||
500              EvalMode == EM_PotentialConstantExpressionUnevaluated;
501     }
502 
503     /// Are we checking an expression for overflow?
504     // FIXME: We should check for any kind of undefined or suspicious behavior
505     // in such constructs, not just overflow.
506     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
507 
508     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
509       : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
510         CallStackDepth(0), NextCallIndex(1),
511         StepsLeft(getLangOpts().ConstexprStepLimit),
512         BottomFrame(*this, SourceLocation(), 0, 0, 0),
513         EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
514         HasActiveDiagnostic(false), EvalMode(Mode) {}
515 
516     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
517       EvaluatingDecl = Base;
518       EvaluatingDeclValue = &Value;
519     }
520 
521     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
522 
523     bool CheckCallLimit(SourceLocation Loc) {
524       // Don't perform any constexpr calls (other than the call we're checking)
525       // when checking a potential constant expression.
526       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
527         return false;
528       if (NextCallIndex == 0) {
529         // NextCallIndex has wrapped around.
530         Diag(Loc, diag::note_constexpr_call_limit_exceeded);
531         return false;
532       }
533       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
534         return true;
535       Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
536         << getLangOpts().ConstexprCallDepth;
537       return false;
538     }
539 
540     CallStackFrame *getCallFrame(unsigned CallIndex) {
541       assert(CallIndex && "no call index in getCallFrame");
542       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
543       // be null in this loop.
544       CallStackFrame *Frame = CurrentCall;
545       while (Frame->Index > CallIndex)
546         Frame = Frame->Caller;
547       return (Frame->Index == CallIndex) ? Frame : 0;
548     }
549 
550     bool nextStep(const Stmt *S) {
551       if (!StepsLeft) {
552         Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
553         return false;
554       }
555       --StepsLeft;
556       return true;
557     }
558 
559   private:
560     /// Add a diagnostic to the diagnostics list.
561     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
562       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
563       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
564       return EvalStatus.Diag->back().second;
565     }
566 
567     /// Add notes containing a call stack to the current point of evaluation.
568     void addCallStack(unsigned Limit);
569 
570   public:
571     /// Diagnose that the evaluation cannot be folded.
572     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
573                               = diag::note_invalid_subexpr_in_const_expr,
574                             unsigned ExtraNotes = 0) {
575       if (EvalStatus.Diag) {
576         // If we have a prior diagnostic, it will be noting that the expression
577         // isn't a constant expression. This diagnostic is more important,
578         // unless we require this evaluation to produce a constant expression.
579         //
580         // FIXME: We might want to show both diagnostics to the user in
581         // EM_ConstantFold mode.
582         if (!EvalStatus.Diag->empty()) {
583           switch (EvalMode) {
584           case EM_ConstantFold:
585           case EM_IgnoreSideEffects:
586           case EM_EvaluateForOverflow:
587             if (!EvalStatus.HasSideEffects)
588               break;
589             // We've had side-effects; we want the diagnostic from them, not
590             // some later problem.
591           case EM_ConstantExpression:
592           case EM_PotentialConstantExpression:
593           case EM_ConstantExpressionUnevaluated:
594           case EM_PotentialConstantExpressionUnevaluated:
595             HasActiveDiagnostic = false;
596             return OptionalDiagnostic();
597           }
598         }
599 
600         unsigned CallStackNotes = CallStackDepth - 1;
601         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
602         if (Limit)
603           CallStackNotes = std::min(CallStackNotes, Limit + 1);
604         if (checkingPotentialConstantExpression())
605           CallStackNotes = 0;
606 
607         HasActiveDiagnostic = true;
608         EvalStatus.Diag->clear();
609         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
610         addDiag(Loc, DiagId);
611         if (!checkingPotentialConstantExpression())
612           addCallStack(Limit);
613         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
614       }
615       HasActiveDiagnostic = false;
616       return OptionalDiagnostic();
617     }
618 
619     OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
620                               = diag::note_invalid_subexpr_in_const_expr,
621                             unsigned ExtraNotes = 0) {
622       if (EvalStatus.Diag)
623         return Diag(E->getExprLoc(), DiagId, ExtraNotes);
624       HasActiveDiagnostic = false;
625       return OptionalDiagnostic();
626     }
627 
628     /// Diagnose that the evaluation does not produce a C++11 core constant
629     /// expression.
630     ///
631     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
632     /// EM_PotentialConstantExpression mode and we produce one of these.
633     template<typename LocArg>
634     OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
635                                  = diag::note_invalid_subexpr_in_const_expr,
636                                unsigned ExtraNotes = 0) {
637       // Don't override a previous diagnostic. Don't bother collecting
638       // diagnostics if we're evaluating for overflow.
639       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
640         HasActiveDiagnostic = false;
641         return OptionalDiagnostic();
642       }
643       return Diag(Loc, DiagId, ExtraNotes);
644     }
645 
646     /// Add a note to a prior diagnostic.
647     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
648       if (!HasActiveDiagnostic)
649         return OptionalDiagnostic();
650       return OptionalDiagnostic(&addDiag(Loc, DiagId));
651     }
652 
653     /// Add a stack of notes to a prior diagnostic.
654     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
655       if (HasActiveDiagnostic) {
656         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
657                                 Diags.begin(), Diags.end());
658       }
659     }
660 
661     /// Should we continue evaluation after encountering a side-effect that we
662     /// couldn't model?
663     bool keepEvaluatingAfterSideEffect() {
664       switch (EvalMode) {
665       case EM_PotentialConstantExpression:
666       case EM_PotentialConstantExpressionUnevaluated:
667       case EM_EvaluateForOverflow:
668       case EM_IgnoreSideEffects:
669         return true;
670 
671       case EM_ConstantExpression:
672       case EM_ConstantExpressionUnevaluated:
673       case EM_ConstantFold:
674         return false;
675       }
676       llvm_unreachable("Missed EvalMode case");
677     }
678 
679     /// Note that we have had a side-effect, and determine whether we should
680     /// keep evaluating.
681     bool noteSideEffect() {
682       EvalStatus.HasSideEffects = true;
683       return keepEvaluatingAfterSideEffect();
684     }
685 
686     /// Should we continue evaluation as much as possible after encountering a
687     /// construct which can't be reduced to a value?
688     bool keepEvaluatingAfterFailure() {
689       if (!StepsLeft)
690         return false;
691 
692       switch (EvalMode) {
693       case EM_PotentialConstantExpression:
694       case EM_PotentialConstantExpressionUnevaluated:
695       case EM_EvaluateForOverflow:
696         return true;
697 
698       case EM_ConstantExpression:
699       case EM_ConstantExpressionUnevaluated:
700       case EM_ConstantFold:
701       case EM_IgnoreSideEffects:
702         return false;
703       }
704       llvm_unreachable("Missed EvalMode case");
705     }
706   };
707 
708   /// Object used to treat all foldable expressions as constant expressions.
709   struct FoldConstant {
710     EvalInfo &Info;
711     bool Enabled;
712     bool HadNoPriorDiags;
713     EvalInfo::EvaluationMode OldMode;
714 
715     explicit FoldConstant(EvalInfo &Info, bool Enabled)
716       : Info(Info),
717         Enabled(Enabled),
718         HadNoPriorDiags(Info.EvalStatus.Diag &&
719                         Info.EvalStatus.Diag->empty() &&
720                         !Info.EvalStatus.HasSideEffects),
721         OldMode(Info.EvalMode) {
722       if (Enabled &&
723           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
724            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
725         Info.EvalMode = EvalInfo::EM_ConstantFold;
726     }
727     void keepDiagnostics() { Enabled = false; }
728     ~FoldConstant() {
729       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
730           !Info.EvalStatus.HasSideEffects)
731         Info.EvalStatus.Diag->clear();
732       Info.EvalMode = OldMode;
733     }
734   };
735 
736   /// RAII object used to suppress diagnostics and side-effects from a
737   /// speculative evaluation.
738   class SpeculativeEvaluationRAII {
739     EvalInfo &Info;
740     Expr::EvalStatus Old;
741 
742   public:
743     SpeculativeEvaluationRAII(EvalInfo &Info,
744                               SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
745       : Info(Info), Old(Info.EvalStatus) {
746       Info.EvalStatus.Diag = NewDiag;
747       // If we're speculatively evaluating, we may have skipped over some
748       // evaluations and missed out a side effect.
749       Info.EvalStatus.HasSideEffects = true;
750     }
751     ~SpeculativeEvaluationRAII() {
752       Info.EvalStatus = Old;
753     }
754   };
755 
756   /// RAII object wrapping a full-expression or block scope, and handling
757   /// the ending of the lifetime of temporaries created within it.
758   template<bool IsFullExpression>
759   class ScopeRAII {
760     EvalInfo &Info;
761     unsigned OldStackSize;
762   public:
763     ScopeRAII(EvalInfo &Info)
764         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
765     ~ScopeRAII() {
766       // Body moved to a static method to encourage the compiler to inline away
767       // instances of this class.
768       cleanup(Info, OldStackSize);
769     }
770   private:
771     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
772       unsigned NewEnd = OldStackSize;
773       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
774            I != N; ++I) {
775         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
776           // Full-expression cleanup of a lifetime-extended temporary: nothing
777           // to do, just move this cleanup to the right place in the stack.
778           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
779           ++NewEnd;
780         } else {
781           // End the lifetime of the object.
782           Info.CleanupStack[I].endLifetime();
783         }
784       }
785       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
786                               Info.CleanupStack.end());
787     }
788   };
789   typedef ScopeRAII<false> BlockScopeRAII;
790   typedef ScopeRAII<true> FullExpressionRAII;
791 }
792 
793 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
794                                          CheckSubobjectKind CSK) {
795   if (Invalid)
796     return false;
797   if (isOnePastTheEnd()) {
798     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
799       << CSK;
800     setInvalid();
801     return false;
802   }
803   return true;
804 }
805 
806 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
807                                                     const Expr *E, uint64_t N) {
808   if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
809     Info.CCEDiag(E, diag::note_constexpr_array_index)
810       << static_cast<int>(N) << /*array*/ 0
811       << static_cast<unsigned>(MostDerivedArraySize);
812   else
813     Info.CCEDiag(E, diag::note_constexpr_array_index)
814       << static_cast<int>(N) << /*non-array*/ 1;
815   setInvalid();
816 }
817 
818 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
819                                const FunctionDecl *Callee, const LValue *This,
820                                APValue *Arguments)
821     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
822       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
823   Info.CurrentCall = this;
824   ++Info.CallStackDepth;
825 }
826 
827 CallStackFrame::~CallStackFrame() {
828   assert(Info.CurrentCall == this && "calls retired out of order");
829   --Info.CallStackDepth;
830   Info.CurrentCall = Caller;
831 }
832 
833 APValue &CallStackFrame::createTemporary(const void *Key,
834                                          bool IsLifetimeExtended) {
835   APValue &Result = Temporaries[Key];
836   assert(Result.isUninit() && "temporary created multiple times");
837   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
838   return Result;
839 }
840 
841 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
842 
843 void EvalInfo::addCallStack(unsigned Limit) {
844   // Determine which calls to skip, if any.
845   unsigned ActiveCalls = CallStackDepth - 1;
846   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
847   if (Limit && Limit < ActiveCalls) {
848     SkipStart = Limit / 2 + Limit % 2;
849     SkipEnd = ActiveCalls - Limit / 2;
850   }
851 
852   // Walk the call stack and add the diagnostics.
853   unsigned CallIdx = 0;
854   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
855        Frame = Frame->Caller, ++CallIdx) {
856     // Skip this call?
857     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
858       if (CallIdx == SkipStart) {
859         // Note that we're skipping calls.
860         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
861           << unsigned(ActiveCalls - Limit);
862       }
863       continue;
864     }
865 
866     SmallVector<char, 128> Buffer;
867     llvm::raw_svector_ostream Out(Buffer);
868     describeCall(Frame, Out);
869     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
870   }
871 }
872 
873 namespace {
874   struct ComplexValue {
875   private:
876     bool IsInt;
877 
878   public:
879     APSInt IntReal, IntImag;
880     APFloat FloatReal, FloatImag;
881 
882     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
883 
884     void makeComplexFloat() { IsInt = false; }
885     bool isComplexFloat() const { return !IsInt; }
886     APFloat &getComplexFloatReal() { return FloatReal; }
887     APFloat &getComplexFloatImag() { return FloatImag; }
888 
889     void makeComplexInt() { IsInt = true; }
890     bool isComplexInt() const { return IsInt; }
891     APSInt &getComplexIntReal() { return IntReal; }
892     APSInt &getComplexIntImag() { return IntImag; }
893 
894     void moveInto(APValue &v) const {
895       if (isComplexFloat())
896         v = APValue(FloatReal, FloatImag);
897       else
898         v = APValue(IntReal, IntImag);
899     }
900     void setFrom(const APValue &v) {
901       assert(v.isComplexFloat() || v.isComplexInt());
902       if (v.isComplexFloat()) {
903         makeComplexFloat();
904         FloatReal = v.getComplexFloatReal();
905         FloatImag = v.getComplexFloatImag();
906       } else {
907         makeComplexInt();
908         IntReal = v.getComplexIntReal();
909         IntImag = v.getComplexIntImag();
910       }
911     }
912   };
913 
914   struct LValue {
915     APValue::LValueBase Base;
916     CharUnits Offset;
917     unsigned CallIndex;
918     SubobjectDesignator Designator;
919 
920     const APValue::LValueBase getLValueBase() const { return Base; }
921     CharUnits &getLValueOffset() { return Offset; }
922     const CharUnits &getLValueOffset() const { return Offset; }
923     unsigned getLValueCallIndex() const { return CallIndex; }
924     SubobjectDesignator &getLValueDesignator() { return Designator; }
925     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
926 
927     void moveInto(APValue &V) const {
928       if (Designator.Invalid)
929         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
930       else
931         V = APValue(Base, Offset, Designator.Entries,
932                     Designator.IsOnePastTheEnd, CallIndex);
933     }
934     void setFrom(ASTContext &Ctx, const APValue &V) {
935       assert(V.isLValue());
936       Base = V.getLValueBase();
937       Offset = V.getLValueOffset();
938       CallIndex = V.getLValueCallIndex();
939       Designator = SubobjectDesignator(Ctx, V);
940     }
941 
942     void set(APValue::LValueBase B, unsigned I = 0) {
943       Base = B;
944       Offset = CharUnits::Zero();
945       CallIndex = I;
946       Designator = SubobjectDesignator(getType(B));
947     }
948 
949     // Check that this LValue is not based on a null pointer. If it is, produce
950     // a diagnostic and mark the designator as invalid.
951     bool checkNullPointer(EvalInfo &Info, const Expr *E,
952                           CheckSubobjectKind CSK) {
953       if (Designator.Invalid)
954         return false;
955       if (!Base) {
956         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
957           << CSK;
958         Designator.setInvalid();
959         return false;
960       }
961       return true;
962     }
963 
964     // Check this LValue refers to an object. If not, set the designator to be
965     // invalid and emit a diagnostic.
966     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
967       // Outside C++11, do not build a designator referring to a subobject of
968       // any object: we won't use such a designator for anything.
969       if (!Info.getLangOpts().CPlusPlus11)
970         Designator.setInvalid();
971       return checkNullPointer(Info, E, CSK) &&
972              Designator.checkSubobject(Info, E, CSK);
973     }
974 
975     void addDecl(EvalInfo &Info, const Expr *E,
976                  const Decl *D, bool Virtual = false) {
977       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
978         Designator.addDeclUnchecked(D, Virtual);
979     }
980     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
981       if (checkSubobject(Info, E, CSK_ArrayToPointer))
982         Designator.addArrayUnchecked(CAT);
983     }
984     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
985       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
986         Designator.addComplexUnchecked(EltTy, Imag);
987     }
988     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
989       if (checkNullPointer(Info, E, CSK_ArrayIndex))
990         Designator.adjustIndex(Info, E, N);
991     }
992   };
993 
994   struct MemberPtr {
995     MemberPtr() {}
996     explicit MemberPtr(const ValueDecl *Decl) :
997       DeclAndIsDerivedMember(Decl, false), Path() {}
998 
999     /// The member or (direct or indirect) field referred to by this member
1000     /// pointer, or 0 if this is a null member pointer.
1001     const ValueDecl *getDecl() const {
1002       return DeclAndIsDerivedMember.getPointer();
1003     }
1004     /// Is this actually a member of some type derived from the relevant class?
1005     bool isDerivedMember() const {
1006       return DeclAndIsDerivedMember.getInt();
1007     }
1008     /// Get the class which the declaration actually lives in.
1009     const CXXRecordDecl *getContainingRecord() const {
1010       return cast<CXXRecordDecl>(
1011           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1012     }
1013 
1014     void moveInto(APValue &V) const {
1015       V = APValue(getDecl(), isDerivedMember(), Path);
1016     }
1017     void setFrom(const APValue &V) {
1018       assert(V.isMemberPointer());
1019       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1020       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1021       Path.clear();
1022       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1023       Path.insert(Path.end(), P.begin(), P.end());
1024     }
1025 
1026     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1027     /// whether the member is a member of some class derived from the class type
1028     /// of the member pointer.
1029     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1030     /// Path - The path of base/derived classes from the member declaration's
1031     /// class (exclusive) to the class type of the member pointer (inclusive).
1032     SmallVector<const CXXRecordDecl*, 4> Path;
1033 
1034     /// Perform a cast towards the class of the Decl (either up or down the
1035     /// hierarchy).
1036     bool castBack(const CXXRecordDecl *Class) {
1037       assert(!Path.empty());
1038       const CXXRecordDecl *Expected;
1039       if (Path.size() >= 2)
1040         Expected = Path[Path.size() - 2];
1041       else
1042         Expected = getContainingRecord();
1043       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1044         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1045         // if B does not contain the original member and is not a base or
1046         // derived class of the class containing the original member, the result
1047         // of the cast is undefined.
1048         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1049         // (D::*). We consider that to be a language defect.
1050         return false;
1051       }
1052       Path.pop_back();
1053       return true;
1054     }
1055     /// Perform a base-to-derived member pointer cast.
1056     bool castToDerived(const CXXRecordDecl *Derived) {
1057       if (!getDecl())
1058         return true;
1059       if (!isDerivedMember()) {
1060         Path.push_back(Derived);
1061         return true;
1062       }
1063       if (!castBack(Derived))
1064         return false;
1065       if (Path.empty())
1066         DeclAndIsDerivedMember.setInt(false);
1067       return true;
1068     }
1069     /// Perform a derived-to-base member pointer cast.
1070     bool castToBase(const CXXRecordDecl *Base) {
1071       if (!getDecl())
1072         return true;
1073       if (Path.empty())
1074         DeclAndIsDerivedMember.setInt(true);
1075       if (isDerivedMember()) {
1076         Path.push_back(Base);
1077         return true;
1078       }
1079       return castBack(Base);
1080     }
1081   };
1082 
1083   /// Compare two member pointers, which are assumed to be of the same type.
1084   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1085     if (!LHS.getDecl() || !RHS.getDecl())
1086       return !LHS.getDecl() && !RHS.getDecl();
1087     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1088       return false;
1089     return LHS.Path == RHS.Path;
1090   }
1091 }
1092 
1093 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1094 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1095                             const LValue &This, const Expr *E,
1096                             bool AllowNonLiteralTypes = false);
1097 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1098 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1099 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1100                                   EvalInfo &Info);
1101 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1102 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
1103 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1104                                     EvalInfo &Info);
1105 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1106 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1107 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1108 
1109 //===----------------------------------------------------------------------===//
1110 // Misc utilities
1111 //===----------------------------------------------------------------------===//
1112 
1113 /// Produce a string describing the given constexpr call.
1114 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1115   unsigned ArgIndex = 0;
1116   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1117                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1118                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1119 
1120   if (!IsMemberCall)
1121     Out << *Frame->Callee << '(';
1122 
1123   if (Frame->This && IsMemberCall) {
1124     APValue Val;
1125     Frame->This->moveInto(Val);
1126     Val.printPretty(Out, Frame->Info.Ctx,
1127                     Frame->This->Designator.MostDerivedType);
1128     // FIXME: Add parens around Val if needed.
1129     Out << "->" << *Frame->Callee << '(';
1130     IsMemberCall = false;
1131   }
1132 
1133   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1134        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1135     if (ArgIndex > (unsigned)IsMemberCall)
1136       Out << ", ";
1137 
1138     const ParmVarDecl *Param = *I;
1139     const APValue &Arg = Frame->Arguments[ArgIndex];
1140     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1141 
1142     if (ArgIndex == 0 && IsMemberCall)
1143       Out << "->" << *Frame->Callee << '(';
1144   }
1145 
1146   Out << ')';
1147 }
1148 
1149 /// Evaluate an expression to see if it had side-effects, and discard its
1150 /// result.
1151 /// \return \c true if the caller should keep evaluating.
1152 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1153   APValue Scratch;
1154   if (!Evaluate(Scratch, Info, E))
1155     // We don't need the value, but we might have skipped a side effect here.
1156     return Info.noteSideEffect();
1157   return true;
1158 }
1159 
1160 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1161 /// return its existing value.
1162 static int64_t getExtValue(const APSInt &Value) {
1163   return Value.isSigned() ? Value.getSExtValue()
1164                           : static_cast<int64_t>(Value.getZExtValue());
1165 }
1166 
1167 /// Should this call expression be treated as a string literal?
1168 static bool IsStringLiteralCall(const CallExpr *E) {
1169   unsigned Builtin = E->getBuiltinCallee();
1170   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1171           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1172 }
1173 
1174 static bool IsGlobalLValue(APValue::LValueBase B) {
1175   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1176   // constant expression of pointer type that evaluates to...
1177 
1178   // ... a null pointer value, or a prvalue core constant expression of type
1179   // std::nullptr_t.
1180   if (!B) return true;
1181 
1182   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1183     // ... the address of an object with static storage duration,
1184     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1185       return VD->hasGlobalStorage();
1186     // ... the address of a function,
1187     return isa<FunctionDecl>(D);
1188   }
1189 
1190   const Expr *E = B.get<const Expr*>();
1191   switch (E->getStmtClass()) {
1192   default:
1193     return false;
1194   case Expr::CompoundLiteralExprClass: {
1195     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1196     return CLE->isFileScope() && CLE->isLValue();
1197   }
1198   case Expr::MaterializeTemporaryExprClass:
1199     // A materialized temporary might have been lifetime-extended to static
1200     // storage duration.
1201     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1202   // A string literal has static storage duration.
1203   case Expr::StringLiteralClass:
1204   case Expr::PredefinedExprClass:
1205   case Expr::ObjCStringLiteralClass:
1206   case Expr::ObjCEncodeExprClass:
1207   case Expr::CXXTypeidExprClass:
1208   case Expr::CXXUuidofExprClass:
1209     return true;
1210   case Expr::CallExprClass:
1211     return IsStringLiteralCall(cast<CallExpr>(E));
1212   // For GCC compatibility, &&label has static storage duration.
1213   case Expr::AddrLabelExprClass:
1214     return true;
1215   // A Block literal expression may be used as the initialization value for
1216   // Block variables at global or local static scope.
1217   case Expr::BlockExprClass:
1218     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1219   case Expr::ImplicitValueInitExprClass:
1220     // FIXME:
1221     // We can never form an lvalue with an implicit value initialization as its
1222     // base through expression evaluation, so these only appear in one case: the
1223     // implicit variable declaration we invent when checking whether a constexpr
1224     // constructor can produce a constant expression. We must assume that such
1225     // an expression might be a global lvalue.
1226     return true;
1227   }
1228 }
1229 
1230 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1231   assert(Base && "no location for a null lvalue");
1232   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1233   if (VD)
1234     Info.Note(VD->getLocation(), diag::note_declared_at);
1235   else
1236     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1237               diag::note_constexpr_temporary_here);
1238 }
1239 
1240 /// Check that this reference or pointer core constant expression is a valid
1241 /// value for an address or reference constant expression. Return true if we
1242 /// can fold this expression, whether or not it's a constant expression.
1243 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1244                                           QualType Type, const LValue &LVal) {
1245   bool IsReferenceType = Type->isReferenceType();
1246 
1247   APValue::LValueBase Base = LVal.getLValueBase();
1248   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1249 
1250   // Check that the object is a global. Note that the fake 'this' object we
1251   // manufacture when checking potential constant expressions is conservatively
1252   // assumed to be global here.
1253   if (!IsGlobalLValue(Base)) {
1254     if (Info.getLangOpts().CPlusPlus11) {
1255       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1256       Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1257         << IsReferenceType << !Designator.Entries.empty()
1258         << !!VD << VD;
1259       NoteLValueLocation(Info, Base);
1260     } else {
1261       Info.Diag(Loc);
1262     }
1263     // Don't allow references to temporaries to escape.
1264     return false;
1265   }
1266   assert((Info.checkingPotentialConstantExpression() ||
1267           LVal.getLValueCallIndex() == 0) &&
1268          "have call index for global lvalue");
1269 
1270   // Check if this is a thread-local variable.
1271   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1272     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1273       if (Var->getTLSKind())
1274         return false;
1275     }
1276   }
1277 
1278   // Allow address constant expressions to be past-the-end pointers. This is
1279   // an extension: the standard requires them to point to an object.
1280   if (!IsReferenceType)
1281     return true;
1282 
1283   // A reference constant expression must refer to an object.
1284   if (!Base) {
1285     // FIXME: diagnostic
1286     Info.CCEDiag(Loc);
1287     return true;
1288   }
1289 
1290   // Does this refer one past the end of some object?
1291   if (Designator.isOnePastTheEnd()) {
1292     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1293     Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1294       << !Designator.Entries.empty() << !!VD << VD;
1295     NoteLValueLocation(Info, Base);
1296   }
1297 
1298   return true;
1299 }
1300 
1301 /// Check that this core constant expression is of literal type, and if not,
1302 /// produce an appropriate diagnostic.
1303 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1304                              const LValue *This = 0) {
1305   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1306     return true;
1307 
1308   // C++1y: A constant initializer for an object o [...] may also invoke
1309   // constexpr constructors for o and its subobjects even if those objects
1310   // are of non-literal class types.
1311   if (Info.getLangOpts().CPlusPlus1y && This &&
1312       Info.EvaluatingDecl == This->getLValueBase())
1313     return true;
1314 
1315   // Prvalue constant expressions must be of literal types.
1316   if (Info.getLangOpts().CPlusPlus11)
1317     Info.Diag(E, diag::note_constexpr_nonliteral)
1318       << E->getType();
1319   else
1320     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1321   return false;
1322 }
1323 
1324 /// Check that this core constant expression value is a valid value for a
1325 /// constant expression. If not, report an appropriate diagnostic. Does not
1326 /// check that the expression is of literal type.
1327 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1328                                     QualType Type, const APValue &Value) {
1329   if (Value.isUninit()) {
1330     Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1331       << true << Type;
1332     return false;
1333   }
1334 
1335   // Core issue 1454: For a literal constant expression of array or class type,
1336   // each subobject of its value shall have been initialized by a constant
1337   // expression.
1338   if (Value.isArray()) {
1339     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1340     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1341       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1342                                    Value.getArrayInitializedElt(I)))
1343         return false;
1344     }
1345     if (!Value.hasArrayFiller())
1346       return true;
1347     return CheckConstantExpression(Info, DiagLoc, EltTy,
1348                                    Value.getArrayFiller());
1349   }
1350   if (Value.isUnion() && Value.getUnionField()) {
1351     return CheckConstantExpression(Info, DiagLoc,
1352                                    Value.getUnionField()->getType(),
1353                                    Value.getUnionValue());
1354   }
1355   if (Value.isStruct()) {
1356     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1357     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1358       unsigned BaseIndex = 0;
1359       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1360              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1361         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1362                                      Value.getStructBase(BaseIndex)))
1363           return false;
1364       }
1365     }
1366     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1367          I != E; ++I) {
1368       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1369                                    Value.getStructField(I->getFieldIndex())))
1370         return false;
1371     }
1372   }
1373 
1374   if (Value.isLValue()) {
1375     LValue LVal;
1376     LVal.setFrom(Info.Ctx, Value);
1377     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1378   }
1379 
1380   // Everything else is fine.
1381   return true;
1382 }
1383 
1384 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1385   return LVal.Base.dyn_cast<const ValueDecl*>();
1386 }
1387 
1388 static bool IsLiteralLValue(const LValue &Value) {
1389   if (Value.CallIndex)
1390     return false;
1391   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1392   return E && !isa<MaterializeTemporaryExpr>(E);
1393 }
1394 
1395 static bool IsWeakLValue(const LValue &Value) {
1396   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1397   return Decl && Decl->isWeak();
1398 }
1399 
1400 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1401   // A null base expression indicates a null pointer.  These are always
1402   // evaluatable, and they are false unless the offset is zero.
1403   if (!Value.getLValueBase()) {
1404     Result = !Value.getLValueOffset().isZero();
1405     return true;
1406   }
1407 
1408   // We have a non-null base.  These are generally known to be true, but if it's
1409   // a weak declaration it can be null at runtime.
1410   Result = true;
1411   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1412   return !Decl || !Decl->isWeak();
1413 }
1414 
1415 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1416   switch (Val.getKind()) {
1417   case APValue::Uninitialized:
1418     return false;
1419   case APValue::Int:
1420     Result = Val.getInt().getBoolValue();
1421     return true;
1422   case APValue::Float:
1423     Result = !Val.getFloat().isZero();
1424     return true;
1425   case APValue::ComplexInt:
1426     Result = Val.getComplexIntReal().getBoolValue() ||
1427              Val.getComplexIntImag().getBoolValue();
1428     return true;
1429   case APValue::ComplexFloat:
1430     Result = !Val.getComplexFloatReal().isZero() ||
1431              !Val.getComplexFloatImag().isZero();
1432     return true;
1433   case APValue::LValue:
1434     return EvalPointerValueAsBool(Val, Result);
1435   case APValue::MemberPointer:
1436     Result = Val.getMemberPointerDecl();
1437     return true;
1438   case APValue::Vector:
1439   case APValue::Array:
1440   case APValue::Struct:
1441   case APValue::Union:
1442   case APValue::AddrLabelDiff:
1443     return false;
1444   }
1445 
1446   llvm_unreachable("unknown APValue kind");
1447 }
1448 
1449 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1450                                        EvalInfo &Info) {
1451   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1452   APValue Val;
1453   if (!Evaluate(Val, Info, E))
1454     return false;
1455   return HandleConversionToBool(Val, Result);
1456 }
1457 
1458 template<typename T>
1459 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1460                            const T &SrcValue, QualType DestType) {
1461   Info.CCEDiag(E, diag::note_constexpr_overflow)
1462     << SrcValue << DestType;
1463 }
1464 
1465 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1466                                  QualType SrcType, const APFloat &Value,
1467                                  QualType DestType, APSInt &Result) {
1468   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1469   // Determine whether we are converting to unsigned or signed.
1470   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1471 
1472   Result = APSInt(DestWidth, !DestSigned);
1473   bool ignored;
1474   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1475       & APFloat::opInvalidOp)
1476     HandleOverflow(Info, E, Value, DestType);
1477   return true;
1478 }
1479 
1480 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1481                                    QualType SrcType, QualType DestType,
1482                                    APFloat &Result) {
1483   APFloat Value = Result;
1484   bool ignored;
1485   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1486                      APFloat::rmNearestTiesToEven, &ignored)
1487       & APFloat::opOverflow)
1488     HandleOverflow(Info, E, Value, DestType);
1489   return true;
1490 }
1491 
1492 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1493                                  QualType DestType, QualType SrcType,
1494                                  APSInt &Value) {
1495   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1496   APSInt Result = Value;
1497   // Figure out if this is a truncate, extend or noop cast.
1498   // If the input is signed, do a sign extend, noop, or truncate.
1499   Result = Result.extOrTrunc(DestWidth);
1500   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1501   return Result;
1502 }
1503 
1504 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1505                                  QualType SrcType, const APSInt &Value,
1506                                  QualType DestType, APFloat &Result) {
1507   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1508   if (Result.convertFromAPInt(Value, Value.isSigned(),
1509                               APFloat::rmNearestTiesToEven)
1510       & APFloat::opOverflow)
1511     HandleOverflow(Info, E, Value, DestType);
1512   return true;
1513 }
1514 
1515 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1516                                   APValue &Value, const FieldDecl *FD) {
1517   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1518 
1519   if (!Value.isInt()) {
1520     // Trying to store a pointer-cast-to-integer into a bitfield.
1521     // FIXME: In this case, we should provide the diagnostic for casting
1522     // a pointer to an integer.
1523     assert(Value.isLValue() && "integral value neither int nor lvalue?");
1524     Info.Diag(E);
1525     return false;
1526   }
1527 
1528   APSInt &Int = Value.getInt();
1529   unsigned OldBitWidth = Int.getBitWidth();
1530   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1531   if (NewBitWidth < OldBitWidth)
1532     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1533   return true;
1534 }
1535 
1536 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1537                                   llvm::APInt &Res) {
1538   APValue SVal;
1539   if (!Evaluate(SVal, Info, E))
1540     return false;
1541   if (SVal.isInt()) {
1542     Res = SVal.getInt();
1543     return true;
1544   }
1545   if (SVal.isFloat()) {
1546     Res = SVal.getFloat().bitcastToAPInt();
1547     return true;
1548   }
1549   if (SVal.isVector()) {
1550     QualType VecTy = E->getType();
1551     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1552     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1553     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1554     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1555     Res = llvm::APInt::getNullValue(VecSize);
1556     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1557       APValue &Elt = SVal.getVectorElt(i);
1558       llvm::APInt EltAsInt;
1559       if (Elt.isInt()) {
1560         EltAsInt = Elt.getInt();
1561       } else if (Elt.isFloat()) {
1562         EltAsInt = Elt.getFloat().bitcastToAPInt();
1563       } else {
1564         // Don't try to handle vectors of anything other than int or float
1565         // (not sure if it's possible to hit this case).
1566         Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1567         return false;
1568       }
1569       unsigned BaseEltSize = EltAsInt.getBitWidth();
1570       if (BigEndian)
1571         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1572       else
1573         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1574     }
1575     return true;
1576   }
1577   // Give up if the input isn't an int, float, or vector.  For example, we
1578   // reject "(v4i16)(intptr_t)&a".
1579   Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1580   return false;
1581 }
1582 
1583 /// Perform the given integer operation, which is known to need at most BitWidth
1584 /// bits, and check for overflow in the original type (if that type was not an
1585 /// unsigned type).
1586 template<typename Operation>
1587 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1588                                    const APSInt &LHS, const APSInt &RHS,
1589                                    unsigned BitWidth, Operation Op) {
1590   if (LHS.isUnsigned())
1591     return Op(LHS, RHS);
1592 
1593   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1594   APSInt Result = Value.trunc(LHS.getBitWidth());
1595   if (Result.extend(BitWidth) != Value) {
1596     if (Info.checkingForOverflow())
1597       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1598         diag::warn_integer_constant_overflow)
1599           << Result.toString(10) << E->getType();
1600     else
1601       HandleOverflow(Info, E, Value, E->getType());
1602   }
1603   return Result;
1604 }
1605 
1606 /// Perform the given binary integer operation.
1607 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1608                               BinaryOperatorKind Opcode, APSInt RHS,
1609                               APSInt &Result) {
1610   switch (Opcode) {
1611   default:
1612     Info.Diag(E);
1613     return false;
1614   case BO_Mul:
1615     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1616                                   std::multiplies<APSInt>());
1617     return true;
1618   case BO_Add:
1619     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1620                                   std::plus<APSInt>());
1621     return true;
1622   case BO_Sub:
1623     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1624                                   std::minus<APSInt>());
1625     return true;
1626   case BO_And: Result = LHS & RHS; return true;
1627   case BO_Xor: Result = LHS ^ RHS; return true;
1628   case BO_Or:  Result = LHS | RHS; return true;
1629   case BO_Div:
1630   case BO_Rem:
1631     if (RHS == 0) {
1632       Info.Diag(E, diag::note_expr_divide_by_zero);
1633       return false;
1634     }
1635     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1636     if (RHS.isNegative() && RHS.isAllOnesValue() &&
1637         LHS.isSigned() && LHS.isMinSignedValue())
1638       HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1639     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1640     return true;
1641   case BO_Shl: {
1642     if (Info.getLangOpts().OpenCL)
1643       // OpenCL 6.3j: shift values are effectively % word size of LHS.
1644       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1645                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1646                     RHS.isUnsigned());
1647     else if (RHS.isSigned() && RHS.isNegative()) {
1648       // During constant-folding, a negative shift is an opposite shift. Such
1649       // a shift is not a constant expression.
1650       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1651       RHS = -RHS;
1652       goto shift_right;
1653     }
1654   shift_left:
1655     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1656     // the shifted type.
1657     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1658     if (SA != RHS) {
1659       Info.CCEDiag(E, diag::note_constexpr_large_shift)
1660         << RHS << E->getType() << LHS.getBitWidth();
1661     } else if (LHS.isSigned()) {
1662       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1663       // operand, and must not overflow the corresponding unsigned type.
1664       if (LHS.isNegative())
1665         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1666       else if (LHS.countLeadingZeros() < SA)
1667         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1668     }
1669     Result = LHS << SA;
1670     return true;
1671   }
1672   case BO_Shr: {
1673     if (Info.getLangOpts().OpenCL)
1674       // OpenCL 6.3j: shift values are effectively % word size of LHS.
1675       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1676                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1677                     RHS.isUnsigned());
1678     else if (RHS.isSigned() && RHS.isNegative()) {
1679       // During constant-folding, a negative shift is an opposite shift. Such a
1680       // shift is not a constant expression.
1681       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1682       RHS = -RHS;
1683       goto shift_left;
1684     }
1685   shift_right:
1686     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1687     // shifted type.
1688     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1689     if (SA != RHS)
1690       Info.CCEDiag(E, diag::note_constexpr_large_shift)
1691         << RHS << E->getType() << LHS.getBitWidth();
1692     Result = LHS >> SA;
1693     return true;
1694   }
1695 
1696   case BO_LT: Result = LHS < RHS; return true;
1697   case BO_GT: Result = LHS > RHS; return true;
1698   case BO_LE: Result = LHS <= RHS; return true;
1699   case BO_GE: Result = LHS >= RHS; return true;
1700   case BO_EQ: Result = LHS == RHS; return true;
1701   case BO_NE: Result = LHS != RHS; return true;
1702   }
1703 }
1704 
1705 /// Perform the given binary floating-point operation, in-place, on LHS.
1706 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1707                                   APFloat &LHS, BinaryOperatorKind Opcode,
1708                                   const APFloat &RHS) {
1709   switch (Opcode) {
1710   default:
1711     Info.Diag(E);
1712     return false;
1713   case BO_Mul:
1714     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1715     break;
1716   case BO_Add:
1717     LHS.add(RHS, APFloat::rmNearestTiesToEven);
1718     break;
1719   case BO_Sub:
1720     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1721     break;
1722   case BO_Div:
1723     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1724     break;
1725   }
1726 
1727   if (LHS.isInfinity() || LHS.isNaN())
1728     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1729   return true;
1730 }
1731 
1732 /// Cast an lvalue referring to a base subobject to a derived class, by
1733 /// truncating the lvalue's path to the given length.
1734 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1735                                const RecordDecl *TruncatedType,
1736                                unsigned TruncatedElements) {
1737   SubobjectDesignator &D = Result.Designator;
1738 
1739   // Check we actually point to a derived class object.
1740   if (TruncatedElements == D.Entries.size())
1741     return true;
1742   assert(TruncatedElements >= D.MostDerivedPathLength &&
1743          "not casting to a derived class");
1744   if (!Result.checkSubobject(Info, E, CSK_Derived))
1745     return false;
1746 
1747   // Truncate the path to the subobject, and remove any derived-to-base offsets.
1748   const RecordDecl *RD = TruncatedType;
1749   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1750     if (RD->isInvalidDecl()) return false;
1751     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1752     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1753     if (isVirtualBaseClass(D.Entries[I]))
1754       Result.Offset -= Layout.getVBaseClassOffset(Base);
1755     else
1756       Result.Offset -= Layout.getBaseClassOffset(Base);
1757     RD = Base;
1758   }
1759   D.Entries.resize(TruncatedElements);
1760   return true;
1761 }
1762 
1763 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1764                                    const CXXRecordDecl *Derived,
1765                                    const CXXRecordDecl *Base,
1766                                    const ASTRecordLayout *RL = 0) {
1767   if (!RL) {
1768     if (Derived->isInvalidDecl()) return false;
1769     RL = &Info.Ctx.getASTRecordLayout(Derived);
1770   }
1771 
1772   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1773   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1774   return true;
1775 }
1776 
1777 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1778                              const CXXRecordDecl *DerivedDecl,
1779                              const CXXBaseSpecifier *Base) {
1780   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1781 
1782   if (!Base->isVirtual())
1783     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1784 
1785   SubobjectDesignator &D = Obj.Designator;
1786   if (D.Invalid)
1787     return false;
1788 
1789   // Extract most-derived object and corresponding type.
1790   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1791   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1792     return false;
1793 
1794   // Find the virtual base class.
1795   if (DerivedDecl->isInvalidDecl()) return false;
1796   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1797   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1798   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1799   return true;
1800 }
1801 
1802 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1803                                  QualType Type, LValue &Result) {
1804   for (CastExpr::path_const_iterator PathI = E->path_begin(),
1805                                      PathE = E->path_end();
1806        PathI != PathE; ++PathI) {
1807     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1808                           *PathI))
1809       return false;
1810     Type = (*PathI)->getType();
1811   }
1812   return true;
1813 }
1814 
1815 /// Update LVal to refer to the given field, which must be a member of the type
1816 /// currently described by LVal.
1817 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1818                                const FieldDecl *FD,
1819                                const ASTRecordLayout *RL = 0) {
1820   if (!RL) {
1821     if (FD->getParent()->isInvalidDecl()) return false;
1822     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1823   }
1824 
1825   unsigned I = FD->getFieldIndex();
1826   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1827   LVal.addDecl(Info, E, FD);
1828   return true;
1829 }
1830 
1831 /// Update LVal to refer to the given indirect field.
1832 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1833                                        LValue &LVal,
1834                                        const IndirectFieldDecl *IFD) {
1835   for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1836                                          CE = IFD->chain_end(); C != CE; ++C)
1837     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1838       return false;
1839   return true;
1840 }
1841 
1842 /// Get the size of the given type in char units.
1843 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1844                          QualType Type, CharUnits &Size) {
1845   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1846   // extension.
1847   if (Type->isVoidType() || Type->isFunctionType()) {
1848     Size = CharUnits::One();
1849     return true;
1850   }
1851 
1852   if (!Type->isConstantSizeType()) {
1853     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1854     // FIXME: Better diagnostic.
1855     Info.Diag(Loc);
1856     return false;
1857   }
1858 
1859   Size = Info.Ctx.getTypeSizeInChars(Type);
1860   return true;
1861 }
1862 
1863 /// Update a pointer value to model pointer arithmetic.
1864 /// \param Info - Information about the ongoing evaluation.
1865 /// \param E - The expression being evaluated, for diagnostic purposes.
1866 /// \param LVal - The pointer value to be updated.
1867 /// \param EltTy - The pointee type represented by LVal.
1868 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1869 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1870                                         LValue &LVal, QualType EltTy,
1871                                         int64_t Adjustment) {
1872   CharUnits SizeOfPointee;
1873   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1874     return false;
1875 
1876   // Compute the new offset in the appropriate width.
1877   LVal.Offset += Adjustment * SizeOfPointee;
1878   LVal.adjustIndex(Info, E, Adjustment);
1879   return true;
1880 }
1881 
1882 /// Update an lvalue to refer to a component of a complex number.
1883 /// \param Info - Information about the ongoing evaluation.
1884 /// \param LVal - The lvalue to be updated.
1885 /// \param EltTy - The complex number's component type.
1886 /// \param Imag - False for the real component, true for the imaginary.
1887 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1888                                        LValue &LVal, QualType EltTy,
1889                                        bool Imag) {
1890   if (Imag) {
1891     CharUnits SizeOfComponent;
1892     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1893       return false;
1894     LVal.Offset += SizeOfComponent;
1895   }
1896   LVal.addComplex(Info, E, EltTy, Imag);
1897   return true;
1898 }
1899 
1900 /// Try to evaluate the initializer for a variable declaration.
1901 ///
1902 /// \param Info   Information about the ongoing evaluation.
1903 /// \param E      An expression to be used when printing diagnostics.
1904 /// \param VD     The variable whose initializer should be obtained.
1905 /// \param Frame  The frame in which the variable was created. Must be null
1906 ///               if this variable is not local to the evaluation.
1907 /// \param Result Filled in with a pointer to the value of the variable.
1908 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1909                                 const VarDecl *VD, CallStackFrame *Frame,
1910                                 APValue *&Result) {
1911   // If this is a parameter to an active constexpr function call, perform
1912   // argument substitution.
1913   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1914     // Assume arguments of a potential constant expression are unknown
1915     // constant expressions.
1916     if (Info.checkingPotentialConstantExpression())
1917       return false;
1918     if (!Frame || !Frame->Arguments) {
1919       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1920       return false;
1921     }
1922     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1923     return true;
1924   }
1925 
1926   // If this is a local variable, dig out its value.
1927   if (Frame) {
1928     Result = Frame->getTemporary(VD);
1929     assert(Result && "missing value for local variable");
1930     return true;
1931   }
1932 
1933   // Dig out the initializer, and use the declaration which it's attached to.
1934   const Expr *Init = VD->getAnyInitializer(VD);
1935   if (!Init || Init->isValueDependent()) {
1936     // If we're checking a potential constant expression, the variable could be
1937     // initialized later.
1938     if (!Info.checkingPotentialConstantExpression())
1939       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1940     return false;
1941   }
1942 
1943   // If we're currently evaluating the initializer of this declaration, use that
1944   // in-flight value.
1945   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1946     Result = Info.EvaluatingDeclValue;
1947     return true;
1948   }
1949 
1950   // Never evaluate the initializer of a weak variable. We can't be sure that
1951   // this is the definition which will be used.
1952   if (VD->isWeak()) {
1953     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1954     return false;
1955   }
1956 
1957   // Check that we can fold the initializer. In C++, we will have already done
1958   // this in the cases where it matters for conformance.
1959   SmallVector<PartialDiagnosticAt, 8> Notes;
1960   if (!VD->evaluateValue(Notes)) {
1961     Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1962               Notes.size() + 1) << VD;
1963     Info.Note(VD->getLocation(), diag::note_declared_at);
1964     Info.addNotes(Notes);
1965     return false;
1966   } else if (!VD->checkInitIsICE()) {
1967     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1968                  Notes.size() + 1) << VD;
1969     Info.Note(VD->getLocation(), diag::note_declared_at);
1970     Info.addNotes(Notes);
1971   }
1972 
1973   Result = VD->getEvaluatedValue();
1974   return true;
1975 }
1976 
1977 static bool IsConstNonVolatile(QualType T) {
1978   Qualifiers Quals = T.getQualifiers();
1979   return Quals.hasConst() && !Quals.hasVolatile();
1980 }
1981 
1982 /// Get the base index of the given base class within an APValue representing
1983 /// the given derived class.
1984 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1985                              const CXXRecordDecl *Base) {
1986   Base = Base->getCanonicalDecl();
1987   unsigned Index = 0;
1988   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1989          E = Derived->bases_end(); I != E; ++I, ++Index) {
1990     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1991       return Index;
1992   }
1993 
1994   llvm_unreachable("base class missing from derived class's bases list");
1995 }
1996 
1997 /// Extract the value of a character from a string literal.
1998 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1999                                             uint64_t Index) {
2000   // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2001   const StringLiteral *S = cast<StringLiteral>(Lit);
2002   const ConstantArrayType *CAT =
2003       Info.Ctx.getAsConstantArrayType(S->getType());
2004   assert(CAT && "string literal isn't an array");
2005   QualType CharType = CAT->getElementType();
2006   assert(CharType->isIntegerType() && "unexpected character type");
2007 
2008   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2009                CharType->isUnsignedIntegerType());
2010   if (Index < S->getLength())
2011     Value = S->getCodeUnit(Index);
2012   return Value;
2013 }
2014 
2015 // Expand a string literal into an array of characters.
2016 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2017                                 APValue &Result) {
2018   const StringLiteral *S = cast<StringLiteral>(Lit);
2019   const ConstantArrayType *CAT =
2020       Info.Ctx.getAsConstantArrayType(S->getType());
2021   assert(CAT && "string literal isn't an array");
2022   QualType CharType = CAT->getElementType();
2023   assert(CharType->isIntegerType() && "unexpected character type");
2024 
2025   unsigned Elts = CAT->getSize().getZExtValue();
2026   Result = APValue(APValue::UninitArray(),
2027                    std::min(S->getLength(), Elts), Elts);
2028   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2029                CharType->isUnsignedIntegerType());
2030   if (Result.hasArrayFiller())
2031     Result.getArrayFiller() = APValue(Value);
2032   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2033     Value = S->getCodeUnit(I);
2034     Result.getArrayInitializedElt(I) = APValue(Value);
2035   }
2036 }
2037 
2038 // Expand an array so that it has more than Index filled elements.
2039 static void expandArray(APValue &Array, unsigned Index) {
2040   unsigned Size = Array.getArraySize();
2041   assert(Index < Size);
2042 
2043   // Always at least double the number of elements for which we store a value.
2044   unsigned OldElts = Array.getArrayInitializedElts();
2045   unsigned NewElts = std::max(Index+1, OldElts * 2);
2046   NewElts = std::min(Size, std::max(NewElts, 8u));
2047 
2048   // Copy the data across.
2049   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2050   for (unsigned I = 0; I != OldElts; ++I)
2051     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2052   for (unsigned I = OldElts; I != NewElts; ++I)
2053     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2054   if (NewValue.hasArrayFiller())
2055     NewValue.getArrayFiller() = Array.getArrayFiller();
2056   Array.swap(NewValue);
2057 }
2058 
2059 /// Kinds of access we can perform on an object, for diagnostics.
2060 enum AccessKinds {
2061   AK_Read,
2062   AK_Assign,
2063   AK_Increment,
2064   AK_Decrement
2065 };
2066 
2067 /// A handle to a complete object (an object that is not a subobject of
2068 /// another object).
2069 struct CompleteObject {
2070   /// The value of the complete object.
2071   APValue *Value;
2072   /// The type of the complete object.
2073   QualType Type;
2074 
2075   CompleteObject() : Value(0) {}
2076   CompleteObject(APValue *Value, QualType Type)
2077       : Value(Value), Type(Type) {
2078     assert(Value && "missing value for complete object");
2079   }
2080 
2081   LLVM_EXPLICIT operator bool() const { return Value; }
2082 };
2083 
2084 /// Find the designated sub-object of an rvalue.
2085 template<typename SubobjectHandler>
2086 typename SubobjectHandler::result_type
2087 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2088               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2089   if (Sub.Invalid)
2090     // A diagnostic will have already been produced.
2091     return handler.failed();
2092   if (Sub.isOnePastTheEnd()) {
2093     if (Info.getLangOpts().CPlusPlus11)
2094       Info.Diag(E, diag::note_constexpr_access_past_end)
2095         << handler.AccessKind;
2096     else
2097       Info.Diag(E);
2098     return handler.failed();
2099   }
2100 
2101   APValue *O = Obj.Value;
2102   QualType ObjType = Obj.Type;
2103   const FieldDecl *LastField = 0;
2104 
2105   // Walk the designator's path to find the subobject.
2106   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2107     if (O->isUninit()) {
2108       if (!Info.checkingPotentialConstantExpression())
2109         Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2110       return handler.failed();
2111     }
2112 
2113     if (I == N) {
2114       if (!handler.found(*O, ObjType))
2115         return false;
2116 
2117       // If we modified a bit-field, truncate it to the right width.
2118       if (handler.AccessKind != AK_Read &&
2119           LastField && LastField->isBitField() &&
2120           !truncateBitfieldValue(Info, E, *O, LastField))
2121         return false;
2122 
2123       return true;
2124     }
2125 
2126     LastField = 0;
2127     if (ObjType->isArrayType()) {
2128       // Next subobject is an array element.
2129       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2130       assert(CAT && "vla in literal type?");
2131       uint64_t Index = Sub.Entries[I].ArrayIndex;
2132       if (CAT->getSize().ule(Index)) {
2133         // Note, it should not be possible to form a pointer with a valid
2134         // designator which points more than one past the end of the array.
2135         if (Info.getLangOpts().CPlusPlus11)
2136           Info.Diag(E, diag::note_constexpr_access_past_end)
2137             << handler.AccessKind;
2138         else
2139           Info.Diag(E);
2140         return handler.failed();
2141       }
2142 
2143       ObjType = CAT->getElementType();
2144 
2145       // An array object is represented as either an Array APValue or as an
2146       // LValue which refers to a string literal.
2147       if (O->isLValue()) {
2148         assert(I == N - 1 && "extracting subobject of character?");
2149         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2150         if (handler.AccessKind != AK_Read)
2151           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2152                               *O);
2153         else
2154           return handler.foundString(*O, ObjType, Index);
2155       }
2156 
2157       if (O->getArrayInitializedElts() > Index)
2158         O = &O->getArrayInitializedElt(Index);
2159       else if (handler.AccessKind != AK_Read) {
2160         expandArray(*O, Index);
2161         O = &O->getArrayInitializedElt(Index);
2162       } else
2163         O = &O->getArrayFiller();
2164     } else if (ObjType->isAnyComplexType()) {
2165       // Next subobject is a complex number.
2166       uint64_t Index = Sub.Entries[I].ArrayIndex;
2167       if (Index > 1) {
2168         if (Info.getLangOpts().CPlusPlus11)
2169           Info.Diag(E, diag::note_constexpr_access_past_end)
2170             << handler.AccessKind;
2171         else
2172           Info.Diag(E);
2173         return handler.failed();
2174       }
2175 
2176       bool WasConstQualified = ObjType.isConstQualified();
2177       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2178       if (WasConstQualified)
2179         ObjType.addConst();
2180 
2181       assert(I == N - 1 && "extracting subobject of scalar?");
2182       if (O->isComplexInt()) {
2183         return handler.found(Index ? O->getComplexIntImag()
2184                                    : O->getComplexIntReal(), ObjType);
2185       } else {
2186         assert(O->isComplexFloat());
2187         return handler.found(Index ? O->getComplexFloatImag()
2188                                    : O->getComplexFloatReal(), ObjType);
2189       }
2190     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2191       if (Field->isMutable() && handler.AccessKind == AK_Read) {
2192         Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2193           << Field;
2194         Info.Note(Field->getLocation(), diag::note_declared_at);
2195         return handler.failed();
2196       }
2197 
2198       // Next subobject is a class, struct or union field.
2199       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2200       if (RD->isUnion()) {
2201         const FieldDecl *UnionField = O->getUnionField();
2202         if (!UnionField ||
2203             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2204           Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2205             << handler.AccessKind << Field << !UnionField << UnionField;
2206           return handler.failed();
2207         }
2208         O = &O->getUnionValue();
2209       } else
2210         O = &O->getStructField(Field->getFieldIndex());
2211 
2212       bool WasConstQualified = ObjType.isConstQualified();
2213       ObjType = Field->getType();
2214       if (WasConstQualified && !Field->isMutable())
2215         ObjType.addConst();
2216 
2217       if (ObjType.isVolatileQualified()) {
2218         if (Info.getLangOpts().CPlusPlus) {
2219           // FIXME: Include a description of the path to the volatile subobject.
2220           Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2221             << handler.AccessKind << 2 << Field;
2222           Info.Note(Field->getLocation(), diag::note_declared_at);
2223         } else {
2224           Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2225         }
2226         return handler.failed();
2227       }
2228 
2229       LastField = Field;
2230     } else {
2231       // Next subobject is a base class.
2232       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2233       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2234       O = &O->getStructBase(getBaseIndex(Derived, Base));
2235 
2236       bool WasConstQualified = ObjType.isConstQualified();
2237       ObjType = Info.Ctx.getRecordType(Base);
2238       if (WasConstQualified)
2239         ObjType.addConst();
2240     }
2241   }
2242 }
2243 
2244 namespace {
2245 struct ExtractSubobjectHandler {
2246   EvalInfo &Info;
2247   APValue &Result;
2248 
2249   static const AccessKinds AccessKind = AK_Read;
2250 
2251   typedef bool result_type;
2252   bool failed() { return false; }
2253   bool found(APValue &Subobj, QualType SubobjType) {
2254     Result = Subobj;
2255     return true;
2256   }
2257   bool found(APSInt &Value, QualType SubobjType) {
2258     Result = APValue(Value);
2259     return true;
2260   }
2261   bool found(APFloat &Value, QualType SubobjType) {
2262     Result = APValue(Value);
2263     return true;
2264   }
2265   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2266     Result = APValue(extractStringLiteralCharacter(
2267         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2268     return true;
2269   }
2270 };
2271 } // end anonymous namespace
2272 
2273 const AccessKinds ExtractSubobjectHandler::AccessKind;
2274 
2275 /// Extract the designated sub-object of an rvalue.
2276 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2277                              const CompleteObject &Obj,
2278                              const SubobjectDesignator &Sub,
2279                              APValue &Result) {
2280   ExtractSubobjectHandler Handler = { Info, Result };
2281   return findSubobject(Info, E, Obj, Sub, Handler);
2282 }
2283 
2284 namespace {
2285 struct ModifySubobjectHandler {
2286   EvalInfo &Info;
2287   APValue &NewVal;
2288   const Expr *E;
2289 
2290   typedef bool result_type;
2291   static const AccessKinds AccessKind = AK_Assign;
2292 
2293   bool checkConst(QualType QT) {
2294     // Assigning to a const object has undefined behavior.
2295     if (QT.isConstQualified()) {
2296       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2297       return false;
2298     }
2299     return true;
2300   }
2301 
2302   bool failed() { return false; }
2303   bool found(APValue &Subobj, QualType SubobjType) {
2304     if (!checkConst(SubobjType))
2305       return false;
2306     // We've been given ownership of NewVal, so just swap it in.
2307     Subobj.swap(NewVal);
2308     return true;
2309   }
2310   bool found(APSInt &Value, QualType SubobjType) {
2311     if (!checkConst(SubobjType))
2312       return false;
2313     if (!NewVal.isInt()) {
2314       // Maybe trying to write a cast pointer value into a complex?
2315       Info.Diag(E);
2316       return false;
2317     }
2318     Value = NewVal.getInt();
2319     return true;
2320   }
2321   bool found(APFloat &Value, QualType SubobjType) {
2322     if (!checkConst(SubobjType))
2323       return false;
2324     Value = NewVal.getFloat();
2325     return true;
2326   }
2327   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2328     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2329   }
2330 };
2331 } // end anonymous namespace
2332 
2333 const AccessKinds ModifySubobjectHandler::AccessKind;
2334 
2335 /// Update the designated sub-object of an rvalue to the given value.
2336 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2337                             const CompleteObject &Obj,
2338                             const SubobjectDesignator &Sub,
2339                             APValue &NewVal) {
2340   ModifySubobjectHandler Handler = { Info, NewVal, E };
2341   return findSubobject(Info, E, Obj, Sub, Handler);
2342 }
2343 
2344 /// Find the position where two subobject designators diverge, or equivalently
2345 /// the length of the common initial subsequence.
2346 static unsigned FindDesignatorMismatch(QualType ObjType,
2347                                        const SubobjectDesignator &A,
2348                                        const SubobjectDesignator &B,
2349                                        bool &WasArrayIndex) {
2350   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2351   for (/**/; I != N; ++I) {
2352     if (!ObjType.isNull() &&
2353         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2354       // Next subobject is an array element.
2355       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2356         WasArrayIndex = true;
2357         return I;
2358       }
2359       if (ObjType->isAnyComplexType())
2360         ObjType = ObjType->castAs<ComplexType>()->getElementType();
2361       else
2362         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2363     } else {
2364       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2365         WasArrayIndex = false;
2366         return I;
2367       }
2368       if (const FieldDecl *FD = getAsField(A.Entries[I]))
2369         // Next subobject is a field.
2370         ObjType = FD->getType();
2371       else
2372         // Next subobject is a base class.
2373         ObjType = QualType();
2374     }
2375   }
2376   WasArrayIndex = false;
2377   return I;
2378 }
2379 
2380 /// Determine whether the given subobject designators refer to elements of the
2381 /// same array object.
2382 static bool AreElementsOfSameArray(QualType ObjType,
2383                                    const SubobjectDesignator &A,
2384                                    const SubobjectDesignator &B) {
2385   if (A.Entries.size() != B.Entries.size())
2386     return false;
2387 
2388   bool IsArray = A.MostDerivedArraySize != 0;
2389   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2390     // A is a subobject of the array element.
2391     return false;
2392 
2393   // If A (and B) designates an array element, the last entry will be the array
2394   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2395   // of length 1' case, and the entire path must match.
2396   bool WasArrayIndex;
2397   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2398   return CommonLength >= A.Entries.size() - IsArray;
2399 }
2400 
2401 /// Find the complete object to which an LValue refers.
2402 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2403                                   const LValue &LVal, QualType LValType) {
2404   if (!LVal.Base) {
2405     Info.Diag(E, diag::note_constexpr_access_null) << AK;
2406     return CompleteObject();
2407   }
2408 
2409   CallStackFrame *Frame = 0;
2410   if (LVal.CallIndex) {
2411     Frame = Info.getCallFrame(LVal.CallIndex);
2412     if (!Frame) {
2413       Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2414         << AK << LVal.Base.is<const ValueDecl*>();
2415       NoteLValueLocation(Info, LVal.Base);
2416       return CompleteObject();
2417     }
2418   }
2419 
2420   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2421   // is not a constant expression (even if the object is non-volatile). We also
2422   // apply this rule to C++98, in order to conform to the expected 'volatile'
2423   // semantics.
2424   if (LValType.isVolatileQualified()) {
2425     if (Info.getLangOpts().CPlusPlus)
2426       Info.Diag(E, diag::note_constexpr_access_volatile_type)
2427         << AK << LValType;
2428     else
2429       Info.Diag(E);
2430     return CompleteObject();
2431   }
2432 
2433   // Compute value storage location and type of base object.
2434   APValue *BaseVal = 0;
2435   QualType BaseType = getType(LVal.Base);
2436 
2437   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2438     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2439     // In C++11, constexpr, non-volatile variables initialized with constant
2440     // expressions are constant expressions too. Inside constexpr functions,
2441     // parameters are constant expressions even if they're non-const.
2442     // In C++1y, objects local to a constant expression (those with a Frame) are
2443     // both readable and writable inside constant expressions.
2444     // In C, such things can also be folded, although they are not ICEs.
2445     const VarDecl *VD = dyn_cast<VarDecl>(D);
2446     if (VD) {
2447       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2448         VD = VDef;
2449     }
2450     if (!VD || VD->isInvalidDecl()) {
2451       Info.Diag(E);
2452       return CompleteObject();
2453     }
2454 
2455     // Accesses of volatile-qualified objects are not allowed.
2456     if (BaseType.isVolatileQualified()) {
2457       if (Info.getLangOpts().CPlusPlus) {
2458         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2459           << AK << 1 << VD;
2460         Info.Note(VD->getLocation(), diag::note_declared_at);
2461       } else {
2462         Info.Diag(E);
2463       }
2464       return CompleteObject();
2465     }
2466 
2467     // Unless we're looking at a local variable or argument in a constexpr call,
2468     // the variable we're reading must be const.
2469     if (!Frame) {
2470       if (Info.getLangOpts().CPlusPlus1y &&
2471           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2472         // OK, we can read and modify an object if we're in the process of
2473         // evaluating its initializer, because its lifetime began in this
2474         // evaluation.
2475       } else if (AK != AK_Read) {
2476         // All the remaining cases only permit reading.
2477         Info.Diag(E, diag::note_constexpr_modify_global);
2478         return CompleteObject();
2479       } else if (VD->isConstexpr()) {
2480         // OK, we can read this variable.
2481       } else if (BaseType->isIntegralOrEnumerationType()) {
2482         if (!BaseType.isConstQualified()) {
2483           if (Info.getLangOpts().CPlusPlus) {
2484             Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2485             Info.Note(VD->getLocation(), diag::note_declared_at);
2486           } else {
2487             Info.Diag(E);
2488           }
2489           return CompleteObject();
2490         }
2491       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2492         // We support folding of const floating-point types, in order to make
2493         // static const data members of such types (supported as an extension)
2494         // more useful.
2495         if (Info.getLangOpts().CPlusPlus11) {
2496           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2497           Info.Note(VD->getLocation(), diag::note_declared_at);
2498         } else {
2499           Info.CCEDiag(E);
2500         }
2501       } else {
2502         // FIXME: Allow folding of values of any literal type in all languages.
2503         if (Info.getLangOpts().CPlusPlus11) {
2504           Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2505           Info.Note(VD->getLocation(), diag::note_declared_at);
2506         } else {
2507           Info.Diag(E);
2508         }
2509         return CompleteObject();
2510       }
2511     }
2512 
2513     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2514       return CompleteObject();
2515   } else {
2516     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2517 
2518     if (!Frame) {
2519       if (const MaterializeTemporaryExpr *MTE =
2520               dyn_cast<MaterializeTemporaryExpr>(Base)) {
2521         assert(MTE->getStorageDuration() == SD_Static &&
2522                "should have a frame for a non-global materialized temporary");
2523 
2524         // Per C++1y [expr.const]p2:
2525         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2526         //   - a [...] glvalue of integral or enumeration type that refers to
2527         //     a non-volatile const object [...]
2528         //   [...]
2529         //   - a [...] glvalue of literal type that refers to a non-volatile
2530         //     object whose lifetime began within the evaluation of e.
2531         //
2532         // C++11 misses the 'began within the evaluation of e' check and
2533         // instead allows all temporaries, including things like:
2534         //   int &&r = 1;
2535         //   int x = ++r;
2536         //   constexpr int k = r;
2537         // Therefore we use the C++1y rules in C++11 too.
2538         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2539         const ValueDecl *ED = MTE->getExtendingDecl();
2540         if (!(BaseType.isConstQualified() &&
2541               BaseType->isIntegralOrEnumerationType()) &&
2542             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2543           Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2544           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2545           return CompleteObject();
2546         }
2547 
2548         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2549         assert(BaseVal && "got reference to unevaluated temporary");
2550       } else {
2551         Info.Diag(E);
2552         return CompleteObject();
2553       }
2554     } else {
2555       BaseVal = Frame->getTemporary(Base);
2556       assert(BaseVal && "missing value for temporary");
2557     }
2558 
2559     // Volatile temporary objects cannot be accessed in constant expressions.
2560     if (BaseType.isVolatileQualified()) {
2561       if (Info.getLangOpts().CPlusPlus) {
2562         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563           << AK << 0;
2564         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2565       } else {
2566         Info.Diag(E);
2567       }
2568       return CompleteObject();
2569     }
2570   }
2571 
2572   // During the construction of an object, it is not yet 'const'.
2573   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2574   // and this doesn't do quite the right thing for const subobjects of the
2575   // object under construction.
2576   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2577     BaseType = Info.Ctx.getCanonicalType(BaseType);
2578     BaseType.removeLocalConst();
2579   }
2580 
2581   // In C++1y, we can't safely access any mutable state when we might be
2582   // evaluating after an unmodeled side effect or an evaluation failure.
2583   //
2584   // FIXME: Not all local state is mutable. Allow local constant subobjects
2585   // to be read here (but take care with 'mutable' fields).
2586   if (Frame && Info.getLangOpts().CPlusPlus1y &&
2587       (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2588     return CompleteObject();
2589 
2590   return CompleteObject(BaseVal, BaseType);
2591 }
2592 
2593 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2594 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2595 /// glvalue referred to by an entity of reference type.
2596 ///
2597 /// \param Info - Information about the ongoing evaluation.
2598 /// \param Conv - The expression for which we are performing the conversion.
2599 ///               Used for diagnostics.
2600 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2601 ///               case of a non-class type).
2602 /// \param LVal - The glvalue on which we are attempting to perform this action.
2603 /// \param RVal - The produced value will be placed here.
2604 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2605                                            QualType Type,
2606                                            const LValue &LVal, APValue &RVal) {
2607   if (LVal.Designator.Invalid)
2608     return false;
2609 
2610   // Check for special cases where there is no existing APValue to look at.
2611   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2612   if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2613       !Type.isVolatileQualified()) {
2614     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2615       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2616       // initializer until now for such expressions. Such an expression can't be
2617       // an ICE in C, so this only matters for fold.
2618       assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2619       if (Type.isVolatileQualified()) {
2620         Info.Diag(Conv);
2621         return false;
2622       }
2623       APValue Lit;
2624       if (!Evaluate(Lit, Info, CLE->getInitializer()))
2625         return false;
2626       CompleteObject LitObj(&Lit, Base->getType());
2627       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2628     } else if (isa<StringLiteral>(Base)) {
2629       // We represent a string literal array as an lvalue pointing at the
2630       // corresponding expression, rather than building an array of chars.
2631       // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2632       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2633       CompleteObject StrObj(&Str, Base->getType());
2634       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2635     }
2636   }
2637 
2638   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2639   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2640 }
2641 
2642 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2643 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2644                              QualType LValType, APValue &Val) {
2645   if (LVal.Designator.Invalid)
2646     return false;
2647 
2648   if (!Info.getLangOpts().CPlusPlus1y) {
2649     Info.Diag(E);
2650     return false;
2651   }
2652 
2653   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2654   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2655 }
2656 
2657 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2658   return T->isSignedIntegerType() &&
2659          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2660 }
2661 
2662 namespace {
2663 struct CompoundAssignSubobjectHandler {
2664   EvalInfo &Info;
2665   const Expr *E;
2666   QualType PromotedLHSType;
2667   BinaryOperatorKind Opcode;
2668   const APValue &RHS;
2669 
2670   static const AccessKinds AccessKind = AK_Assign;
2671 
2672   typedef bool result_type;
2673 
2674   bool checkConst(QualType QT) {
2675     // Assigning to a const object has undefined behavior.
2676     if (QT.isConstQualified()) {
2677       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2678       return false;
2679     }
2680     return true;
2681   }
2682 
2683   bool failed() { return false; }
2684   bool found(APValue &Subobj, QualType SubobjType) {
2685     switch (Subobj.getKind()) {
2686     case APValue::Int:
2687       return found(Subobj.getInt(), SubobjType);
2688     case APValue::Float:
2689       return found(Subobj.getFloat(), SubobjType);
2690     case APValue::ComplexInt:
2691     case APValue::ComplexFloat:
2692       // FIXME: Implement complex compound assignment.
2693       Info.Diag(E);
2694       return false;
2695     case APValue::LValue:
2696       return foundPointer(Subobj, SubobjType);
2697     default:
2698       // FIXME: can this happen?
2699       Info.Diag(E);
2700       return false;
2701     }
2702   }
2703   bool found(APSInt &Value, QualType SubobjType) {
2704     if (!checkConst(SubobjType))
2705       return false;
2706 
2707     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2708       // We don't support compound assignment on integer-cast-to-pointer
2709       // values.
2710       Info.Diag(E);
2711       return false;
2712     }
2713 
2714     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2715                                     SubobjType, Value);
2716     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2717       return false;
2718     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2719     return true;
2720   }
2721   bool found(APFloat &Value, QualType SubobjType) {
2722     return checkConst(SubobjType) &&
2723            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2724                                   Value) &&
2725            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2726            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2727   }
2728   bool foundPointer(APValue &Subobj, QualType SubobjType) {
2729     if (!checkConst(SubobjType))
2730       return false;
2731 
2732     QualType PointeeType;
2733     if (const PointerType *PT = SubobjType->getAs<PointerType>())
2734       PointeeType = PT->getPointeeType();
2735 
2736     if (PointeeType.isNull() || !RHS.isInt() ||
2737         (Opcode != BO_Add && Opcode != BO_Sub)) {
2738       Info.Diag(E);
2739       return false;
2740     }
2741 
2742     int64_t Offset = getExtValue(RHS.getInt());
2743     if (Opcode == BO_Sub)
2744       Offset = -Offset;
2745 
2746     LValue LVal;
2747     LVal.setFrom(Info.Ctx, Subobj);
2748     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2749       return false;
2750     LVal.moveInto(Subobj);
2751     return true;
2752   }
2753   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2754     llvm_unreachable("shouldn't encounter string elements here");
2755   }
2756 };
2757 } // end anonymous namespace
2758 
2759 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2760 
2761 /// Perform a compound assignment of LVal <op>= RVal.
2762 static bool handleCompoundAssignment(
2763     EvalInfo &Info, const Expr *E,
2764     const LValue &LVal, QualType LValType, QualType PromotedLValType,
2765     BinaryOperatorKind Opcode, const APValue &RVal) {
2766   if (LVal.Designator.Invalid)
2767     return false;
2768 
2769   if (!Info.getLangOpts().CPlusPlus1y) {
2770     Info.Diag(E);
2771     return false;
2772   }
2773 
2774   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2775   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2776                                              RVal };
2777   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2778 }
2779 
2780 namespace {
2781 struct IncDecSubobjectHandler {
2782   EvalInfo &Info;
2783   const Expr *E;
2784   AccessKinds AccessKind;
2785   APValue *Old;
2786 
2787   typedef bool result_type;
2788 
2789   bool checkConst(QualType QT) {
2790     // Assigning to a const object has undefined behavior.
2791     if (QT.isConstQualified()) {
2792       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2793       return false;
2794     }
2795     return true;
2796   }
2797 
2798   bool failed() { return false; }
2799   bool found(APValue &Subobj, QualType SubobjType) {
2800     // Stash the old value. Also clear Old, so we don't clobber it later
2801     // if we're post-incrementing a complex.
2802     if (Old) {
2803       *Old = Subobj;
2804       Old = 0;
2805     }
2806 
2807     switch (Subobj.getKind()) {
2808     case APValue::Int:
2809       return found(Subobj.getInt(), SubobjType);
2810     case APValue::Float:
2811       return found(Subobj.getFloat(), SubobjType);
2812     case APValue::ComplexInt:
2813       return found(Subobj.getComplexIntReal(),
2814                    SubobjType->castAs<ComplexType>()->getElementType()
2815                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2816     case APValue::ComplexFloat:
2817       return found(Subobj.getComplexFloatReal(),
2818                    SubobjType->castAs<ComplexType>()->getElementType()
2819                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2820     case APValue::LValue:
2821       return foundPointer(Subobj, SubobjType);
2822     default:
2823       // FIXME: can this happen?
2824       Info.Diag(E);
2825       return false;
2826     }
2827   }
2828   bool found(APSInt &Value, QualType SubobjType) {
2829     if (!checkConst(SubobjType))
2830       return false;
2831 
2832     if (!SubobjType->isIntegerType()) {
2833       // We don't support increment / decrement on integer-cast-to-pointer
2834       // values.
2835       Info.Diag(E);
2836       return false;
2837     }
2838 
2839     if (Old) *Old = APValue(Value);
2840 
2841     // bool arithmetic promotes to int, and the conversion back to bool
2842     // doesn't reduce mod 2^n, so special-case it.
2843     if (SubobjType->isBooleanType()) {
2844       if (AccessKind == AK_Increment)
2845         Value = 1;
2846       else
2847         Value = !Value;
2848       return true;
2849     }
2850 
2851     bool WasNegative = Value.isNegative();
2852     if (AccessKind == AK_Increment) {
2853       ++Value;
2854 
2855       if (!WasNegative && Value.isNegative() &&
2856           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2857         APSInt ActualValue(Value, /*IsUnsigned*/true);
2858         HandleOverflow(Info, E, ActualValue, SubobjType);
2859       }
2860     } else {
2861       --Value;
2862 
2863       if (WasNegative && !Value.isNegative() &&
2864           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2865         unsigned BitWidth = Value.getBitWidth();
2866         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2867         ActualValue.setBit(BitWidth);
2868         HandleOverflow(Info, E, ActualValue, SubobjType);
2869       }
2870     }
2871     return true;
2872   }
2873   bool found(APFloat &Value, QualType SubobjType) {
2874     if (!checkConst(SubobjType))
2875       return false;
2876 
2877     if (Old) *Old = APValue(Value);
2878 
2879     APFloat One(Value.getSemantics(), 1);
2880     if (AccessKind == AK_Increment)
2881       Value.add(One, APFloat::rmNearestTiesToEven);
2882     else
2883       Value.subtract(One, APFloat::rmNearestTiesToEven);
2884     return true;
2885   }
2886   bool foundPointer(APValue &Subobj, QualType SubobjType) {
2887     if (!checkConst(SubobjType))
2888       return false;
2889 
2890     QualType PointeeType;
2891     if (const PointerType *PT = SubobjType->getAs<PointerType>())
2892       PointeeType = PT->getPointeeType();
2893     else {
2894       Info.Diag(E);
2895       return false;
2896     }
2897 
2898     LValue LVal;
2899     LVal.setFrom(Info.Ctx, Subobj);
2900     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2901                                      AccessKind == AK_Increment ? 1 : -1))
2902       return false;
2903     LVal.moveInto(Subobj);
2904     return true;
2905   }
2906   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2907     llvm_unreachable("shouldn't encounter string elements here");
2908   }
2909 };
2910 } // end anonymous namespace
2911 
2912 /// Perform an increment or decrement on LVal.
2913 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2914                          QualType LValType, bool IsIncrement, APValue *Old) {
2915   if (LVal.Designator.Invalid)
2916     return false;
2917 
2918   if (!Info.getLangOpts().CPlusPlus1y) {
2919     Info.Diag(E);
2920     return false;
2921   }
2922 
2923   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2924   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2925   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2926   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2927 }
2928 
2929 /// Build an lvalue for the object argument of a member function call.
2930 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2931                                    LValue &This) {
2932   if (Object->getType()->isPointerType())
2933     return EvaluatePointer(Object, This, Info);
2934 
2935   if (Object->isGLValue())
2936     return EvaluateLValue(Object, This, Info);
2937 
2938   if (Object->getType()->isLiteralType(Info.Ctx))
2939     return EvaluateTemporary(Object, This, Info);
2940 
2941   return false;
2942 }
2943 
2944 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
2945 /// lvalue referring to the result.
2946 ///
2947 /// \param Info - Information about the ongoing evaluation.
2948 /// \param LV - An lvalue referring to the base of the member pointer.
2949 /// \param RHS - The member pointer expression.
2950 /// \param IncludeMember - Specifies whether the member itself is included in
2951 ///        the resulting LValue subobject designator. This is not possible when
2952 ///        creating a bound member function.
2953 /// \return The field or method declaration to which the member pointer refers,
2954 ///         or 0 if evaluation fails.
2955 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2956                                                   QualType LVType,
2957                                                   LValue &LV,
2958                                                   const Expr *RHS,
2959                                                   bool IncludeMember = true) {
2960   MemberPtr MemPtr;
2961   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
2962     return 0;
2963 
2964   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2965   // member value, the behavior is undefined.
2966   if (!MemPtr.getDecl()) {
2967     // FIXME: Specific diagnostic.
2968     Info.Diag(RHS);
2969     return 0;
2970   }
2971 
2972   if (MemPtr.isDerivedMember()) {
2973     // This is a member of some derived class. Truncate LV appropriately.
2974     // The end of the derived-to-base path for the base object must match the
2975     // derived-to-base path for the member pointer.
2976     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
2977         LV.Designator.Entries.size()) {
2978       Info.Diag(RHS);
2979       return 0;
2980     }
2981     unsigned PathLengthToMember =
2982         LV.Designator.Entries.size() - MemPtr.Path.size();
2983     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2984       const CXXRecordDecl *LVDecl = getAsBaseClass(
2985           LV.Designator.Entries[PathLengthToMember + I]);
2986       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2987       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2988         Info.Diag(RHS);
2989         return 0;
2990       }
2991     }
2992 
2993     // Truncate the lvalue to the appropriate derived class.
2994     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
2995                             PathLengthToMember))
2996       return 0;
2997   } else if (!MemPtr.Path.empty()) {
2998     // Extend the LValue path with the member pointer's path.
2999     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3000                                   MemPtr.Path.size() + IncludeMember);
3001 
3002     // Walk down to the appropriate base class.
3003     if (const PointerType *PT = LVType->getAs<PointerType>())
3004       LVType = PT->getPointeeType();
3005     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3006     assert(RD && "member pointer access on non-class-type expression");
3007     // The first class in the path is that of the lvalue.
3008     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3009       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3010       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3011         return 0;
3012       RD = Base;
3013     }
3014     // Finally cast to the class containing the member.
3015     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3016                                 MemPtr.getContainingRecord()))
3017       return 0;
3018   }
3019 
3020   // Add the member. Note that we cannot build bound member functions here.
3021   if (IncludeMember) {
3022     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3023       if (!HandleLValueMember(Info, RHS, LV, FD))
3024         return 0;
3025     } else if (const IndirectFieldDecl *IFD =
3026                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3027       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3028         return 0;
3029     } else {
3030       llvm_unreachable("can't construct reference to bound member function");
3031     }
3032   }
3033 
3034   return MemPtr.getDecl();
3035 }
3036 
3037 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3038                                                   const BinaryOperator *BO,
3039                                                   LValue &LV,
3040                                                   bool IncludeMember = true) {
3041   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3042 
3043   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3044     if (Info.keepEvaluatingAfterFailure()) {
3045       MemberPtr MemPtr;
3046       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3047     }
3048     return 0;
3049   }
3050 
3051   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3052                                    BO->getRHS(), IncludeMember);
3053 }
3054 
3055 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3056 /// the provided lvalue, which currently refers to the base object.
3057 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3058                                     LValue &Result) {
3059   SubobjectDesignator &D = Result.Designator;
3060   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3061     return false;
3062 
3063   QualType TargetQT = E->getType();
3064   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3065     TargetQT = PT->getPointeeType();
3066 
3067   // Check this cast lands within the final derived-to-base subobject path.
3068   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3069     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3070       << D.MostDerivedType << TargetQT;
3071     return false;
3072   }
3073 
3074   // Check the type of the final cast. We don't need to check the path,
3075   // since a cast can only be formed if the path is unique.
3076   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3077   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3078   const CXXRecordDecl *FinalType;
3079   if (NewEntriesSize == D.MostDerivedPathLength)
3080     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3081   else
3082     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3083   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3084     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3085       << D.MostDerivedType << TargetQT;
3086     return false;
3087   }
3088 
3089   // Truncate the lvalue to the appropriate derived class.
3090   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3091 }
3092 
3093 namespace {
3094 enum EvalStmtResult {
3095   /// Evaluation failed.
3096   ESR_Failed,
3097   /// Hit a 'return' statement.
3098   ESR_Returned,
3099   /// Evaluation succeeded.
3100   ESR_Succeeded,
3101   /// Hit a 'continue' statement.
3102   ESR_Continue,
3103   /// Hit a 'break' statement.
3104   ESR_Break,
3105   /// Still scanning for 'case' or 'default' statement.
3106   ESR_CaseNotFound
3107 };
3108 }
3109 
3110 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3111   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3112     // We don't need to evaluate the initializer for a static local.
3113     if (!VD->hasLocalStorage())
3114       return true;
3115 
3116     LValue Result;
3117     Result.set(VD, Info.CurrentCall->Index);
3118     APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3119 
3120     const Expr *InitE = VD->getInit();
3121     if (!InitE) {
3122       Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3123         << false << VD->getType();
3124       Val = APValue();
3125       return false;
3126     }
3127 
3128     if (InitE->isValueDependent())
3129       return false;
3130 
3131     if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3132       // Wipe out any partially-computed value, to allow tracking that this
3133       // evaluation failed.
3134       Val = APValue();
3135       return false;
3136     }
3137   }
3138 
3139   return true;
3140 }
3141 
3142 /// Evaluate a condition (either a variable declaration or an expression).
3143 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3144                          const Expr *Cond, bool &Result) {
3145   FullExpressionRAII Scope(Info);
3146   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3147     return false;
3148   return EvaluateAsBooleanCondition(Cond, Result, Info);
3149 }
3150 
3151 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3152                                    const Stmt *S, const SwitchCase *SC = 0);
3153 
3154 /// Evaluate the body of a loop, and translate the result as appropriate.
3155 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3156                                        const Stmt *Body,
3157                                        const SwitchCase *Case = 0) {
3158   BlockScopeRAII Scope(Info);
3159   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3160   case ESR_Break:
3161     return ESR_Succeeded;
3162   case ESR_Succeeded:
3163   case ESR_Continue:
3164     return ESR_Continue;
3165   case ESR_Failed:
3166   case ESR_Returned:
3167   case ESR_CaseNotFound:
3168     return ESR;
3169   }
3170   llvm_unreachable("Invalid EvalStmtResult!");
3171 }
3172 
3173 /// Evaluate a switch statement.
3174 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3175                                      const SwitchStmt *SS) {
3176   BlockScopeRAII Scope(Info);
3177 
3178   // Evaluate the switch condition.
3179   APSInt Value;
3180   {
3181     FullExpressionRAII Scope(Info);
3182     if (SS->getConditionVariable() &&
3183         !EvaluateDecl(Info, SS->getConditionVariable()))
3184       return ESR_Failed;
3185     if (!EvaluateInteger(SS->getCond(), Value, Info))
3186       return ESR_Failed;
3187   }
3188 
3189   // Find the switch case corresponding to the value of the condition.
3190   // FIXME: Cache this lookup.
3191   const SwitchCase *Found = 0;
3192   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3193        SC = SC->getNextSwitchCase()) {
3194     if (isa<DefaultStmt>(SC)) {
3195       Found = SC;
3196       continue;
3197     }
3198 
3199     const CaseStmt *CS = cast<CaseStmt>(SC);
3200     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3201     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3202                               : LHS;
3203     if (LHS <= Value && Value <= RHS) {
3204       Found = SC;
3205       break;
3206     }
3207   }
3208 
3209   if (!Found)
3210     return ESR_Succeeded;
3211 
3212   // Search the switch body for the switch case and evaluate it from there.
3213   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3214   case ESR_Break:
3215     return ESR_Succeeded;
3216   case ESR_Succeeded:
3217   case ESR_Continue:
3218   case ESR_Failed:
3219   case ESR_Returned:
3220     return ESR;
3221   case ESR_CaseNotFound:
3222     // This can only happen if the switch case is nested within a statement
3223     // expression. We have no intention of supporting that.
3224     Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3225     return ESR_Failed;
3226   }
3227   llvm_unreachable("Invalid EvalStmtResult!");
3228 }
3229 
3230 // Evaluate a statement.
3231 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3232                                    const Stmt *S, const SwitchCase *Case) {
3233   if (!Info.nextStep(S))
3234     return ESR_Failed;
3235 
3236   // If we're hunting down a 'case' or 'default' label, recurse through
3237   // substatements until we hit the label.
3238   if (Case) {
3239     // FIXME: We don't start the lifetime of objects whose initialization we
3240     // jump over. However, such objects must be of class type with a trivial
3241     // default constructor that initialize all subobjects, so must be empty,
3242     // so this almost never matters.
3243     switch (S->getStmtClass()) {
3244     case Stmt::CompoundStmtClass:
3245       // FIXME: Precompute which substatement of a compound statement we
3246       // would jump to, and go straight there rather than performing a
3247       // linear scan each time.
3248     case Stmt::LabelStmtClass:
3249     case Stmt::AttributedStmtClass:
3250     case Stmt::DoStmtClass:
3251       break;
3252 
3253     case Stmt::CaseStmtClass:
3254     case Stmt::DefaultStmtClass:
3255       if (Case == S)
3256         Case = 0;
3257       break;
3258 
3259     case Stmt::IfStmtClass: {
3260       // FIXME: Precompute which side of an 'if' we would jump to, and go
3261       // straight there rather than scanning both sides.
3262       const IfStmt *IS = cast<IfStmt>(S);
3263 
3264       // Wrap the evaluation in a block scope, in case it's a DeclStmt
3265       // preceded by our switch label.
3266       BlockScopeRAII Scope(Info);
3267 
3268       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3269       if (ESR != ESR_CaseNotFound || !IS->getElse())
3270         return ESR;
3271       return EvaluateStmt(Result, Info, IS->getElse(), Case);
3272     }
3273 
3274     case Stmt::WhileStmtClass: {
3275       EvalStmtResult ESR =
3276           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3277       if (ESR != ESR_Continue)
3278         return ESR;
3279       break;
3280     }
3281 
3282     case Stmt::ForStmtClass: {
3283       const ForStmt *FS = cast<ForStmt>(S);
3284       EvalStmtResult ESR =
3285           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3286       if (ESR != ESR_Continue)
3287         return ESR;
3288       if (FS->getInc()) {
3289         FullExpressionRAII IncScope(Info);
3290         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3291           return ESR_Failed;
3292       }
3293       break;
3294     }
3295 
3296     case Stmt::DeclStmtClass:
3297       // FIXME: If the variable has initialization that can't be jumped over,
3298       // bail out of any immediately-surrounding compound-statement too.
3299     default:
3300       return ESR_CaseNotFound;
3301     }
3302   }
3303 
3304   switch (S->getStmtClass()) {
3305   default:
3306     if (const Expr *E = dyn_cast<Expr>(S)) {
3307       // Don't bother evaluating beyond an expression-statement which couldn't
3308       // be evaluated.
3309       FullExpressionRAII Scope(Info);
3310       if (!EvaluateIgnoredValue(Info, E))
3311         return ESR_Failed;
3312       return ESR_Succeeded;
3313     }
3314 
3315     Info.Diag(S->getLocStart());
3316     return ESR_Failed;
3317 
3318   case Stmt::NullStmtClass:
3319     return ESR_Succeeded;
3320 
3321   case Stmt::DeclStmtClass: {
3322     const DeclStmt *DS = cast<DeclStmt>(S);
3323     for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3324            DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3325       // Each declaration initialization is its own full-expression.
3326       // FIXME: This isn't quite right; if we're performing aggregate
3327       // initialization, each braced subexpression is its own full-expression.
3328       FullExpressionRAII Scope(Info);
3329       if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3330         return ESR_Failed;
3331     }
3332     return ESR_Succeeded;
3333   }
3334 
3335   case Stmt::ReturnStmtClass: {
3336     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3337     FullExpressionRAII Scope(Info);
3338     if (RetExpr && !Evaluate(Result, Info, RetExpr))
3339       return ESR_Failed;
3340     return ESR_Returned;
3341   }
3342 
3343   case Stmt::CompoundStmtClass: {
3344     BlockScopeRAII Scope(Info);
3345 
3346     const CompoundStmt *CS = cast<CompoundStmt>(S);
3347     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3348            BE = CS->body_end(); BI != BE; ++BI) {
3349       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3350       if (ESR == ESR_Succeeded)
3351         Case = 0;
3352       else if (ESR != ESR_CaseNotFound)
3353         return ESR;
3354     }
3355     return Case ? ESR_CaseNotFound : ESR_Succeeded;
3356   }
3357 
3358   case Stmt::IfStmtClass: {
3359     const IfStmt *IS = cast<IfStmt>(S);
3360 
3361     // Evaluate the condition, as either a var decl or as an expression.
3362     BlockScopeRAII Scope(Info);
3363     bool Cond;
3364     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3365       return ESR_Failed;
3366 
3367     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3368       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3369       if (ESR != ESR_Succeeded)
3370         return ESR;
3371     }
3372     return ESR_Succeeded;
3373   }
3374 
3375   case Stmt::WhileStmtClass: {
3376     const WhileStmt *WS = cast<WhileStmt>(S);
3377     while (true) {
3378       BlockScopeRAII Scope(Info);
3379       bool Continue;
3380       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3381                         Continue))
3382         return ESR_Failed;
3383       if (!Continue)
3384         break;
3385 
3386       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3387       if (ESR != ESR_Continue)
3388         return ESR;
3389     }
3390     return ESR_Succeeded;
3391   }
3392 
3393   case Stmt::DoStmtClass: {
3394     const DoStmt *DS = cast<DoStmt>(S);
3395     bool Continue;
3396     do {
3397       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3398       if (ESR != ESR_Continue)
3399         return ESR;
3400       Case = 0;
3401 
3402       FullExpressionRAII CondScope(Info);
3403       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3404         return ESR_Failed;
3405     } while (Continue);
3406     return ESR_Succeeded;
3407   }
3408 
3409   case Stmt::ForStmtClass: {
3410     const ForStmt *FS = cast<ForStmt>(S);
3411     BlockScopeRAII Scope(Info);
3412     if (FS->getInit()) {
3413       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3414       if (ESR != ESR_Succeeded)
3415         return ESR;
3416     }
3417     while (true) {
3418       BlockScopeRAII Scope(Info);
3419       bool Continue = true;
3420       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3421                                          FS->getCond(), Continue))
3422         return ESR_Failed;
3423       if (!Continue)
3424         break;
3425 
3426       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3427       if (ESR != ESR_Continue)
3428         return ESR;
3429 
3430       if (FS->getInc()) {
3431         FullExpressionRAII IncScope(Info);
3432         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3433           return ESR_Failed;
3434       }
3435     }
3436     return ESR_Succeeded;
3437   }
3438 
3439   case Stmt::CXXForRangeStmtClass: {
3440     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3441     BlockScopeRAII Scope(Info);
3442 
3443     // Initialize the __range variable.
3444     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3445     if (ESR != ESR_Succeeded)
3446       return ESR;
3447 
3448     // Create the __begin and __end iterators.
3449     ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3450     if (ESR != ESR_Succeeded)
3451       return ESR;
3452 
3453     while (true) {
3454       // Condition: __begin != __end.
3455       {
3456         bool Continue = true;
3457         FullExpressionRAII CondExpr(Info);
3458         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3459           return ESR_Failed;
3460         if (!Continue)
3461           break;
3462       }
3463 
3464       // User's variable declaration, initialized by *__begin.
3465       BlockScopeRAII InnerScope(Info);
3466       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3467       if (ESR != ESR_Succeeded)
3468         return ESR;
3469 
3470       // Loop body.
3471       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3472       if (ESR != ESR_Continue)
3473         return ESR;
3474 
3475       // Increment: ++__begin
3476       if (!EvaluateIgnoredValue(Info, FS->getInc()))
3477         return ESR_Failed;
3478     }
3479 
3480     return ESR_Succeeded;
3481   }
3482 
3483   case Stmt::SwitchStmtClass:
3484     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3485 
3486   case Stmt::ContinueStmtClass:
3487     return ESR_Continue;
3488 
3489   case Stmt::BreakStmtClass:
3490     return ESR_Break;
3491 
3492   case Stmt::LabelStmtClass:
3493     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3494 
3495   case Stmt::AttributedStmtClass:
3496     // As a general principle, C++11 attributes can be ignored without
3497     // any semantic impact.
3498     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3499                         Case);
3500 
3501   case Stmt::CaseStmtClass:
3502   case Stmt::DefaultStmtClass:
3503     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3504   }
3505 }
3506 
3507 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3508 /// default constructor. If so, we'll fold it whether or not it's marked as
3509 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3510 /// so we need special handling.
3511 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3512                                            const CXXConstructorDecl *CD,
3513                                            bool IsValueInitialization) {
3514   if (!CD->isTrivial() || !CD->isDefaultConstructor())
3515     return false;
3516 
3517   // Value-initialization does not call a trivial default constructor, so such a
3518   // call is a core constant expression whether or not the constructor is
3519   // constexpr.
3520   if (!CD->isConstexpr() && !IsValueInitialization) {
3521     if (Info.getLangOpts().CPlusPlus11) {
3522       // FIXME: If DiagDecl is an implicitly-declared special member function,
3523       // we should be much more explicit about why it's not constexpr.
3524       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3525         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3526       Info.Note(CD->getLocation(), diag::note_declared_at);
3527     } else {
3528       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3529     }
3530   }
3531   return true;
3532 }
3533 
3534 /// CheckConstexprFunction - Check that a function can be called in a constant
3535 /// expression.
3536 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3537                                    const FunctionDecl *Declaration,
3538                                    const FunctionDecl *Definition) {
3539   // Potential constant expressions can contain calls to declared, but not yet
3540   // defined, constexpr functions.
3541   if (Info.checkingPotentialConstantExpression() && !Definition &&
3542       Declaration->isConstexpr())
3543     return false;
3544 
3545   // Bail out with no diagnostic if the function declaration itself is invalid.
3546   // We will have produced a relevant diagnostic while parsing it.
3547   if (Declaration->isInvalidDecl())
3548     return false;
3549 
3550   // Can we evaluate this function call?
3551   if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3552     return true;
3553 
3554   if (Info.getLangOpts().CPlusPlus11) {
3555     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3556     // FIXME: If DiagDecl is an implicitly-declared special member function, we
3557     // should be much more explicit about why it's not constexpr.
3558     Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3559       << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3560       << DiagDecl;
3561     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3562   } else {
3563     Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3564   }
3565   return false;
3566 }
3567 
3568 namespace {
3569 typedef SmallVector<APValue, 8> ArgVector;
3570 }
3571 
3572 /// EvaluateArgs - Evaluate the arguments to a function call.
3573 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3574                          EvalInfo &Info) {
3575   bool Success = true;
3576   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3577        I != E; ++I) {
3578     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3579       // If we're checking for a potential constant expression, evaluate all
3580       // initializers even if some of them fail.
3581       if (!Info.keepEvaluatingAfterFailure())
3582         return false;
3583       Success = false;
3584     }
3585   }
3586   return Success;
3587 }
3588 
3589 /// Evaluate a function call.
3590 static bool HandleFunctionCall(SourceLocation CallLoc,
3591                                const FunctionDecl *Callee, const LValue *This,
3592                                ArrayRef<const Expr*> Args, const Stmt *Body,
3593                                EvalInfo &Info, APValue &Result) {
3594   ArgVector ArgValues(Args.size());
3595   if (!EvaluateArgs(Args, ArgValues, Info))
3596     return false;
3597 
3598   if (!Info.CheckCallLimit(CallLoc))
3599     return false;
3600 
3601   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3602 
3603   // For a trivial copy or move assignment, perform an APValue copy. This is
3604   // essential for unions, where the operations performed by the assignment
3605   // operator cannot be represented as statements.
3606   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3607   if (MD && MD->isDefaulted() && MD->isTrivial()) {
3608     assert(This &&
3609            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3610     LValue RHS;
3611     RHS.setFrom(Info.Ctx, ArgValues[0]);
3612     APValue RHSValue;
3613     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3614                                         RHS, RHSValue))
3615       return false;
3616     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3617                           RHSValue))
3618       return false;
3619     This->moveInto(Result);
3620     return true;
3621   }
3622 
3623   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3624   if (ESR == ESR_Succeeded) {
3625     if (Callee->getReturnType()->isVoidType())
3626       return true;
3627     Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3628   }
3629   return ESR == ESR_Returned;
3630 }
3631 
3632 /// Evaluate a constructor call.
3633 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3634                                   ArrayRef<const Expr*> Args,
3635                                   const CXXConstructorDecl *Definition,
3636                                   EvalInfo &Info, APValue &Result) {
3637   ArgVector ArgValues(Args.size());
3638   if (!EvaluateArgs(Args, ArgValues, Info))
3639     return false;
3640 
3641   if (!Info.CheckCallLimit(CallLoc))
3642     return false;
3643 
3644   const CXXRecordDecl *RD = Definition->getParent();
3645   if (RD->getNumVBases()) {
3646     Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3647     return false;
3648   }
3649 
3650   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3651 
3652   // If it's a delegating constructor, just delegate.
3653   if (Definition->isDelegatingConstructor()) {
3654     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3655     {
3656       FullExpressionRAII InitScope(Info);
3657       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3658         return false;
3659     }
3660     return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3661   }
3662 
3663   // For a trivial copy or move constructor, perform an APValue copy. This is
3664   // essential for unions, where the operations performed by the constructor
3665   // cannot be represented by ctor-initializers.
3666   if (Definition->isDefaulted() &&
3667       ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3668        (Definition->isMoveConstructor() && Definition->isTrivial()))) {
3669     LValue RHS;
3670     RHS.setFrom(Info.Ctx, ArgValues[0]);
3671     return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3672                                           RHS, Result);
3673   }
3674 
3675   // Reserve space for the struct members.
3676   if (!RD->isUnion() && Result.isUninit())
3677     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3678                      std::distance(RD->field_begin(), RD->field_end()));
3679 
3680   if (RD->isInvalidDecl()) return false;
3681   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3682 
3683   // A scope for temporaries lifetime-extended by reference members.
3684   BlockScopeRAII LifetimeExtendedScope(Info);
3685 
3686   bool Success = true;
3687   unsigned BasesSeen = 0;
3688 #ifndef NDEBUG
3689   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3690 #endif
3691   for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3692        E = Definition->init_end(); I != E; ++I) {
3693     LValue Subobject = This;
3694     APValue *Value = &Result;
3695 
3696     // Determine the subobject to initialize.
3697     FieldDecl *FD = 0;
3698     if ((*I)->isBaseInitializer()) {
3699       QualType BaseType((*I)->getBaseClass(), 0);
3700 #ifndef NDEBUG
3701       // Non-virtual base classes are initialized in the order in the class
3702       // definition. We have already checked for virtual base classes.
3703       assert(!BaseIt->isVirtual() && "virtual base for literal type");
3704       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3705              "base class initializers not in expected order");
3706       ++BaseIt;
3707 #endif
3708       if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3709                                   BaseType->getAsCXXRecordDecl(), &Layout))
3710         return false;
3711       Value = &Result.getStructBase(BasesSeen++);
3712     } else if ((FD = (*I)->getMember())) {
3713       if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3714         return false;
3715       if (RD->isUnion()) {
3716         Result = APValue(FD);
3717         Value = &Result.getUnionValue();
3718       } else {
3719         Value = &Result.getStructField(FD->getFieldIndex());
3720       }
3721     } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
3722       // Walk the indirect field decl's chain to find the object to initialize,
3723       // and make sure we've initialized every step along it.
3724       for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3725                                              CE = IFD->chain_end();
3726            C != CE; ++C) {
3727         FD = cast<FieldDecl>(*C);
3728         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3729         // Switch the union field if it differs. This happens if we had
3730         // preceding zero-initialization, and we're now initializing a union
3731         // subobject other than the first.
3732         // FIXME: In this case, the values of the other subobjects are
3733         // specified, since zero-initialization sets all padding bits to zero.
3734         if (Value->isUninit() ||
3735             (Value->isUnion() && Value->getUnionField() != FD)) {
3736           if (CD->isUnion())
3737             *Value = APValue(FD);
3738           else
3739             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3740                              std::distance(CD->field_begin(), CD->field_end()));
3741         }
3742         if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3743           return false;
3744         if (CD->isUnion())
3745           Value = &Value->getUnionValue();
3746         else
3747           Value = &Value->getStructField(FD->getFieldIndex());
3748       }
3749     } else {
3750       llvm_unreachable("unknown base initializer kind");
3751     }
3752 
3753     FullExpressionRAII InitScope(Info);
3754     if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3755         (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3756                                                           *Value, FD))) {
3757       // If we're checking for a potential constant expression, evaluate all
3758       // initializers even if some of them fail.
3759       if (!Info.keepEvaluatingAfterFailure())
3760         return false;
3761       Success = false;
3762     }
3763   }
3764 
3765   return Success &&
3766          EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3767 }
3768 
3769 //===----------------------------------------------------------------------===//
3770 // Generic Evaluation
3771 //===----------------------------------------------------------------------===//
3772 namespace {
3773 
3774 template <class Derived>
3775 class ExprEvaluatorBase
3776   : public ConstStmtVisitor<Derived, bool> {
3777 private:
3778   bool DerivedSuccess(const APValue &V, const Expr *E) {
3779     return static_cast<Derived*>(this)->Success(V, E);
3780   }
3781   bool DerivedZeroInitialization(const Expr *E) {
3782     return static_cast<Derived*>(this)->ZeroInitialization(E);
3783   }
3784 
3785   // Check whether a conditional operator with a non-constant condition is a
3786   // potential constant expression. If neither arm is a potential constant
3787   // expression, then the conditional operator is not either.
3788   template<typename ConditionalOperator>
3789   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3790     assert(Info.checkingPotentialConstantExpression());
3791 
3792     // Speculatively evaluate both arms.
3793     {
3794       SmallVector<PartialDiagnosticAt, 8> Diag;
3795       SpeculativeEvaluationRAII Speculate(Info, &Diag);
3796 
3797       StmtVisitorTy::Visit(E->getFalseExpr());
3798       if (Diag.empty())
3799         return;
3800 
3801       Diag.clear();
3802       StmtVisitorTy::Visit(E->getTrueExpr());
3803       if (Diag.empty())
3804         return;
3805     }
3806 
3807     Error(E, diag::note_constexpr_conditional_never_const);
3808   }
3809 
3810 
3811   template<typename ConditionalOperator>
3812   bool HandleConditionalOperator(const ConditionalOperator *E) {
3813     bool BoolResult;
3814     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3815       if (Info.checkingPotentialConstantExpression())
3816         CheckPotentialConstantConditional(E);
3817       return false;
3818     }
3819 
3820     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3821     return StmtVisitorTy::Visit(EvalExpr);
3822   }
3823 
3824 protected:
3825   EvalInfo &Info;
3826   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3827   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3828 
3829   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3830     return Info.CCEDiag(E, D);
3831   }
3832 
3833   bool ZeroInitialization(const Expr *E) { return Error(E); }
3834 
3835 public:
3836   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3837 
3838   EvalInfo &getEvalInfo() { return Info; }
3839 
3840   /// Report an evaluation error. This should only be called when an error is
3841   /// first discovered. When propagating an error, just return false.
3842   bool Error(const Expr *E, diag::kind D) {
3843     Info.Diag(E, D);
3844     return false;
3845   }
3846   bool Error(const Expr *E) {
3847     return Error(E, diag::note_invalid_subexpr_in_const_expr);
3848   }
3849 
3850   bool VisitStmt(const Stmt *) {
3851     llvm_unreachable("Expression evaluator should not be called on stmts");
3852   }
3853   bool VisitExpr(const Expr *E) {
3854     return Error(E);
3855   }
3856 
3857   bool VisitParenExpr(const ParenExpr *E)
3858     { return StmtVisitorTy::Visit(E->getSubExpr()); }
3859   bool VisitUnaryExtension(const UnaryOperator *E)
3860     { return StmtVisitorTy::Visit(E->getSubExpr()); }
3861   bool VisitUnaryPlus(const UnaryOperator *E)
3862     { return StmtVisitorTy::Visit(E->getSubExpr()); }
3863   bool VisitChooseExpr(const ChooseExpr *E)
3864     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3865   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3866     { return StmtVisitorTy::Visit(E->getResultExpr()); }
3867   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3868     { return StmtVisitorTy::Visit(E->getReplacement()); }
3869   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3870     { return StmtVisitorTy::Visit(E->getExpr()); }
3871   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3872     // The initializer may not have been parsed yet, or might be erroneous.
3873     if (!E->getExpr())
3874       return Error(E);
3875     return StmtVisitorTy::Visit(E->getExpr());
3876   }
3877   // We cannot create any objects for which cleanups are required, so there is
3878   // nothing to do here; all cleanups must come from unevaluated subexpressions.
3879   bool VisitExprWithCleanups(const ExprWithCleanups *E)
3880     { return StmtVisitorTy::Visit(E->getSubExpr()); }
3881 
3882   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3883     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3884     return static_cast<Derived*>(this)->VisitCastExpr(E);
3885   }
3886   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3887     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3888     return static_cast<Derived*>(this)->VisitCastExpr(E);
3889   }
3890 
3891   bool VisitBinaryOperator(const BinaryOperator *E) {
3892     switch (E->getOpcode()) {
3893     default:
3894       return Error(E);
3895 
3896     case BO_Comma:
3897       VisitIgnoredValue(E->getLHS());
3898       return StmtVisitorTy::Visit(E->getRHS());
3899 
3900     case BO_PtrMemD:
3901     case BO_PtrMemI: {
3902       LValue Obj;
3903       if (!HandleMemberPointerAccess(Info, E, Obj))
3904         return false;
3905       APValue Result;
3906       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
3907         return false;
3908       return DerivedSuccess(Result, E);
3909     }
3910     }
3911   }
3912 
3913   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
3914     // Evaluate and cache the common expression. We treat it as a temporary,
3915     // even though it's not quite the same thing.
3916     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
3917                   Info, E->getCommon()))
3918       return false;
3919 
3920     return HandleConditionalOperator(E);
3921   }
3922 
3923   bool VisitConditionalOperator(const ConditionalOperator *E) {
3924     bool IsBcpCall = false;
3925     // If the condition (ignoring parens) is a __builtin_constant_p call,
3926     // the result is a constant expression if it can be folded without
3927     // side-effects. This is an important GNU extension. See GCC PR38377
3928     // for discussion.
3929     if (const CallExpr *CallCE =
3930           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3931       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
3932         IsBcpCall = true;
3933 
3934     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3935     // constant expression; we can't check whether it's potentially foldable.
3936     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
3937       return false;
3938 
3939     FoldConstant Fold(Info, IsBcpCall);
3940     if (!HandleConditionalOperator(E)) {
3941       Fold.keepDiagnostics();
3942       return false;
3943     }
3944 
3945     return true;
3946   }
3947 
3948   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3949     if (APValue *Value = Info.CurrentCall->getTemporary(E))
3950       return DerivedSuccess(*Value, E);
3951 
3952     const Expr *Source = E->getSourceExpr();
3953     if (!Source)
3954       return Error(E);
3955     if (Source == E) { // sanity checking.
3956       assert(0 && "OpaqueValueExpr recursively refers to itself");
3957       return Error(E);
3958     }
3959     return StmtVisitorTy::Visit(Source);
3960   }
3961 
3962   bool VisitCallExpr(const CallExpr *E) {
3963     const Expr *Callee = E->getCallee()->IgnoreParens();
3964     QualType CalleeType = Callee->getType();
3965 
3966     const FunctionDecl *FD = 0;
3967     LValue *This = 0, ThisVal;
3968     ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
3969     bool HasQualifier = false;
3970 
3971     // Extract function decl and 'this' pointer from the callee.
3972     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
3973       const ValueDecl *Member = 0;
3974       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3975         // Explicit bound member calls, such as x.f() or p->g();
3976         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
3977           return false;
3978         Member = ME->getMemberDecl();
3979         This = &ThisVal;
3980         HasQualifier = ME->hasQualifier();
3981       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3982         // Indirect bound member calls ('.*' or '->*').
3983         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3984         if (!Member) return false;
3985         This = &ThisVal;
3986       } else
3987         return Error(Callee);
3988 
3989       FD = dyn_cast<FunctionDecl>(Member);
3990       if (!FD)
3991         return Error(Callee);
3992     } else if (CalleeType->isFunctionPointerType()) {
3993       LValue Call;
3994       if (!EvaluatePointer(Callee, Call, Info))
3995         return false;
3996 
3997       if (!Call.getLValueOffset().isZero())
3998         return Error(Callee);
3999       FD = dyn_cast_or_null<FunctionDecl>(
4000                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4001       if (!FD)
4002         return Error(Callee);
4003 
4004       // Overloaded operator calls to member functions are represented as normal
4005       // calls with '*this' as the first argument.
4006       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4007       if (MD && !MD->isStatic()) {
4008         // FIXME: When selecting an implicit conversion for an overloaded
4009         // operator delete, we sometimes try to evaluate calls to conversion
4010         // operators without a 'this' parameter!
4011         if (Args.empty())
4012           return Error(E);
4013 
4014         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4015           return false;
4016         This = &ThisVal;
4017         Args = Args.slice(1);
4018       }
4019 
4020       // Don't call function pointers which have been cast to some other type.
4021       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4022         return Error(E);
4023     } else
4024       return Error(E);
4025 
4026     if (This && !This->checkSubobject(Info, E, CSK_This))
4027       return false;
4028 
4029     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4030     // calls to such functions in constant expressions.
4031     if (This && !HasQualifier &&
4032         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4033       return Error(E, diag::note_constexpr_virtual_call);
4034 
4035     const FunctionDecl *Definition = 0;
4036     Stmt *Body = FD->getBody(Definition);
4037     APValue Result;
4038 
4039     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4040         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4041                             Info, Result))
4042       return false;
4043 
4044     return DerivedSuccess(Result, E);
4045   }
4046 
4047   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4048     return StmtVisitorTy::Visit(E->getInitializer());
4049   }
4050   bool VisitInitListExpr(const InitListExpr *E) {
4051     if (E->getNumInits() == 0)
4052       return DerivedZeroInitialization(E);
4053     if (E->getNumInits() == 1)
4054       return StmtVisitorTy::Visit(E->getInit(0));
4055     return Error(E);
4056   }
4057   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4058     return DerivedZeroInitialization(E);
4059   }
4060   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4061     return DerivedZeroInitialization(E);
4062   }
4063   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4064     return DerivedZeroInitialization(E);
4065   }
4066 
4067   /// A member expression where the object is a prvalue is itself a prvalue.
4068   bool VisitMemberExpr(const MemberExpr *E) {
4069     assert(!E->isArrow() && "missing call to bound member function?");
4070 
4071     APValue Val;
4072     if (!Evaluate(Val, Info, E->getBase()))
4073       return false;
4074 
4075     QualType BaseTy = E->getBase()->getType();
4076 
4077     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4078     if (!FD) return Error(E);
4079     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4080     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4081            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4082 
4083     CompleteObject Obj(&Val, BaseTy);
4084     SubobjectDesignator Designator(BaseTy);
4085     Designator.addDeclUnchecked(FD);
4086 
4087     APValue Result;
4088     return extractSubobject(Info, E, Obj, Designator, Result) &&
4089            DerivedSuccess(Result, E);
4090   }
4091 
4092   bool VisitCastExpr(const CastExpr *E) {
4093     switch (E->getCastKind()) {
4094     default:
4095       break;
4096 
4097     case CK_AtomicToNonAtomic: {
4098       APValue AtomicVal;
4099       if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4100         return false;
4101       return DerivedSuccess(AtomicVal, E);
4102     }
4103 
4104     case CK_NoOp:
4105     case CK_UserDefinedConversion:
4106       return StmtVisitorTy::Visit(E->getSubExpr());
4107 
4108     case CK_LValueToRValue: {
4109       LValue LVal;
4110       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4111         return false;
4112       APValue RVal;
4113       // Note, we use the subexpression's type in order to retain cv-qualifiers.
4114       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4115                                           LVal, RVal))
4116         return false;
4117       return DerivedSuccess(RVal, E);
4118     }
4119     }
4120 
4121     return Error(E);
4122   }
4123 
4124   bool VisitUnaryPostInc(const UnaryOperator *UO) {
4125     return VisitUnaryPostIncDec(UO);
4126   }
4127   bool VisitUnaryPostDec(const UnaryOperator *UO) {
4128     return VisitUnaryPostIncDec(UO);
4129   }
4130   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4131     if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4132       return Error(UO);
4133 
4134     LValue LVal;
4135     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4136       return false;
4137     APValue RVal;
4138     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4139                       UO->isIncrementOp(), &RVal))
4140       return false;
4141     return DerivedSuccess(RVal, UO);
4142   }
4143 
4144   bool VisitStmtExpr(const StmtExpr *E) {
4145     // We will have checked the full-expressions inside the statement expression
4146     // when they were completed, and don't need to check them again now.
4147     if (Info.checkingForOverflow())
4148       return Error(E);
4149 
4150     BlockScopeRAII Scope(Info);
4151     const CompoundStmt *CS = E->getSubStmt();
4152     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4153                                            BE = CS->body_end();
4154          /**/; ++BI) {
4155       if (BI + 1 == BE) {
4156         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4157         if (!FinalExpr) {
4158           Info.Diag((*BI)->getLocStart(),
4159                     diag::note_constexpr_stmt_expr_unsupported);
4160           return false;
4161         }
4162         return this->Visit(FinalExpr);
4163       }
4164 
4165       APValue ReturnValue;
4166       EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4167       if (ESR != ESR_Succeeded) {
4168         // FIXME: If the statement-expression terminated due to 'return',
4169         // 'break', or 'continue', it would be nice to propagate that to
4170         // the outer statement evaluation rather than bailing out.
4171         if (ESR != ESR_Failed)
4172           Info.Diag((*BI)->getLocStart(),
4173                     diag::note_constexpr_stmt_expr_unsupported);
4174         return false;
4175       }
4176     }
4177   }
4178 
4179   /// Visit a value which is evaluated, but whose value is ignored.
4180   void VisitIgnoredValue(const Expr *E) {
4181     EvaluateIgnoredValue(Info, E);
4182   }
4183 };
4184 
4185 }
4186 
4187 //===----------------------------------------------------------------------===//
4188 // Common base class for lvalue and temporary evaluation.
4189 //===----------------------------------------------------------------------===//
4190 namespace {
4191 template<class Derived>
4192 class LValueExprEvaluatorBase
4193   : public ExprEvaluatorBase<Derived> {
4194 protected:
4195   LValue &Result;
4196   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4197   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4198 
4199   bool Success(APValue::LValueBase B) {
4200     Result.set(B);
4201     return true;
4202   }
4203 
4204 public:
4205   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4206     ExprEvaluatorBaseTy(Info), Result(Result) {}
4207 
4208   bool Success(const APValue &V, const Expr *E) {
4209     Result.setFrom(this->Info.Ctx, V);
4210     return true;
4211   }
4212 
4213   bool VisitMemberExpr(const MemberExpr *E) {
4214     // Handle non-static data members.
4215     QualType BaseTy;
4216     if (E->isArrow()) {
4217       if (!EvaluatePointer(E->getBase(), Result, this->Info))
4218         return false;
4219       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4220     } else if (E->getBase()->isRValue()) {
4221       assert(E->getBase()->getType()->isRecordType());
4222       if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4223         return false;
4224       BaseTy = E->getBase()->getType();
4225     } else {
4226       if (!this->Visit(E->getBase()))
4227         return false;
4228       BaseTy = E->getBase()->getType();
4229     }
4230 
4231     const ValueDecl *MD = E->getMemberDecl();
4232     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4233       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4234              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4235       (void)BaseTy;
4236       if (!HandleLValueMember(this->Info, E, Result, FD))
4237         return false;
4238     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4239       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4240         return false;
4241     } else
4242       return this->Error(E);
4243 
4244     if (MD->getType()->isReferenceType()) {
4245       APValue RefValue;
4246       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4247                                           RefValue))
4248         return false;
4249       return Success(RefValue, E);
4250     }
4251     return true;
4252   }
4253 
4254   bool VisitBinaryOperator(const BinaryOperator *E) {
4255     switch (E->getOpcode()) {
4256     default:
4257       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4258 
4259     case BO_PtrMemD:
4260     case BO_PtrMemI:
4261       return HandleMemberPointerAccess(this->Info, E, Result);
4262     }
4263   }
4264 
4265   bool VisitCastExpr(const CastExpr *E) {
4266     switch (E->getCastKind()) {
4267     default:
4268       return ExprEvaluatorBaseTy::VisitCastExpr(E);
4269 
4270     case CK_DerivedToBase:
4271     case CK_UncheckedDerivedToBase:
4272       if (!this->Visit(E->getSubExpr()))
4273         return false;
4274 
4275       // Now figure out the necessary offset to add to the base LV to get from
4276       // the derived class to the base class.
4277       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4278                                   Result);
4279     }
4280   }
4281 };
4282 }
4283 
4284 //===----------------------------------------------------------------------===//
4285 // LValue Evaluation
4286 //
4287 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4288 // function designators (in C), decl references to void objects (in C), and
4289 // temporaries (if building with -Wno-address-of-temporary).
4290 //
4291 // LValue evaluation produces values comprising a base expression of one of the
4292 // following types:
4293 // - Declarations
4294 //  * VarDecl
4295 //  * FunctionDecl
4296 // - Literals
4297 //  * CompoundLiteralExpr in C
4298 //  * StringLiteral
4299 //  * CXXTypeidExpr
4300 //  * PredefinedExpr
4301 //  * ObjCStringLiteralExpr
4302 //  * ObjCEncodeExpr
4303 //  * AddrLabelExpr
4304 //  * BlockExpr
4305 //  * CallExpr for a MakeStringConstant builtin
4306 // - Locals and temporaries
4307 //  * MaterializeTemporaryExpr
4308 //  * Any Expr, with a CallIndex indicating the function in which the temporary
4309 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
4310 //    from the AST (FIXME).
4311 //  * A MaterializeTemporaryExpr that has static storage duration, with no
4312 //    CallIndex, for a lifetime-extended temporary.
4313 // plus an offset in bytes.
4314 //===----------------------------------------------------------------------===//
4315 namespace {
4316 class LValueExprEvaluator
4317   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4318 public:
4319   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4320     LValueExprEvaluatorBaseTy(Info, Result) {}
4321 
4322   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4323   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4324 
4325   bool VisitDeclRefExpr(const DeclRefExpr *E);
4326   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4327   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4328   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4329   bool VisitMemberExpr(const MemberExpr *E);
4330   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4331   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4332   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4333   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4334   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4335   bool VisitUnaryDeref(const UnaryOperator *E);
4336   bool VisitUnaryReal(const UnaryOperator *E);
4337   bool VisitUnaryImag(const UnaryOperator *E);
4338   bool VisitUnaryPreInc(const UnaryOperator *UO) {
4339     return VisitUnaryPreIncDec(UO);
4340   }
4341   bool VisitUnaryPreDec(const UnaryOperator *UO) {
4342     return VisitUnaryPreIncDec(UO);
4343   }
4344   bool VisitBinAssign(const BinaryOperator *BO);
4345   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4346 
4347   bool VisitCastExpr(const CastExpr *E) {
4348     switch (E->getCastKind()) {
4349     default:
4350       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4351 
4352     case CK_LValueBitCast:
4353       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4354       if (!Visit(E->getSubExpr()))
4355         return false;
4356       Result.Designator.setInvalid();
4357       return true;
4358 
4359     case CK_BaseToDerived:
4360       if (!Visit(E->getSubExpr()))
4361         return false;
4362       return HandleBaseToDerivedCast(Info, E, Result);
4363     }
4364   }
4365 };
4366 } // end anonymous namespace
4367 
4368 /// Evaluate an expression as an lvalue. This can be legitimately called on
4369 /// expressions which are not glvalues, in two cases:
4370 ///  * function designators in C, and
4371 ///  * "extern void" objects
4372 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4373   assert(E->isGLValue() || E->getType()->isFunctionType() ||
4374          E->getType()->isVoidType());
4375   return LValueExprEvaluator(Info, Result).Visit(E);
4376 }
4377 
4378 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4379   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4380     return Success(FD);
4381   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4382     return VisitVarDecl(E, VD);
4383   return Error(E);
4384 }
4385 
4386 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4387   CallStackFrame *Frame = 0;
4388   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4389     Frame = Info.CurrentCall;
4390 
4391   if (!VD->getType()->isReferenceType()) {
4392     if (Frame) {
4393       Result.set(VD, Frame->Index);
4394       return true;
4395     }
4396     return Success(VD);
4397   }
4398 
4399   APValue *V;
4400   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4401     return false;
4402   if (V->isUninit()) {
4403     if (!Info.checkingPotentialConstantExpression())
4404       Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4405     return false;
4406   }
4407   return Success(*V, E);
4408 }
4409 
4410 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4411     const MaterializeTemporaryExpr *E) {
4412   // Walk through the expression to find the materialized temporary itself.
4413   SmallVector<const Expr *, 2> CommaLHSs;
4414   SmallVector<SubobjectAdjustment, 2> Adjustments;
4415   const Expr *Inner = E->GetTemporaryExpr()->
4416       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4417 
4418   // If we passed any comma operators, evaluate their LHSs.
4419   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4420     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4421       return false;
4422 
4423   // A materialized temporary with static storage duration can appear within the
4424   // result of a constant expression evaluation, so we need to preserve its
4425   // value for use outside this evaluation.
4426   APValue *Value;
4427   if (E->getStorageDuration() == SD_Static) {
4428     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4429     *Value = APValue();
4430     Result.set(E);
4431   } else {
4432     Value = &Info.CurrentCall->
4433         createTemporary(E, E->getStorageDuration() == SD_Automatic);
4434     Result.set(E, Info.CurrentCall->Index);
4435   }
4436 
4437   QualType Type = Inner->getType();
4438 
4439   // Materialize the temporary itself.
4440   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4441       (E->getStorageDuration() == SD_Static &&
4442        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4443     *Value = APValue();
4444     return false;
4445   }
4446 
4447   // Adjust our lvalue to refer to the desired subobject.
4448   for (unsigned I = Adjustments.size(); I != 0; /**/) {
4449     --I;
4450     switch (Adjustments[I].Kind) {
4451     case SubobjectAdjustment::DerivedToBaseAdjustment:
4452       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4453                                 Type, Result))
4454         return false;
4455       Type = Adjustments[I].DerivedToBase.BasePath->getType();
4456       break;
4457 
4458     case SubobjectAdjustment::FieldAdjustment:
4459       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4460         return false;
4461       Type = Adjustments[I].Field->getType();
4462       break;
4463 
4464     case SubobjectAdjustment::MemberPointerAdjustment:
4465       if (!HandleMemberPointerAccess(this->Info, Type, Result,
4466                                      Adjustments[I].Ptr.RHS))
4467         return false;
4468       Type = Adjustments[I].Ptr.MPT->getPointeeType();
4469       break;
4470     }
4471   }
4472 
4473   return true;
4474 }
4475 
4476 bool
4477 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4478   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4479   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4480   // only see this when folding in C, so there's no standard to follow here.
4481   return Success(E);
4482 }
4483 
4484 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4485   if (!E->isPotentiallyEvaluated())
4486     return Success(E);
4487 
4488   Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4489     << E->getExprOperand()->getType()
4490     << E->getExprOperand()->getSourceRange();
4491   return false;
4492 }
4493 
4494 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4495   return Success(E);
4496 }
4497 
4498 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4499   // Handle static data members.
4500   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4501     VisitIgnoredValue(E->getBase());
4502     return VisitVarDecl(E, VD);
4503   }
4504 
4505   // Handle static member functions.
4506   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4507     if (MD->isStatic()) {
4508       VisitIgnoredValue(E->getBase());
4509       return Success(MD);
4510     }
4511   }
4512 
4513   // Handle non-static data members.
4514   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4515 }
4516 
4517 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4518   // FIXME: Deal with vectors as array subscript bases.
4519   if (E->getBase()->getType()->isVectorType())
4520     return Error(E);
4521 
4522   if (!EvaluatePointer(E->getBase(), Result, Info))
4523     return false;
4524 
4525   APSInt Index;
4526   if (!EvaluateInteger(E->getIdx(), Index, Info))
4527     return false;
4528 
4529   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4530                                      getExtValue(Index));
4531 }
4532 
4533 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4534   return EvaluatePointer(E->getSubExpr(), Result, Info);
4535 }
4536 
4537 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4538   if (!Visit(E->getSubExpr()))
4539     return false;
4540   // __real is a no-op on scalar lvalues.
4541   if (E->getSubExpr()->getType()->isAnyComplexType())
4542     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4543   return true;
4544 }
4545 
4546 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4547   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4548          "lvalue __imag__ on scalar?");
4549   if (!Visit(E->getSubExpr()))
4550     return false;
4551   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4552   return true;
4553 }
4554 
4555 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4556   if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4557     return Error(UO);
4558 
4559   if (!this->Visit(UO->getSubExpr()))
4560     return false;
4561 
4562   return handleIncDec(
4563       this->Info, UO, Result, UO->getSubExpr()->getType(),
4564       UO->isIncrementOp(), 0);
4565 }
4566 
4567 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4568     const CompoundAssignOperator *CAO) {
4569   if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4570     return Error(CAO);
4571 
4572   APValue RHS;
4573 
4574   // The overall lvalue result is the result of evaluating the LHS.
4575   if (!this->Visit(CAO->getLHS())) {
4576     if (Info.keepEvaluatingAfterFailure())
4577       Evaluate(RHS, this->Info, CAO->getRHS());
4578     return false;
4579   }
4580 
4581   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4582     return false;
4583 
4584   return handleCompoundAssignment(
4585       this->Info, CAO,
4586       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4587       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4588 }
4589 
4590 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4591   if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4592     return Error(E);
4593 
4594   APValue NewVal;
4595 
4596   if (!this->Visit(E->getLHS())) {
4597     if (Info.keepEvaluatingAfterFailure())
4598       Evaluate(NewVal, this->Info, E->getRHS());
4599     return false;
4600   }
4601 
4602   if (!Evaluate(NewVal, this->Info, E->getRHS()))
4603     return false;
4604 
4605   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4606                           NewVal);
4607 }
4608 
4609 //===----------------------------------------------------------------------===//
4610 // Pointer Evaluation
4611 //===----------------------------------------------------------------------===//
4612 
4613 namespace {
4614 class PointerExprEvaluator
4615   : public ExprEvaluatorBase<PointerExprEvaluator> {
4616   LValue &Result;
4617 
4618   bool Success(const Expr *E) {
4619     Result.set(E);
4620     return true;
4621   }
4622 public:
4623 
4624   PointerExprEvaluator(EvalInfo &info, LValue &Result)
4625     : ExprEvaluatorBaseTy(info), Result(Result) {}
4626 
4627   bool Success(const APValue &V, const Expr *E) {
4628     Result.setFrom(Info.Ctx, V);
4629     return true;
4630   }
4631   bool ZeroInitialization(const Expr *E) {
4632     return Success((Expr*)0);
4633   }
4634 
4635   bool VisitBinaryOperator(const BinaryOperator *E);
4636   bool VisitCastExpr(const CastExpr* E);
4637   bool VisitUnaryAddrOf(const UnaryOperator *E);
4638   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4639       { return Success(E); }
4640   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4641       { return Success(E); }
4642   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4643       { return Success(E); }
4644   bool VisitCallExpr(const CallExpr *E);
4645   bool VisitBlockExpr(const BlockExpr *E) {
4646     if (!E->getBlockDecl()->hasCaptures())
4647       return Success(E);
4648     return Error(E);
4649   }
4650   bool VisitCXXThisExpr(const CXXThisExpr *E) {
4651     // Can't look at 'this' when checking a potential constant expression.
4652     if (Info.checkingPotentialConstantExpression())
4653       return false;
4654     if (!Info.CurrentCall->This)
4655       return Error(E);
4656     Result = *Info.CurrentCall->This;
4657     return true;
4658   }
4659 
4660   // FIXME: Missing: @protocol, @selector
4661 };
4662 } // end anonymous namespace
4663 
4664 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4665   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4666   return PointerExprEvaluator(Info, Result).Visit(E);
4667 }
4668 
4669 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4670   if (E->getOpcode() != BO_Add &&
4671       E->getOpcode() != BO_Sub)
4672     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4673 
4674   const Expr *PExp = E->getLHS();
4675   const Expr *IExp = E->getRHS();
4676   if (IExp->getType()->isPointerType())
4677     std::swap(PExp, IExp);
4678 
4679   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4680   if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4681     return false;
4682 
4683   llvm::APSInt Offset;
4684   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4685     return false;
4686 
4687   int64_t AdditionalOffset = getExtValue(Offset);
4688   if (E->getOpcode() == BO_Sub)
4689     AdditionalOffset = -AdditionalOffset;
4690 
4691   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4692   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4693                                      AdditionalOffset);
4694 }
4695 
4696 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4697   return EvaluateLValue(E->getSubExpr(), Result, Info);
4698 }
4699 
4700 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4701   const Expr* SubExpr = E->getSubExpr();
4702 
4703   switch (E->getCastKind()) {
4704   default:
4705     break;
4706 
4707   case CK_BitCast:
4708   case CK_CPointerToObjCPointerCast:
4709   case CK_BlockPointerToObjCPointerCast:
4710   case CK_AnyPointerToBlockPointerCast:
4711     if (!Visit(SubExpr))
4712       return false;
4713     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4714     // permitted in constant expressions in C++11. Bitcasts from cv void* are
4715     // also static_casts, but we disallow them as a resolution to DR1312.
4716     if (!E->getType()->isVoidPointerType()) {
4717       Result.Designator.setInvalid();
4718       if (SubExpr->getType()->isVoidPointerType())
4719         CCEDiag(E, diag::note_constexpr_invalid_cast)
4720           << 3 << SubExpr->getType();
4721       else
4722         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4723     }
4724     return true;
4725 
4726   case CK_DerivedToBase:
4727   case CK_UncheckedDerivedToBase:
4728     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4729       return false;
4730     if (!Result.Base && Result.Offset.isZero())
4731       return true;
4732 
4733     // Now figure out the necessary offset to add to the base LV to get from
4734     // the derived class to the base class.
4735     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4736                                   castAs<PointerType>()->getPointeeType(),
4737                                 Result);
4738 
4739   case CK_BaseToDerived:
4740     if (!Visit(E->getSubExpr()))
4741       return false;
4742     if (!Result.Base && Result.Offset.isZero())
4743       return true;
4744     return HandleBaseToDerivedCast(Info, E, Result);
4745 
4746   case CK_NullToPointer:
4747     VisitIgnoredValue(E->getSubExpr());
4748     return ZeroInitialization(E);
4749 
4750   case CK_IntegralToPointer: {
4751     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4752 
4753     APValue Value;
4754     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4755       break;
4756 
4757     if (Value.isInt()) {
4758       unsigned Size = Info.Ctx.getTypeSize(E->getType());
4759       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4760       Result.Base = (Expr*)0;
4761       Result.Offset = CharUnits::fromQuantity(N);
4762       Result.CallIndex = 0;
4763       Result.Designator.setInvalid();
4764       return true;
4765     } else {
4766       // Cast is of an lvalue, no need to change value.
4767       Result.setFrom(Info.Ctx, Value);
4768       return true;
4769     }
4770   }
4771   case CK_ArrayToPointerDecay:
4772     if (SubExpr->isGLValue()) {
4773       if (!EvaluateLValue(SubExpr, Result, Info))
4774         return false;
4775     } else {
4776       Result.set(SubExpr, Info.CurrentCall->Index);
4777       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4778                            Info, Result, SubExpr))
4779         return false;
4780     }
4781     // The result is a pointer to the first element of the array.
4782     if (const ConstantArrayType *CAT
4783           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4784       Result.addArray(Info, E, CAT);
4785     else
4786       Result.Designator.setInvalid();
4787     return true;
4788 
4789   case CK_FunctionToPointerDecay:
4790     return EvaluateLValue(SubExpr, Result, Info);
4791   }
4792 
4793   return ExprEvaluatorBaseTy::VisitCastExpr(E);
4794 }
4795 
4796 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4797   if (IsStringLiteralCall(E))
4798     return Success(E);
4799 
4800   switch (E->getBuiltinCallee()) {
4801   case Builtin::BI__builtin_addressof:
4802     return EvaluateLValue(E->getArg(0), Result, Info);
4803 
4804   default:
4805     return ExprEvaluatorBaseTy::VisitCallExpr(E);
4806   }
4807 }
4808 
4809 //===----------------------------------------------------------------------===//
4810 // Member Pointer Evaluation
4811 //===----------------------------------------------------------------------===//
4812 
4813 namespace {
4814 class MemberPointerExprEvaluator
4815   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
4816   MemberPtr &Result;
4817 
4818   bool Success(const ValueDecl *D) {
4819     Result = MemberPtr(D);
4820     return true;
4821   }
4822 public:
4823 
4824   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4825     : ExprEvaluatorBaseTy(Info), Result(Result) {}
4826 
4827   bool Success(const APValue &V, const Expr *E) {
4828     Result.setFrom(V);
4829     return true;
4830   }
4831   bool ZeroInitialization(const Expr *E) {
4832     return Success((const ValueDecl*)0);
4833   }
4834 
4835   bool VisitCastExpr(const CastExpr *E);
4836   bool VisitUnaryAddrOf(const UnaryOperator *E);
4837 };
4838 } // end anonymous namespace
4839 
4840 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4841                                   EvalInfo &Info) {
4842   assert(E->isRValue() && E->getType()->isMemberPointerType());
4843   return MemberPointerExprEvaluator(Info, Result).Visit(E);
4844 }
4845 
4846 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4847   switch (E->getCastKind()) {
4848   default:
4849     return ExprEvaluatorBaseTy::VisitCastExpr(E);
4850 
4851   case CK_NullToMemberPointer:
4852     VisitIgnoredValue(E->getSubExpr());
4853     return ZeroInitialization(E);
4854 
4855   case CK_BaseToDerivedMemberPointer: {
4856     if (!Visit(E->getSubExpr()))
4857       return false;
4858     if (E->path_empty())
4859       return true;
4860     // Base-to-derived member pointer casts store the path in derived-to-base
4861     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4862     // the wrong end of the derived->base arc, so stagger the path by one class.
4863     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4864     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4865          PathI != PathE; ++PathI) {
4866       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4867       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4868       if (!Result.castToDerived(Derived))
4869         return Error(E);
4870     }
4871     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4872     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
4873       return Error(E);
4874     return true;
4875   }
4876 
4877   case CK_DerivedToBaseMemberPointer:
4878     if (!Visit(E->getSubExpr()))
4879       return false;
4880     for (CastExpr::path_const_iterator PathI = E->path_begin(),
4881          PathE = E->path_end(); PathI != PathE; ++PathI) {
4882       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4883       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4884       if (!Result.castToBase(Base))
4885         return Error(E);
4886     }
4887     return true;
4888   }
4889 }
4890 
4891 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4892   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4893   // member can be formed.
4894   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4895 }
4896 
4897 //===----------------------------------------------------------------------===//
4898 // Record Evaluation
4899 //===----------------------------------------------------------------------===//
4900 
4901 namespace {
4902   class RecordExprEvaluator
4903   : public ExprEvaluatorBase<RecordExprEvaluator> {
4904     const LValue &This;
4905     APValue &Result;
4906   public:
4907 
4908     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4909       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4910 
4911     bool Success(const APValue &V, const Expr *E) {
4912       Result = V;
4913       return true;
4914     }
4915     bool ZeroInitialization(const Expr *E);
4916 
4917     bool VisitCastExpr(const CastExpr *E);
4918     bool VisitInitListExpr(const InitListExpr *E);
4919     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4920     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
4921   };
4922 }
4923 
4924 /// Perform zero-initialization on an object of non-union class type.
4925 /// C++11 [dcl.init]p5:
4926 ///  To zero-initialize an object or reference of type T means:
4927 ///    [...]
4928 ///    -- if T is a (possibly cv-qualified) non-union class type,
4929 ///       each non-static data member and each base-class subobject is
4930 ///       zero-initialized
4931 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4932                                           const RecordDecl *RD,
4933                                           const LValue &This, APValue &Result) {
4934   assert(!RD->isUnion() && "Expected non-union class type");
4935   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4936   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4937                    std::distance(RD->field_begin(), RD->field_end()));
4938 
4939   if (RD->isInvalidDecl()) return false;
4940   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4941 
4942   if (CD) {
4943     unsigned Index = 0;
4944     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
4945            End = CD->bases_end(); I != End; ++I, ++Index) {
4946       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4947       LValue Subobject = This;
4948       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4949         return false;
4950       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
4951                                          Result.getStructBase(Index)))
4952         return false;
4953     }
4954   }
4955 
4956   for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4957        I != End; ++I) {
4958     // -- if T is a reference type, no initialization is performed.
4959     if (I->getType()->isReferenceType())
4960       continue;
4961 
4962     LValue Subobject = This;
4963     if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
4964       return false;
4965 
4966     ImplicitValueInitExpr VIE(I->getType());
4967     if (!EvaluateInPlace(
4968           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
4969       return false;
4970   }
4971 
4972   return true;
4973 }
4974 
4975 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4976   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
4977   if (RD->isInvalidDecl()) return false;
4978   if (RD->isUnion()) {
4979     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4980     // object's first non-static named data member is zero-initialized
4981     RecordDecl::field_iterator I = RD->field_begin();
4982     if (I == RD->field_end()) {
4983       Result = APValue((const FieldDecl*)0);
4984       return true;
4985     }
4986 
4987     LValue Subobject = This;
4988     if (!HandleLValueMember(Info, E, Subobject, *I))
4989       return false;
4990     Result = APValue(*I);
4991     ImplicitValueInitExpr VIE(I->getType());
4992     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
4993   }
4994 
4995   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
4996     Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
4997     return false;
4998   }
4999 
5000   return HandleClassZeroInitialization(Info, E, RD, This, Result);
5001 }
5002 
5003 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5004   switch (E->getCastKind()) {
5005   default:
5006     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5007 
5008   case CK_ConstructorConversion:
5009     return Visit(E->getSubExpr());
5010 
5011   case CK_DerivedToBase:
5012   case CK_UncheckedDerivedToBase: {
5013     APValue DerivedObject;
5014     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5015       return false;
5016     if (!DerivedObject.isStruct())
5017       return Error(E->getSubExpr());
5018 
5019     // Derived-to-base rvalue conversion: just slice off the derived part.
5020     APValue *Value = &DerivedObject;
5021     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5022     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5023          PathE = E->path_end(); PathI != PathE; ++PathI) {
5024       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5025       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5026       Value = &Value->getStructBase(getBaseIndex(RD, Base));
5027       RD = Base;
5028     }
5029     Result = *Value;
5030     return true;
5031   }
5032   }
5033 }
5034 
5035 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5036   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5037   if (RD->isInvalidDecl()) return false;
5038   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5039 
5040   if (RD->isUnion()) {
5041     const FieldDecl *Field = E->getInitializedFieldInUnion();
5042     Result = APValue(Field);
5043     if (!Field)
5044       return true;
5045 
5046     // If the initializer list for a union does not contain any elements, the
5047     // first element of the union is value-initialized.
5048     // FIXME: The element should be initialized from an initializer list.
5049     //        Is this difference ever observable for initializer lists which
5050     //        we don't build?
5051     ImplicitValueInitExpr VIE(Field->getType());
5052     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5053 
5054     LValue Subobject = This;
5055     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5056       return false;
5057 
5058     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5059     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5060                                   isa<CXXDefaultInitExpr>(InitExpr));
5061 
5062     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5063   }
5064 
5065   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5066          "initializer list for class with base classes");
5067   Result = APValue(APValue::UninitStruct(), 0,
5068                    std::distance(RD->field_begin(), RD->field_end()));
5069   unsigned ElementNo = 0;
5070   bool Success = true;
5071   for (RecordDecl::field_iterator Field = RD->field_begin(),
5072        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5073     // Anonymous bit-fields are not considered members of the class for
5074     // purposes of aggregate initialization.
5075     if (Field->isUnnamedBitfield())
5076       continue;
5077 
5078     LValue Subobject = This;
5079 
5080     bool HaveInit = ElementNo < E->getNumInits();
5081 
5082     // FIXME: Diagnostics here should point to the end of the initializer
5083     // list, not the start.
5084     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5085                             Subobject, *Field, &Layout))
5086       return false;
5087 
5088     // Perform an implicit value-initialization for members beyond the end of
5089     // the initializer list.
5090     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5091     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5092 
5093     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5094     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5095                                   isa<CXXDefaultInitExpr>(Init));
5096 
5097     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5098     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5099         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5100                                                        FieldVal, *Field))) {
5101       if (!Info.keepEvaluatingAfterFailure())
5102         return false;
5103       Success = false;
5104     }
5105   }
5106 
5107   return Success;
5108 }
5109 
5110 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5111   const CXXConstructorDecl *FD = E->getConstructor();
5112   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5113 
5114   bool ZeroInit = E->requiresZeroInitialization();
5115   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5116     // If we've already performed zero-initialization, we're already done.
5117     if (!Result.isUninit())
5118       return true;
5119 
5120     if (ZeroInit)
5121       return ZeroInitialization(E);
5122 
5123     const CXXRecordDecl *RD = FD->getParent();
5124     if (RD->isUnion())
5125       Result = APValue((FieldDecl*)0);
5126     else
5127       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5128                        std::distance(RD->field_begin(), RD->field_end()));
5129     return true;
5130   }
5131 
5132   const FunctionDecl *Definition = 0;
5133   FD->getBody(Definition);
5134 
5135   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5136     return false;
5137 
5138   // Avoid materializing a temporary for an elidable copy/move constructor.
5139   if (E->isElidable() && !ZeroInit)
5140     if (const MaterializeTemporaryExpr *ME
5141           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5142       return Visit(ME->GetTemporaryExpr());
5143 
5144   if (ZeroInit && !ZeroInitialization(E))
5145     return false;
5146 
5147   ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5148   return HandleConstructorCall(E->getExprLoc(), This, Args,
5149                                cast<CXXConstructorDecl>(Definition), Info,
5150                                Result);
5151 }
5152 
5153 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5154     const CXXStdInitializerListExpr *E) {
5155   const ConstantArrayType *ArrayType =
5156       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5157 
5158   LValue Array;
5159   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5160     return false;
5161 
5162   // Get a pointer to the first element of the array.
5163   Array.addArray(Info, E, ArrayType);
5164 
5165   // FIXME: Perform the checks on the field types in SemaInit.
5166   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5167   RecordDecl::field_iterator Field = Record->field_begin();
5168   if (Field == Record->field_end())
5169     return Error(E);
5170 
5171   // Start pointer.
5172   if (!Field->getType()->isPointerType() ||
5173       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5174                             ArrayType->getElementType()))
5175     return Error(E);
5176 
5177   // FIXME: What if the initializer_list type has base classes, etc?
5178   Result = APValue(APValue::UninitStruct(), 0, 2);
5179   Array.moveInto(Result.getStructField(0));
5180 
5181   if (++Field == Record->field_end())
5182     return Error(E);
5183 
5184   if (Field->getType()->isPointerType() &&
5185       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5186                            ArrayType->getElementType())) {
5187     // End pointer.
5188     if (!HandleLValueArrayAdjustment(Info, E, Array,
5189                                      ArrayType->getElementType(),
5190                                      ArrayType->getSize().getZExtValue()))
5191       return false;
5192     Array.moveInto(Result.getStructField(1));
5193   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5194     // Length.
5195     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5196   else
5197     return Error(E);
5198 
5199   if (++Field != Record->field_end())
5200     return Error(E);
5201 
5202   return true;
5203 }
5204 
5205 static bool EvaluateRecord(const Expr *E, const LValue &This,
5206                            APValue &Result, EvalInfo &Info) {
5207   assert(E->isRValue() && E->getType()->isRecordType() &&
5208          "can't evaluate expression as a record rvalue");
5209   return RecordExprEvaluator(Info, This, Result).Visit(E);
5210 }
5211 
5212 //===----------------------------------------------------------------------===//
5213 // Temporary Evaluation
5214 //
5215 // Temporaries are represented in the AST as rvalues, but generally behave like
5216 // lvalues. The full-object of which the temporary is a subobject is implicitly
5217 // materialized so that a reference can bind to it.
5218 //===----------------------------------------------------------------------===//
5219 namespace {
5220 class TemporaryExprEvaluator
5221   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5222 public:
5223   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5224     LValueExprEvaluatorBaseTy(Info, Result) {}
5225 
5226   /// Visit an expression which constructs the value of this temporary.
5227   bool VisitConstructExpr(const Expr *E) {
5228     Result.set(E, Info.CurrentCall->Index);
5229     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5230                            Info, Result, E);
5231   }
5232 
5233   bool VisitCastExpr(const CastExpr *E) {
5234     switch (E->getCastKind()) {
5235     default:
5236       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5237 
5238     case CK_ConstructorConversion:
5239       return VisitConstructExpr(E->getSubExpr());
5240     }
5241   }
5242   bool VisitInitListExpr(const InitListExpr *E) {
5243     return VisitConstructExpr(E);
5244   }
5245   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5246     return VisitConstructExpr(E);
5247   }
5248   bool VisitCallExpr(const CallExpr *E) {
5249     return VisitConstructExpr(E);
5250   }
5251 };
5252 } // end anonymous namespace
5253 
5254 /// Evaluate an expression of record type as a temporary.
5255 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5256   assert(E->isRValue() && E->getType()->isRecordType());
5257   return TemporaryExprEvaluator(Info, Result).Visit(E);
5258 }
5259 
5260 //===----------------------------------------------------------------------===//
5261 // Vector Evaluation
5262 //===----------------------------------------------------------------------===//
5263 
5264 namespace {
5265   class VectorExprEvaluator
5266   : public ExprEvaluatorBase<VectorExprEvaluator> {
5267     APValue &Result;
5268   public:
5269 
5270     VectorExprEvaluator(EvalInfo &info, APValue &Result)
5271       : ExprEvaluatorBaseTy(info), Result(Result) {}
5272 
5273     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5274       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5275       // FIXME: remove this APValue copy.
5276       Result = APValue(V.data(), V.size());
5277       return true;
5278     }
5279     bool Success(const APValue &V, const Expr *E) {
5280       assert(V.isVector());
5281       Result = V;
5282       return true;
5283     }
5284     bool ZeroInitialization(const Expr *E);
5285 
5286     bool VisitUnaryReal(const UnaryOperator *E)
5287       { return Visit(E->getSubExpr()); }
5288     bool VisitCastExpr(const CastExpr* E);
5289     bool VisitInitListExpr(const InitListExpr *E);
5290     bool VisitUnaryImag(const UnaryOperator *E);
5291     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5292     //                 binary comparisons, binary and/or/xor,
5293     //                 shufflevector, ExtVectorElementExpr
5294   };
5295 } // end anonymous namespace
5296 
5297 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5298   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5299   return VectorExprEvaluator(Info, Result).Visit(E);
5300 }
5301 
5302 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5303   const VectorType *VTy = E->getType()->castAs<VectorType>();
5304   unsigned NElts = VTy->getNumElements();
5305 
5306   const Expr *SE = E->getSubExpr();
5307   QualType SETy = SE->getType();
5308 
5309   switch (E->getCastKind()) {
5310   case CK_VectorSplat: {
5311     APValue Val = APValue();
5312     if (SETy->isIntegerType()) {
5313       APSInt IntResult;
5314       if (!EvaluateInteger(SE, IntResult, Info))
5315          return false;
5316       Val = APValue(IntResult);
5317     } else if (SETy->isRealFloatingType()) {
5318        APFloat F(0.0);
5319        if (!EvaluateFloat(SE, F, Info))
5320          return false;
5321        Val = APValue(F);
5322     } else {
5323       return Error(E);
5324     }
5325 
5326     // Splat and create vector APValue.
5327     SmallVector<APValue, 4> Elts(NElts, Val);
5328     return Success(Elts, E);
5329   }
5330   case CK_BitCast: {
5331     // Evaluate the operand into an APInt we can extract from.
5332     llvm::APInt SValInt;
5333     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5334       return false;
5335     // Extract the elements
5336     QualType EltTy = VTy->getElementType();
5337     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5338     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5339     SmallVector<APValue, 4> Elts;
5340     if (EltTy->isRealFloatingType()) {
5341       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5342       unsigned FloatEltSize = EltSize;
5343       if (&Sem == &APFloat::x87DoubleExtended)
5344         FloatEltSize = 80;
5345       for (unsigned i = 0; i < NElts; i++) {
5346         llvm::APInt Elt;
5347         if (BigEndian)
5348           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5349         else
5350           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5351         Elts.push_back(APValue(APFloat(Sem, Elt)));
5352       }
5353     } else if (EltTy->isIntegerType()) {
5354       for (unsigned i = 0; i < NElts; i++) {
5355         llvm::APInt Elt;
5356         if (BigEndian)
5357           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5358         else
5359           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5360         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5361       }
5362     } else {
5363       return Error(E);
5364     }
5365     return Success(Elts, E);
5366   }
5367   default:
5368     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5369   }
5370 }
5371 
5372 bool
5373 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5374   const VectorType *VT = E->getType()->castAs<VectorType>();
5375   unsigned NumInits = E->getNumInits();
5376   unsigned NumElements = VT->getNumElements();
5377 
5378   QualType EltTy = VT->getElementType();
5379   SmallVector<APValue, 4> Elements;
5380 
5381   // The number of initializers can be less than the number of
5382   // vector elements. For OpenCL, this can be due to nested vector
5383   // initialization. For GCC compatibility, missing trailing elements
5384   // should be initialized with zeroes.
5385   unsigned CountInits = 0, CountElts = 0;
5386   while (CountElts < NumElements) {
5387     // Handle nested vector initialization.
5388     if (CountInits < NumInits
5389         && E->getInit(CountInits)->getType()->isVectorType()) {
5390       APValue v;
5391       if (!EvaluateVector(E->getInit(CountInits), v, Info))
5392         return Error(E);
5393       unsigned vlen = v.getVectorLength();
5394       for (unsigned j = 0; j < vlen; j++)
5395         Elements.push_back(v.getVectorElt(j));
5396       CountElts += vlen;
5397     } else if (EltTy->isIntegerType()) {
5398       llvm::APSInt sInt(32);
5399       if (CountInits < NumInits) {
5400         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5401           return false;
5402       } else // trailing integer zero.
5403         sInt = Info.Ctx.MakeIntValue(0, EltTy);
5404       Elements.push_back(APValue(sInt));
5405       CountElts++;
5406     } else {
5407       llvm::APFloat f(0.0);
5408       if (CountInits < NumInits) {
5409         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5410           return false;
5411       } else // trailing float zero.
5412         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5413       Elements.push_back(APValue(f));
5414       CountElts++;
5415     }
5416     CountInits++;
5417   }
5418   return Success(Elements, E);
5419 }
5420 
5421 bool
5422 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5423   const VectorType *VT = E->getType()->getAs<VectorType>();
5424   QualType EltTy = VT->getElementType();
5425   APValue ZeroElement;
5426   if (EltTy->isIntegerType())
5427     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5428   else
5429     ZeroElement =
5430         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5431 
5432   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5433   return Success(Elements, E);
5434 }
5435 
5436 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5437   VisitIgnoredValue(E->getSubExpr());
5438   return ZeroInitialization(E);
5439 }
5440 
5441 //===----------------------------------------------------------------------===//
5442 // Array Evaluation
5443 //===----------------------------------------------------------------------===//
5444 
5445 namespace {
5446   class ArrayExprEvaluator
5447   : public ExprEvaluatorBase<ArrayExprEvaluator> {
5448     const LValue &This;
5449     APValue &Result;
5450   public:
5451 
5452     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5453       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5454 
5455     bool Success(const APValue &V, const Expr *E) {
5456       assert((V.isArray() || V.isLValue()) &&
5457              "expected array or string literal");
5458       Result = V;
5459       return true;
5460     }
5461 
5462     bool ZeroInitialization(const Expr *E) {
5463       const ConstantArrayType *CAT =
5464           Info.Ctx.getAsConstantArrayType(E->getType());
5465       if (!CAT)
5466         return Error(E);
5467 
5468       Result = APValue(APValue::UninitArray(), 0,
5469                        CAT->getSize().getZExtValue());
5470       if (!Result.hasArrayFiller()) return true;
5471 
5472       // Zero-initialize all elements.
5473       LValue Subobject = This;
5474       Subobject.addArray(Info, E, CAT);
5475       ImplicitValueInitExpr VIE(CAT->getElementType());
5476       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5477     }
5478 
5479     bool VisitInitListExpr(const InitListExpr *E);
5480     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5481     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5482                                const LValue &Subobject,
5483                                APValue *Value, QualType Type);
5484   };
5485 } // end anonymous namespace
5486 
5487 static bool EvaluateArray(const Expr *E, const LValue &This,
5488                           APValue &Result, EvalInfo &Info) {
5489   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5490   return ArrayExprEvaluator(Info, This, Result).Visit(E);
5491 }
5492 
5493 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5494   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5495   if (!CAT)
5496     return Error(E);
5497 
5498   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5499   // an appropriately-typed string literal enclosed in braces.
5500   if (E->isStringLiteralInit()) {
5501     LValue LV;
5502     if (!EvaluateLValue(E->getInit(0), LV, Info))
5503       return false;
5504     APValue Val;
5505     LV.moveInto(Val);
5506     return Success(Val, E);
5507   }
5508 
5509   bool Success = true;
5510 
5511   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5512          "zero-initialized array shouldn't have any initialized elts");
5513   APValue Filler;
5514   if (Result.isArray() && Result.hasArrayFiller())
5515     Filler = Result.getArrayFiller();
5516 
5517   unsigned NumEltsToInit = E->getNumInits();
5518   unsigned NumElts = CAT->getSize().getZExtValue();
5519   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5520 
5521   // If the initializer might depend on the array index, run it for each
5522   // array element. For now, just whitelist non-class value-initialization.
5523   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5524     NumEltsToInit = NumElts;
5525 
5526   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5527 
5528   // If the array was previously zero-initialized, preserve the
5529   // zero-initialized values.
5530   if (!Filler.isUninit()) {
5531     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5532       Result.getArrayInitializedElt(I) = Filler;
5533     if (Result.hasArrayFiller())
5534       Result.getArrayFiller() = Filler;
5535   }
5536 
5537   LValue Subobject = This;
5538   Subobject.addArray(Info, E, CAT);
5539   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5540     const Expr *Init =
5541         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5542     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5543                          Info, Subobject, Init) ||
5544         !HandleLValueArrayAdjustment(Info, Init, Subobject,
5545                                      CAT->getElementType(), 1)) {
5546       if (!Info.keepEvaluatingAfterFailure())
5547         return false;
5548       Success = false;
5549     }
5550   }
5551 
5552   if (!Result.hasArrayFiller())
5553     return Success;
5554 
5555   // If we get here, we have a trivial filler, which we can just evaluate
5556   // once and splat over the rest of the array elements.
5557   assert(FillerExpr && "no array filler for incomplete init list");
5558   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5559                          FillerExpr) && Success;
5560 }
5561 
5562 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5563   return VisitCXXConstructExpr(E, This, &Result, E->getType());
5564 }
5565 
5566 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5567                                                const LValue &Subobject,
5568                                                APValue *Value,
5569                                                QualType Type) {
5570   bool HadZeroInit = !Value->isUninit();
5571 
5572   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5573     unsigned N = CAT->getSize().getZExtValue();
5574 
5575     // Preserve the array filler if we had prior zero-initialization.
5576     APValue Filler =
5577       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5578                                              : APValue();
5579 
5580     *Value = APValue(APValue::UninitArray(), N, N);
5581 
5582     if (HadZeroInit)
5583       for (unsigned I = 0; I != N; ++I)
5584         Value->getArrayInitializedElt(I) = Filler;
5585 
5586     // Initialize the elements.
5587     LValue ArrayElt = Subobject;
5588     ArrayElt.addArray(Info, E, CAT);
5589     for (unsigned I = 0; I != N; ++I)
5590       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5591                                  CAT->getElementType()) ||
5592           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5593                                        CAT->getElementType(), 1))
5594         return false;
5595 
5596     return true;
5597   }
5598 
5599   if (!Type->isRecordType())
5600     return Error(E);
5601 
5602   const CXXConstructorDecl *FD = E->getConstructor();
5603 
5604   bool ZeroInit = E->requiresZeroInitialization();
5605   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5606     if (HadZeroInit)
5607       return true;
5608 
5609     if (ZeroInit) {
5610       ImplicitValueInitExpr VIE(Type);
5611       return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5612     }
5613 
5614     const CXXRecordDecl *RD = FD->getParent();
5615     if (RD->isUnion())
5616       *Value = APValue((FieldDecl*)0);
5617     else
5618       *Value =
5619           APValue(APValue::UninitStruct(), RD->getNumBases(),
5620                   std::distance(RD->field_begin(), RD->field_end()));
5621     return true;
5622   }
5623 
5624   const FunctionDecl *Definition = 0;
5625   FD->getBody(Definition);
5626 
5627   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5628     return false;
5629 
5630   if (ZeroInit && !HadZeroInit) {
5631     ImplicitValueInitExpr VIE(Type);
5632     if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5633       return false;
5634   }
5635 
5636   ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5637   return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5638                                cast<CXXConstructorDecl>(Definition),
5639                                Info, *Value);
5640 }
5641 
5642 //===----------------------------------------------------------------------===//
5643 // Integer Evaluation
5644 //
5645 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5646 // types and back in constant folding. Integer values are thus represented
5647 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5648 //===----------------------------------------------------------------------===//
5649 
5650 namespace {
5651 class IntExprEvaluator
5652   : public ExprEvaluatorBase<IntExprEvaluator> {
5653   APValue &Result;
5654 public:
5655   IntExprEvaluator(EvalInfo &info, APValue &result)
5656     : ExprEvaluatorBaseTy(info), Result(result) {}
5657 
5658   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5659     assert(E->getType()->isIntegralOrEnumerationType() &&
5660            "Invalid evaluation result.");
5661     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5662            "Invalid evaluation result.");
5663     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5664            "Invalid evaluation result.");
5665     Result = APValue(SI);
5666     return true;
5667   }
5668   bool Success(const llvm::APSInt &SI, const Expr *E) {
5669     return Success(SI, E, Result);
5670   }
5671 
5672   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5673     assert(E->getType()->isIntegralOrEnumerationType() &&
5674            "Invalid evaluation result.");
5675     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5676            "Invalid evaluation result.");
5677     Result = APValue(APSInt(I));
5678     Result.getInt().setIsUnsigned(
5679                             E->getType()->isUnsignedIntegerOrEnumerationType());
5680     return true;
5681   }
5682   bool Success(const llvm::APInt &I, const Expr *E) {
5683     return Success(I, E, Result);
5684   }
5685 
5686   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5687     assert(E->getType()->isIntegralOrEnumerationType() &&
5688            "Invalid evaluation result.");
5689     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5690     return true;
5691   }
5692   bool Success(uint64_t Value, const Expr *E) {
5693     return Success(Value, E, Result);
5694   }
5695 
5696   bool Success(CharUnits Size, const Expr *E) {
5697     return Success(Size.getQuantity(), E);
5698   }
5699 
5700   bool Success(const APValue &V, const Expr *E) {
5701     if (V.isLValue() || V.isAddrLabelDiff()) {
5702       Result = V;
5703       return true;
5704     }
5705     return Success(V.getInt(), E);
5706   }
5707 
5708   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5709 
5710   //===--------------------------------------------------------------------===//
5711   //                            Visitor Methods
5712   //===--------------------------------------------------------------------===//
5713 
5714   bool VisitIntegerLiteral(const IntegerLiteral *E) {
5715     return Success(E->getValue(), E);
5716   }
5717   bool VisitCharacterLiteral(const CharacterLiteral *E) {
5718     return Success(E->getValue(), E);
5719   }
5720 
5721   bool CheckReferencedDecl(const Expr *E, const Decl *D);
5722   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5723     if (CheckReferencedDecl(E, E->getDecl()))
5724       return true;
5725 
5726     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5727   }
5728   bool VisitMemberExpr(const MemberExpr *E) {
5729     if (CheckReferencedDecl(E, E->getMemberDecl())) {
5730       VisitIgnoredValue(E->getBase());
5731       return true;
5732     }
5733 
5734     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5735   }
5736 
5737   bool VisitCallExpr(const CallExpr *E);
5738   bool VisitBinaryOperator(const BinaryOperator *E);
5739   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5740   bool VisitUnaryOperator(const UnaryOperator *E);
5741 
5742   bool VisitCastExpr(const CastExpr* E);
5743   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5744 
5745   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5746     return Success(E->getValue(), E);
5747   }
5748 
5749   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5750     return Success(E->getValue(), E);
5751   }
5752 
5753   // Note, GNU defines __null as an integer, not a pointer.
5754   bool VisitGNUNullExpr(const GNUNullExpr *E) {
5755     return ZeroInitialization(E);
5756   }
5757 
5758   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5759     return Success(E->getValue(), E);
5760   }
5761 
5762   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5763     return Success(E->getValue(), E);
5764   }
5765 
5766   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5767     return Success(E->getValue(), E);
5768   }
5769 
5770   bool VisitUnaryReal(const UnaryOperator *E);
5771   bool VisitUnaryImag(const UnaryOperator *E);
5772 
5773   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5774   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5775 
5776 private:
5777   CharUnits GetAlignOfExpr(const Expr *E);
5778   CharUnits GetAlignOfType(QualType T);
5779   static QualType GetObjectType(APValue::LValueBase B);
5780   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
5781   // FIXME: Missing: array subscript of vector, member of vector
5782 };
5783 } // end anonymous namespace
5784 
5785 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5786 /// produce either the integer value or a pointer.
5787 ///
5788 /// GCC has a heinous extension which folds casts between pointer types and
5789 /// pointer-sized integral types. We support this by allowing the evaluation of
5790 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5791 /// Some simple arithmetic on such values is supported (they are treated much
5792 /// like char*).
5793 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
5794                                     EvalInfo &Info) {
5795   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
5796   return IntExprEvaluator(Info, Result).Visit(E);
5797 }
5798 
5799 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
5800   APValue Val;
5801   if (!EvaluateIntegerOrLValue(E, Val, Info))
5802     return false;
5803   if (!Val.isInt()) {
5804     // FIXME: It would be better to produce the diagnostic for casting
5805     //        a pointer to an integer.
5806     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
5807     return false;
5808   }
5809   Result = Val.getInt();
5810   return true;
5811 }
5812 
5813 /// Check whether the given declaration can be directly converted to an integral
5814 /// rvalue. If not, no diagnostic is produced; there are other things we can
5815 /// try.
5816 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
5817   // Enums are integer constant exprs.
5818   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
5819     // Check for signedness/width mismatches between E type and ECD value.
5820     bool SameSign = (ECD->getInitVal().isSigned()
5821                      == E->getType()->isSignedIntegerOrEnumerationType());
5822     bool SameWidth = (ECD->getInitVal().getBitWidth()
5823                       == Info.Ctx.getIntWidth(E->getType()));
5824     if (SameSign && SameWidth)
5825       return Success(ECD->getInitVal(), E);
5826     else {
5827       // Get rid of mismatch (otherwise Success assertions will fail)
5828       // by computing a new value matching the type of E.
5829       llvm::APSInt Val = ECD->getInitVal();
5830       if (!SameSign)
5831         Val.setIsSigned(!ECD->getInitVal().isSigned());
5832       if (!SameWidth)
5833         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5834       return Success(Val, E);
5835     }
5836   }
5837   return false;
5838 }
5839 
5840 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5841 /// as GCC.
5842 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5843   // The following enum mimics the values returned by GCC.
5844   // FIXME: Does GCC differ between lvalue and rvalue references here?
5845   enum gcc_type_class {
5846     no_type_class = -1,
5847     void_type_class, integer_type_class, char_type_class,
5848     enumeral_type_class, boolean_type_class,
5849     pointer_type_class, reference_type_class, offset_type_class,
5850     real_type_class, complex_type_class,
5851     function_type_class, method_type_class,
5852     record_type_class, union_type_class,
5853     array_type_class, string_type_class,
5854     lang_type_class
5855   };
5856 
5857   // If no argument was supplied, default to "no_type_class". This isn't
5858   // ideal, however it is what gcc does.
5859   if (E->getNumArgs() == 0)
5860     return no_type_class;
5861 
5862   QualType ArgTy = E->getArg(0)->getType();
5863   if (ArgTy->isVoidType())
5864     return void_type_class;
5865   else if (ArgTy->isEnumeralType())
5866     return enumeral_type_class;
5867   else if (ArgTy->isBooleanType())
5868     return boolean_type_class;
5869   else if (ArgTy->isCharType())
5870     return string_type_class; // gcc doesn't appear to use char_type_class
5871   else if (ArgTy->isIntegerType())
5872     return integer_type_class;
5873   else if (ArgTy->isPointerType())
5874     return pointer_type_class;
5875   else if (ArgTy->isReferenceType())
5876     return reference_type_class;
5877   else if (ArgTy->isRealType())
5878     return real_type_class;
5879   else if (ArgTy->isComplexType())
5880     return complex_type_class;
5881   else if (ArgTy->isFunctionType())
5882     return function_type_class;
5883   else if (ArgTy->isStructureOrClassType())
5884     return record_type_class;
5885   else if (ArgTy->isUnionType())
5886     return union_type_class;
5887   else if (ArgTy->isArrayType())
5888     return array_type_class;
5889   else if (ArgTy->isUnionType())
5890     return union_type_class;
5891   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
5892     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
5893 }
5894 
5895 /// EvaluateBuiltinConstantPForLValue - Determine the result of
5896 /// __builtin_constant_p when applied to the given lvalue.
5897 ///
5898 /// An lvalue is only "constant" if it is a pointer or reference to the first
5899 /// character of a string literal.
5900 template<typename LValue>
5901 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
5902   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
5903   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5904 }
5905 
5906 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5907 /// GCC as we can manage.
5908 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5909   QualType ArgType = Arg->getType();
5910 
5911   // __builtin_constant_p always has one operand. The rules which gcc follows
5912   // are not precisely documented, but are as follows:
5913   //
5914   //  - If the operand is of integral, floating, complex or enumeration type,
5915   //    and can be folded to a known value of that type, it returns 1.
5916   //  - If the operand and can be folded to a pointer to the first character
5917   //    of a string literal (or such a pointer cast to an integral type), it
5918   //    returns 1.
5919   //
5920   // Otherwise, it returns 0.
5921   //
5922   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5923   // its support for this does not currently work.
5924   if (ArgType->isIntegralOrEnumerationType()) {
5925     Expr::EvalResult Result;
5926     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5927       return false;
5928 
5929     APValue &V = Result.Val;
5930     if (V.getKind() == APValue::Int)
5931       return true;
5932 
5933     return EvaluateBuiltinConstantPForLValue(V);
5934   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5935     return Arg->isEvaluatable(Ctx);
5936   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5937     LValue LV;
5938     Expr::EvalStatus Status;
5939     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
5940     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5941                           : EvaluatePointer(Arg, LV, Info)) &&
5942         !Status.HasSideEffects)
5943       return EvaluateBuiltinConstantPForLValue(LV);
5944   }
5945 
5946   // Anything else isn't considered to be sufficiently constant.
5947   return false;
5948 }
5949 
5950 /// Retrieves the "underlying object type" of the given expression,
5951 /// as used by __builtin_object_size.
5952 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5953   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5954     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5955       return VD->getType();
5956   } else if (const Expr *E = B.get<const Expr*>()) {
5957     if (isa<CompoundLiteralExpr>(E))
5958       return E->getType();
5959   }
5960 
5961   return QualType();
5962 }
5963 
5964 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
5965   LValue Base;
5966 
5967   {
5968     // The operand of __builtin_object_size is never evaluated for side-effects.
5969     // If there are any, but we can determine the pointed-to object anyway, then
5970     // ignore the side-effects.
5971     SpeculativeEvaluationRAII SpeculativeEval(Info);
5972     if (!EvaluatePointer(E->getArg(0), Base, Info))
5973       return false;
5974   }
5975 
5976   // If we can prove the base is null, lower to zero now.
5977   if (!Base.getLValueBase()) return Success(0, E);
5978 
5979   QualType T = GetObjectType(Base.getLValueBase());
5980   if (T.isNull() ||
5981       T->isIncompleteType() ||
5982       T->isFunctionType() ||
5983       T->isVariablyModifiedType() ||
5984       T->isDependentType())
5985     return Error(E);
5986 
5987   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5988   CharUnits Offset = Base.getLValueOffset();
5989 
5990   if (!Offset.isNegative() && Offset <= Size)
5991     Size -= Offset;
5992   else
5993     Size = CharUnits::Zero();
5994   return Success(Size, E);
5995 }
5996 
5997 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
5998   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
5999   default:
6000     return ExprEvaluatorBaseTy::VisitCallExpr(E);
6001 
6002   case Builtin::BI__builtin_object_size: {
6003     if (TryEvaluateBuiltinObjectSize(E))
6004       return true;
6005 
6006     // If evaluating the argument has side-effects, we can't determine the size
6007     // of the object, and so we lower it to unknown now. CodeGen relies on us to
6008     // handle all cases where the expression has side-effects.
6009     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6010       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6011         return Success(-1ULL, E);
6012       return Success(0, E);
6013     }
6014 
6015     // Expression had no side effects, but we couldn't statically determine the
6016     // size of the referenced object.
6017     switch (Info.EvalMode) {
6018     case EvalInfo::EM_ConstantExpression:
6019     case EvalInfo::EM_PotentialConstantExpression:
6020     case EvalInfo::EM_ConstantFold:
6021     case EvalInfo::EM_EvaluateForOverflow:
6022     case EvalInfo::EM_IgnoreSideEffects:
6023       return Error(E);
6024     case EvalInfo::EM_ConstantExpressionUnevaluated:
6025     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6026       return Success(-1ULL, E);
6027     }
6028   }
6029 
6030   case Builtin::BI__builtin_bswap16:
6031   case Builtin::BI__builtin_bswap32:
6032   case Builtin::BI__builtin_bswap64: {
6033     APSInt Val;
6034     if (!EvaluateInteger(E->getArg(0), Val, Info))
6035       return false;
6036 
6037     return Success(Val.byteSwap(), E);
6038   }
6039 
6040   case Builtin::BI__builtin_classify_type:
6041     return Success(EvaluateBuiltinClassifyType(E), E);
6042 
6043   // FIXME: BI__builtin_clrsb
6044   // FIXME: BI__builtin_clrsbl
6045   // FIXME: BI__builtin_clrsbll
6046 
6047   case Builtin::BI__builtin_clz:
6048   case Builtin::BI__builtin_clzl:
6049   case Builtin::BI__builtin_clzll: {
6050     APSInt Val;
6051     if (!EvaluateInteger(E->getArg(0), Val, Info))
6052       return false;
6053     if (!Val)
6054       return Error(E);
6055 
6056     return Success(Val.countLeadingZeros(), E);
6057   }
6058 
6059   case Builtin::BI__builtin_constant_p:
6060     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6061 
6062   case Builtin::BI__builtin_ctz:
6063   case Builtin::BI__builtin_ctzl:
6064   case Builtin::BI__builtin_ctzll: {
6065     APSInt Val;
6066     if (!EvaluateInteger(E->getArg(0), Val, Info))
6067       return false;
6068     if (!Val)
6069       return Error(E);
6070 
6071     return Success(Val.countTrailingZeros(), E);
6072   }
6073 
6074   case Builtin::BI__builtin_eh_return_data_regno: {
6075     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6076     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6077     return Success(Operand, E);
6078   }
6079 
6080   case Builtin::BI__builtin_expect:
6081     return Visit(E->getArg(0));
6082 
6083   case Builtin::BI__builtin_ffs:
6084   case Builtin::BI__builtin_ffsl:
6085   case Builtin::BI__builtin_ffsll: {
6086     APSInt Val;
6087     if (!EvaluateInteger(E->getArg(0), Val, Info))
6088       return false;
6089 
6090     unsigned N = Val.countTrailingZeros();
6091     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6092   }
6093 
6094   case Builtin::BI__builtin_fpclassify: {
6095     APFloat Val(0.0);
6096     if (!EvaluateFloat(E->getArg(5), Val, Info))
6097       return false;
6098     unsigned Arg;
6099     switch (Val.getCategory()) {
6100     case APFloat::fcNaN: Arg = 0; break;
6101     case APFloat::fcInfinity: Arg = 1; break;
6102     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6103     case APFloat::fcZero: Arg = 4; break;
6104     }
6105     return Visit(E->getArg(Arg));
6106   }
6107 
6108   case Builtin::BI__builtin_isinf_sign: {
6109     APFloat Val(0.0);
6110     return EvaluateFloat(E->getArg(0), Val, Info) &&
6111            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6112   }
6113 
6114   case Builtin::BI__builtin_isinf: {
6115     APFloat Val(0.0);
6116     return EvaluateFloat(E->getArg(0), Val, Info) &&
6117            Success(Val.isInfinity() ? 1 : 0, E);
6118   }
6119 
6120   case Builtin::BI__builtin_isfinite: {
6121     APFloat Val(0.0);
6122     return EvaluateFloat(E->getArg(0), Val, Info) &&
6123            Success(Val.isFinite() ? 1 : 0, E);
6124   }
6125 
6126   case Builtin::BI__builtin_isnan: {
6127     APFloat Val(0.0);
6128     return EvaluateFloat(E->getArg(0), Val, Info) &&
6129            Success(Val.isNaN() ? 1 : 0, E);
6130   }
6131 
6132   case Builtin::BI__builtin_isnormal: {
6133     APFloat Val(0.0);
6134     return EvaluateFloat(E->getArg(0), Val, Info) &&
6135            Success(Val.isNormal() ? 1 : 0, E);
6136   }
6137 
6138   case Builtin::BI__builtin_parity:
6139   case Builtin::BI__builtin_parityl:
6140   case Builtin::BI__builtin_parityll: {
6141     APSInt Val;
6142     if (!EvaluateInteger(E->getArg(0), Val, Info))
6143       return false;
6144 
6145     return Success(Val.countPopulation() % 2, E);
6146   }
6147 
6148   case Builtin::BI__builtin_popcount:
6149   case Builtin::BI__builtin_popcountl:
6150   case Builtin::BI__builtin_popcountll: {
6151     APSInt Val;
6152     if (!EvaluateInteger(E->getArg(0), Val, Info))
6153       return false;
6154 
6155     return Success(Val.countPopulation(), E);
6156   }
6157 
6158   case Builtin::BIstrlen:
6159     // A call to strlen is not a constant expression.
6160     if (Info.getLangOpts().CPlusPlus11)
6161       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6162         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6163     else
6164       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6165     // Fall through.
6166   case Builtin::BI__builtin_strlen: {
6167     // As an extension, we support __builtin_strlen() as a constant expression,
6168     // and support folding strlen() to a constant.
6169     LValue String;
6170     if (!EvaluatePointer(E->getArg(0), String, Info))
6171       return false;
6172 
6173     // Fast path: if it's a string literal, search the string value.
6174     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6175             String.getLValueBase().dyn_cast<const Expr *>())) {
6176       // The string literal may have embedded null characters. Find the first
6177       // one and truncate there.
6178       StringRef Str = S->getBytes();
6179       int64_t Off = String.Offset.getQuantity();
6180       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6181           S->getCharByteWidth() == 1) {
6182         Str = Str.substr(Off);
6183 
6184         StringRef::size_type Pos = Str.find(0);
6185         if (Pos != StringRef::npos)
6186           Str = Str.substr(0, Pos);
6187 
6188         return Success(Str.size(), E);
6189       }
6190 
6191       // Fall through to slow path to issue appropriate diagnostic.
6192     }
6193 
6194     // Slow path: scan the bytes of the string looking for the terminating 0.
6195     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6196     for (uint64_t Strlen = 0; /**/; ++Strlen) {
6197       APValue Char;
6198       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6199           !Char.isInt())
6200         return false;
6201       if (!Char.getInt())
6202         return Success(Strlen, E);
6203       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6204         return false;
6205     }
6206   }
6207 
6208   case Builtin::BI__atomic_always_lock_free:
6209   case Builtin::BI__atomic_is_lock_free:
6210   case Builtin::BI__c11_atomic_is_lock_free: {
6211     APSInt SizeVal;
6212     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6213       return false;
6214 
6215     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6216     // of two less than the maximum inline atomic width, we know it is
6217     // lock-free.  If the size isn't a power of two, or greater than the
6218     // maximum alignment where we promote atomics, we know it is not lock-free
6219     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
6220     // the answer can only be determined at runtime; for example, 16-byte
6221     // atomics have lock-free implementations on some, but not all,
6222     // x86-64 processors.
6223 
6224     // Check power-of-two.
6225     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6226     if (Size.isPowerOfTwo()) {
6227       // Check against inlining width.
6228       unsigned InlineWidthBits =
6229           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6230       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6231         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6232             Size == CharUnits::One() ||
6233             E->getArg(1)->isNullPointerConstant(Info.Ctx,
6234                                                 Expr::NPC_NeverValueDependent))
6235           // OK, we will inline appropriately-aligned operations of this size,
6236           // and _Atomic(T) is appropriately-aligned.
6237           return Success(1, E);
6238 
6239         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6240           castAs<PointerType>()->getPointeeType();
6241         if (!PointeeType->isIncompleteType() &&
6242             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6243           // OK, we will inline operations on this object.
6244           return Success(1, E);
6245         }
6246       }
6247     }
6248 
6249     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6250         Success(0, E) : Error(E);
6251   }
6252   }
6253 }
6254 
6255 static bool HasSameBase(const LValue &A, const LValue &B) {
6256   if (!A.getLValueBase())
6257     return !B.getLValueBase();
6258   if (!B.getLValueBase())
6259     return false;
6260 
6261   if (A.getLValueBase().getOpaqueValue() !=
6262       B.getLValueBase().getOpaqueValue()) {
6263     const Decl *ADecl = GetLValueBaseDecl(A);
6264     if (!ADecl)
6265       return false;
6266     const Decl *BDecl = GetLValueBaseDecl(B);
6267     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6268       return false;
6269   }
6270 
6271   return IsGlobalLValue(A.getLValueBase()) ||
6272          A.getLValueCallIndex() == B.getLValueCallIndex();
6273 }
6274 
6275 namespace {
6276 
6277 /// \brief Data recursive integer evaluator of certain binary operators.
6278 ///
6279 /// We use a data recursive algorithm for binary operators so that we are able
6280 /// to handle extreme cases of chained binary operators without causing stack
6281 /// overflow.
6282 class DataRecursiveIntBinOpEvaluator {
6283   struct EvalResult {
6284     APValue Val;
6285     bool Failed;
6286 
6287     EvalResult() : Failed(false) { }
6288 
6289     void swap(EvalResult &RHS) {
6290       Val.swap(RHS.Val);
6291       Failed = RHS.Failed;
6292       RHS.Failed = false;
6293     }
6294   };
6295 
6296   struct Job {
6297     const Expr *E;
6298     EvalResult LHSResult; // meaningful only for binary operator expression.
6299     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6300 
6301     Job() : StoredInfo(0) { }
6302     void startSpeculativeEval(EvalInfo &Info) {
6303       OldEvalStatus = Info.EvalStatus;
6304       Info.EvalStatus.Diag = 0;
6305       StoredInfo = &Info;
6306     }
6307     ~Job() {
6308       if (StoredInfo) {
6309         StoredInfo->EvalStatus = OldEvalStatus;
6310       }
6311     }
6312   private:
6313     EvalInfo *StoredInfo; // non-null if status changed.
6314     Expr::EvalStatus OldEvalStatus;
6315   };
6316 
6317   SmallVector<Job, 16> Queue;
6318 
6319   IntExprEvaluator &IntEval;
6320   EvalInfo &Info;
6321   APValue &FinalResult;
6322 
6323 public:
6324   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6325     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6326 
6327   /// \brief True if \param E is a binary operator that we are going to handle
6328   /// data recursively.
6329   /// We handle binary operators that are comma, logical, or that have operands
6330   /// with integral or enumeration type.
6331   static bool shouldEnqueue(const BinaryOperator *E) {
6332     return E->getOpcode() == BO_Comma ||
6333            E->isLogicalOp() ||
6334            (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6335             E->getRHS()->getType()->isIntegralOrEnumerationType());
6336   }
6337 
6338   bool Traverse(const BinaryOperator *E) {
6339     enqueue(E);
6340     EvalResult PrevResult;
6341     while (!Queue.empty())
6342       process(PrevResult);
6343 
6344     if (PrevResult.Failed) return false;
6345 
6346     FinalResult.swap(PrevResult.Val);
6347     return true;
6348   }
6349 
6350 private:
6351   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6352     return IntEval.Success(Value, E, Result);
6353   }
6354   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6355     return IntEval.Success(Value, E, Result);
6356   }
6357   bool Error(const Expr *E) {
6358     return IntEval.Error(E);
6359   }
6360   bool Error(const Expr *E, diag::kind D) {
6361     return IntEval.Error(E, D);
6362   }
6363 
6364   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6365     return Info.CCEDiag(E, D);
6366   }
6367 
6368   // \brief Returns true if visiting the RHS is necessary, false otherwise.
6369   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6370                          bool &SuppressRHSDiags);
6371 
6372   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6373                   const BinaryOperator *E, APValue &Result);
6374 
6375   void EvaluateExpr(const Expr *E, EvalResult &Result) {
6376     Result.Failed = !Evaluate(Result.Val, Info, E);
6377     if (Result.Failed)
6378       Result.Val = APValue();
6379   }
6380 
6381   void process(EvalResult &Result);
6382 
6383   void enqueue(const Expr *E) {
6384     E = E->IgnoreParens();
6385     Queue.resize(Queue.size()+1);
6386     Queue.back().E = E;
6387     Queue.back().Kind = Job::AnyExprKind;
6388   }
6389 };
6390 
6391 }
6392 
6393 bool DataRecursiveIntBinOpEvaluator::
6394        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6395                          bool &SuppressRHSDiags) {
6396   if (E->getOpcode() == BO_Comma) {
6397     // Ignore LHS but note if we could not evaluate it.
6398     if (LHSResult.Failed)
6399       return Info.noteSideEffect();
6400     return true;
6401   }
6402 
6403   if (E->isLogicalOp()) {
6404     bool LHSAsBool;
6405     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6406       // We were able to evaluate the LHS, see if we can get away with not
6407       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6408       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6409         Success(LHSAsBool, E, LHSResult.Val);
6410         return false; // Ignore RHS
6411       }
6412     } else {
6413       LHSResult.Failed = true;
6414 
6415       // Since we weren't able to evaluate the left hand side, it
6416       // must have had side effects.
6417       if (!Info.noteSideEffect())
6418         return false;
6419 
6420       // We can't evaluate the LHS; however, sometimes the result
6421       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6422       // Don't ignore RHS and suppress diagnostics from this arm.
6423       SuppressRHSDiags = true;
6424     }
6425 
6426     return true;
6427   }
6428 
6429   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6430          E->getRHS()->getType()->isIntegralOrEnumerationType());
6431 
6432   if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6433     return false; // Ignore RHS;
6434 
6435   return true;
6436 }
6437 
6438 bool DataRecursiveIntBinOpEvaluator::
6439        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6440                   const BinaryOperator *E, APValue &Result) {
6441   if (E->getOpcode() == BO_Comma) {
6442     if (RHSResult.Failed)
6443       return false;
6444     Result = RHSResult.Val;
6445     return true;
6446   }
6447 
6448   if (E->isLogicalOp()) {
6449     bool lhsResult, rhsResult;
6450     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6451     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6452 
6453     if (LHSIsOK) {
6454       if (RHSIsOK) {
6455         if (E->getOpcode() == BO_LOr)
6456           return Success(lhsResult || rhsResult, E, Result);
6457         else
6458           return Success(lhsResult && rhsResult, E, Result);
6459       }
6460     } else {
6461       if (RHSIsOK) {
6462         // We can't evaluate the LHS; however, sometimes the result
6463         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6464         if (rhsResult == (E->getOpcode() == BO_LOr))
6465           return Success(rhsResult, E, Result);
6466       }
6467     }
6468 
6469     return false;
6470   }
6471 
6472   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6473          E->getRHS()->getType()->isIntegralOrEnumerationType());
6474 
6475   if (LHSResult.Failed || RHSResult.Failed)
6476     return false;
6477 
6478   const APValue &LHSVal = LHSResult.Val;
6479   const APValue &RHSVal = RHSResult.Val;
6480 
6481   // Handle cases like (unsigned long)&a + 4.
6482   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6483     Result = LHSVal;
6484     CharUnits AdditionalOffset =
6485         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6486     if (E->getOpcode() == BO_Add)
6487       Result.getLValueOffset() += AdditionalOffset;
6488     else
6489       Result.getLValueOffset() -= AdditionalOffset;
6490     return true;
6491   }
6492 
6493   // Handle cases like 4 + (unsigned long)&a
6494   if (E->getOpcode() == BO_Add &&
6495       RHSVal.isLValue() && LHSVal.isInt()) {
6496     Result = RHSVal;
6497     Result.getLValueOffset() +=
6498         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6499     return true;
6500   }
6501 
6502   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6503     // Handle (intptr_t)&&A - (intptr_t)&&B.
6504     if (!LHSVal.getLValueOffset().isZero() ||
6505         !RHSVal.getLValueOffset().isZero())
6506       return false;
6507     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6508     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6509     if (!LHSExpr || !RHSExpr)
6510       return false;
6511     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6512     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6513     if (!LHSAddrExpr || !RHSAddrExpr)
6514       return false;
6515     // Make sure both labels come from the same function.
6516     if (LHSAddrExpr->getLabel()->getDeclContext() !=
6517         RHSAddrExpr->getLabel()->getDeclContext())
6518       return false;
6519     Result = APValue(LHSAddrExpr, RHSAddrExpr);
6520     return true;
6521   }
6522 
6523   // All the remaining cases expect both operands to be an integer
6524   if (!LHSVal.isInt() || !RHSVal.isInt())
6525     return Error(E);
6526 
6527   // Set up the width and signedness manually, in case it can't be deduced
6528   // from the operation we're performing.
6529   // FIXME: Don't do this in the cases where we can deduce it.
6530   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6531                E->getType()->isUnsignedIntegerOrEnumerationType());
6532   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6533                          RHSVal.getInt(), Value))
6534     return false;
6535   return Success(Value, E, Result);
6536 }
6537 
6538 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6539   Job &job = Queue.back();
6540 
6541   switch (job.Kind) {
6542     case Job::AnyExprKind: {
6543       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6544         if (shouldEnqueue(Bop)) {
6545           job.Kind = Job::BinOpKind;
6546           enqueue(Bop->getLHS());
6547           return;
6548         }
6549       }
6550 
6551       EvaluateExpr(job.E, Result);
6552       Queue.pop_back();
6553       return;
6554     }
6555 
6556     case Job::BinOpKind: {
6557       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6558       bool SuppressRHSDiags = false;
6559       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6560         Queue.pop_back();
6561         return;
6562       }
6563       if (SuppressRHSDiags)
6564         job.startSpeculativeEval(Info);
6565       job.LHSResult.swap(Result);
6566       job.Kind = Job::BinOpVisitedLHSKind;
6567       enqueue(Bop->getRHS());
6568       return;
6569     }
6570 
6571     case Job::BinOpVisitedLHSKind: {
6572       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6573       EvalResult RHS;
6574       RHS.swap(Result);
6575       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6576       Queue.pop_back();
6577       return;
6578     }
6579   }
6580 
6581   llvm_unreachable("Invalid Job::Kind!");
6582 }
6583 
6584 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6585   if (E->isAssignmentOp())
6586     return Error(E);
6587 
6588   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6589     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6590 
6591   QualType LHSTy = E->getLHS()->getType();
6592   QualType RHSTy = E->getRHS()->getType();
6593 
6594   if (LHSTy->isAnyComplexType()) {
6595     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
6596     ComplexValue LHS, RHS;
6597 
6598     bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6599     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6600       return false;
6601 
6602     if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6603       return false;
6604 
6605     if (LHS.isComplexFloat()) {
6606       APFloat::cmpResult CR_r =
6607         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6608       APFloat::cmpResult CR_i =
6609         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6610 
6611       if (E->getOpcode() == BO_EQ)
6612         return Success((CR_r == APFloat::cmpEqual &&
6613                         CR_i == APFloat::cmpEqual), E);
6614       else {
6615         assert(E->getOpcode() == BO_NE &&
6616                "Invalid complex comparison.");
6617         return Success(((CR_r == APFloat::cmpGreaterThan ||
6618                          CR_r == APFloat::cmpLessThan ||
6619                          CR_r == APFloat::cmpUnordered) ||
6620                         (CR_i == APFloat::cmpGreaterThan ||
6621                          CR_i == APFloat::cmpLessThan ||
6622                          CR_i == APFloat::cmpUnordered)), E);
6623       }
6624     } else {
6625       if (E->getOpcode() == BO_EQ)
6626         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6627                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6628       else {
6629         assert(E->getOpcode() == BO_NE &&
6630                "Invalid compex comparison.");
6631         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6632                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6633       }
6634     }
6635   }
6636 
6637   if (LHSTy->isRealFloatingType() &&
6638       RHSTy->isRealFloatingType()) {
6639     APFloat RHS(0.0), LHS(0.0);
6640 
6641     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6642     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6643       return false;
6644 
6645     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6646       return false;
6647 
6648     APFloat::cmpResult CR = LHS.compare(RHS);
6649 
6650     switch (E->getOpcode()) {
6651     default:
6652       llvm_unreachable("Invalid binary operator!");
6653     case BO_LT:
6654       return Success(CR == APFloat::cmpLessThan, E);
6655     case BO_GT:
6656       return Success(CR == APFloat::cmpGreaterThan, E);
6657     case BO_LE:
6658       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6659     case BO_GE:
6660       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6661                      E);
6662     case BO_EQ:
6663       return Success(CR == APFloat::cmpEqual, E);
6664     case BO_NE:
6665       return Success(CR == APFloat::cmpGreaterThan
6666                      || CR == APFloat::cmpLessThan
6667                      || CR == APFloat::cmpUnordered, E);
6668     }
6669   }
6670 
6671   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6672     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6673       LValue LHSValue, RHSValue;
6674 
6675       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6676       if (!LHSOK && Info.keepEvaluatingAfterFailure())
6677         return false;
6678 
6679       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6680         return false;
6681 
6682       // Reject differing bases from the normal codepath; we special-case
6683       // comparisons to null.
6684       if (!HasSameBase(LHSValue, RHSValue)) {
6685         if (E->getOpcode() == BO_Sub) {
6686           // Handle &&A - &&B.
6687           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6688             return false;
6689           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6690           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6691           if (!LHSExpr || !RHSExpr)
6692             return false;
6693           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6694           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6695           if (!LHSAddrExpr || !RHSAddrExpr)
6696             return false;
6697           // Make sure both labels come from the same function.
6698           if (LHSAddrExpr->getLabel()->getDeclContext() !=
6699               RHSAddrExpr->getLabel()->getDeclContext())
6700             return false;
6701           Result = APValue(LHSAddrExpr, RHSAddrExpr);
6702           return true;
6703         }
6704         // Inequalities and subtractions between unrelated pointers have
6705         // unspecified or undefined behavior.
6706         if (!E->isEqualityOp())
6707           return Error(E);
6708         // A constant address may compare equal to the address of a symbol.
6709         // The one exception is that address of an object cannot compare equal
6710         // to a null pointer constant.
6711         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6712             (!RHSValue.Base && !RHSValue.Offset.isZero()))
6713           return Error(E);
6714         // It's implementation-defined whether distinct literals will have
6715         // distinct addresses. In clang, the result of such a comparison is
6716         // unspecified, so it is not a constant expression. However, we do know
6717         // that the address of a literal will be non-null.
6718         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6719             LHSValue.Base && RHSValue.Base)
6720           return Error(E);
6721         // We can't tell whether weak symbols will end up pointing to the same
6722         // object.
6723         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6724           return Error(E);
6725         // Pointers with different bases cannot represent the same object.
6726         // (Note that clang defaults to -fmerge-all-constants, which can
6727         // lead to inconsistent results for comparisons involving the address
6728         // of a constant; this generally doesn't matter in practice.)
6729         return Success(E->getOpcode() == BO_NE, E);
6730       }
6731 
6732       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6733       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6734 
6735       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6736       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6737 
6738       if (E->getOpcode() == BO_Sub) {
6739         // C++11 [expr.add]p6:
6740         //   Unless both pointers point to elements of the same array object, or
6741         //   one past the last element of the array object, the behavior is
6742         //   undefined.
6743         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6744             !AreElementsOfSameArray(getType(LHSValue.Base),
6745                                     LHSDesignator, RHSDesignator))
6746           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6747 
6748         QualType Type = E->getLHS()->getType();
6749         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
6750 
6751         CharUnits ElementSize;
6752         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
6753           return false;
6754 
6755         // As an extension, a type may have zero size (empty struct or union in
6756         // C, array of zero length). Pointer subtraction in such cases has
6757         // undefined behavior, so is not constant.
6758         if (ElementSize.isZero()) {
6759           Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6760             << ElementType;
6761           return false;
6762         }
6763 
6764         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6765         // and produce incorrect results when it overflows. Such behavior
6766         // appears to be non-conforming, but is common, so perhaps we should
6767         // assume the standard intended for such cases to be undefined behavior
6768         // and check for them.
6769 
6770         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6771         // overflow in the final conversion to ptrdiff_t.
6772         APSInt LHS(
6773           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6774         APSInt RHS(
6775           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6776         APSInt ElemSize(
6777           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6778         APSInt TrueResult = (LHS - RHS) / ElemSize;
6779         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6780 
6781         if (Result.extend(65) != TrueResult)
6782           HandleOverflow(Info, E, TrueResult, E->getType());
6783         return Success(Result, E);
6784       }
6785 
6786       // C++11 [expr.rel]p3:
6787       //   Pointers to void (after pointer conversions) can be compared, with a
6788       //   result defined as follows: If both pointers represent the same
6789       //   address or are both the null pointer value, the result is true if the
6790       //   operator is <= or >= and false otherwise; otherwise the result is
6791       //   unspecified.
6792       // We interpret this as applying to pointers to *cv* void.
6793       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
6794           E->isRelationalOp())
6795         CCEDiag(E, diag::note_constexpr_void_comparison);
6796 
6797       // C++11 [expr.rel]p2:
6798       // - If two pointers point to non-static data members of the same object,
6799       //   or to subobjects or array elements fo such members, recursively, the
6800       //   pointer to the later declared member compares greater provided the
6801       //   two members have the same access control and provided their class is
6802       //   not a union.
6803       //   [...]
6804       // - Otherwise pointer comparisons are unspecified.
6805       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6806           E->isRelationalOp()) {
6807         bool WasArrayIndex;
6808         unsigned Mismatch =
6809           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6810                                  RHSDesignator, WasArrayIndex);
6811         // At the point where the designators diverge, the comparison has a
6812         // specified value if:
6813         //  - we are comparing array indices
6814         //  - we are comparing fields of a union, or fields with the same access
6815         // Otherwise, the result is unspecified and thus the comparison is not a
6816         // constant expression.
6817         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6818             Mismatch < RHSDesignator.Entries.size()) {
6819           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6820           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6821           if (!LF && !RF)
6822             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6823           else if (!LF)
6824             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6825               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6826               << RF->getParent() << RF;
6827           else if (!RF)
6828             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6829               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6830               << LF->getParent() << LF;
6831           else if (!LF->getParent()->isUnion() &&
6832                    LF->getAccess() != RF->getAccess())
6833             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6834               << LF << LF->getAccess() << RF << RF->getAccess()
6835               << LF->getParent();
6836         }
6837       }
6838 
6839       // The comparison here must be unsigned, and performed with the same
6840       // width as the pointer.
6841       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6842       uint64_t CompareLHS = LHSOffset.getQuantity();
6843       uint64_t CompareRHS = RHSOffset.getQuantity();
6844       assert(PtrSize <= 64 && "Unexpected pointer width");
6845       uint64_t Mask = ~0ULL >> (64 - PtrSize);
6846       CompareLHS &= Mask;
6847       CompareRHS &= Mask;
6848 
6849       // If there is a base and this is a relational operator, we can only
6850       // compare pointers within the object in question; otherwise, the result
6851       // depends on where the object is located in memory.
6852       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6853         QualType BaseTy = getType(LHSValue.Base);
6854         if (BaseTy->isIncompleteType())
6855           return Error(E);
6856         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6857         uint64_t OffsetLimit = Size.getQuantity();
6858         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6859           return Error(E);
6860       }
6861 
6862       switch (E->getOpcode()) {
6863       default: llvm_unreachable("missing comparison operator");
6864       case BO_LT: return Success(CompareLHS < CompareRHS, E);
6865       case BO_GT: return Success(CompareLHS > CompareRHS, E);
6866       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6867       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6868       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6869       case BO_NE: return Success(CompareLHS != CompareRHS, E);
6870       }
6871     }
6872   }
6873 
6874   if (LHSTy->isMemberPointerType()) {
6875     assert(E->isEqualityOp() && "unexpected member pointer operation");
6876     assert(RHSTy->isMemberPointerType() && "invalid comparison");
6877 
6878     MemberPtr LHSValue, RHSValue;
6879 
6880     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6881     if (!LHSOK && Info.keepEvaluatingAfterFailure())
6882       return false;
6883 
6884     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6885       return false;
6886 
6887     // C++11 [expr.eq]p2:
6888     //   If both operands are null, they compare equal. Otherwise if only one is
6889     //   null, they compare unequal.
6890     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6891       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6892       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6893     }
6894 
6895     //   Otherwise if either is a pointer to a virtual member function, the
6896     //   result is unspecified.
6897     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6898       if (MD->isVirtual())
6899         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6900     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6901       if (MD->isVirtual())
6902         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6903 
6904     //   Otherwise they compare equal if and only if they would refer to the
6905     //   same member of the same most derived object or the same subobject if
6906     //   they were dereferenced with a hypothetical object of the associated
6907     //   class type.
6908     bool Equal = LHSValue == RHSValue;
6909     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6910   }
6911 
6912   if (LHSTy->isNullPtrType()) {
6913     assert(E->isComparisonOp() && "unexpected nullptr operation");
6914     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6915     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6916     // are compared, the result is true of the operator is <=, >= or ==, and
6917     // false otherwise.
6918     BinaryOperator::Opcode Opcode = E->getOpcode();
6919     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6920   }
6921 
6922   assert((!LHSTy->isIntegralOrEnumerationType() ||
6923           !RHSTy->isIntegralOrEnumerationType()) &&
6924          "DataRecursiveIntBinOpEvaluator should have handled integral types");
6925   // We can't continue from here for non-integral types.
6926   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6927 }
6928 
6929 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
6930   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6931   //   result shall be the alignment of the referenced type."
6932   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6933     T = Ref->getPointeeType();
6934 
6935   // __alignof is defined to return the preferred alignment.
6936   return Info.Ctx.toCharUnitsFromBits(
6937     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6938 }
6939 
6940 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
6941   E = E->IgnoreParens();
6942 
6943   // The kinds of expressions that we have special-case logic here for
6944   // should be kept up to date with the special checks for those
6945   // expressions in Sema.
6946 
6947   // alignof decl is always accepted, even if it doesn't make sense: we default
6948   // to 1 in those cases.
6949   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6950     return Info.Ctx.getDeclAlign(DRE->getDecl(),
6951                                  /*RefAsPointee*/true);
6952 
6953   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6954     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6955                                  /*RefAsPointee*/true);
6956 
6957   return GetAlignOfType(E->getType());
6958 }
6959 
6960 
6961 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6962 /// a result as the expression's type.
6963 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6964                                     const UnaryExprOrTypeTraitExpr *E) {
6965   switch(E->getKind()) {
6966   case UETT_AlignOf: {
6967     if (E->isArgumentType())
6968       return Success(GetAlignOfType(E->getArgumentType()), E);
6969     else
6970       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
6971   }
6972 
6973   case UETT_VecStep: {
6974     QualType Ty = E->getTypeOfArgument();
6975 
6976     if (Ty->isVectorType()) {
6977       unsigned n = Ty->castAs<VectorType>()->getNumElements();
6978 
6979       // The vec_step built-in functions that take a 3-component
6980       // vector return 4. (OpenCL 1.1 spec 6.11.12)
6981       if (n == 3)
6982         n = 4;
6983 
6984       return Success(n, E);
6985     } else
6986       return Success(1, E);
6987   }
6988 
6989   case UETT_SizeOf: {
6990     QualType SrcTy = E->getTypeOfArgument();
6991     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6992     //   the result is the size of the referenced type."
6993     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6994       SrcTy = Ref->getPointeeType();
6995 
6996     CharUnits Sizeof;
6997     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
6998       return false;
6999     return Success(Sizeof, E);
7000   }
7001   }
7002 
7003   llvm_unreachable("unknown expr/type trait");
7004 }
7005 
7006 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7007   CharUnits Result;
7008   unsigned n = OOE->getNumComponents();
7009   if (n == 0)
7010     return Error(OOE);
7011   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7012   for (unsigned i = 0; i != n; ++i) {
7013     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7014     switch (ON.getKind()) {
7015     case OffsetOfExpr::OffsetOfNode::Array: {
7016       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7017       APSInt IdxResult;
7018       if (!EvaluateInteger(Idx, IdxResult, Info))
7019         return false;
7020       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7021       if (!AT)
7022         return Error(OOE);
7023       CurrentType = AT->getElementType();
7024       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7025       Result += IdxResult.getSExtValue() * ElementSize;
7026       break;
7027     }
7028 
7029     case OffsetOfExpr::OffsetOfNode::Field: {
7030       FieldDecl *MemberDecl = ON.getField();
7031       const RecordType *RT = CurrentType->getAs<RecordType>();
7032       if (!RT)
7033         return Error(OOE);
7034       RecordDecl *RD = RT->getDecl();
7035       if (RD->isInvalidDecl()) return false;
7036       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7037       unsigned i = MemberDecl->getFieldIndex();
7038       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7039       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7040       CurrentType = MemberDecl->getType().getNonReferenceType();
7041       break;
7042     }
7043 
7044     case OffsetOfExpr::OffsetOfNode::Identifier:
7045       llvm_unreachable("dependent __builtin_offsetof");
7046 
7047     case OffsetOfExpr::OffsetOfNode::Base: {
7048       CXXBaseSpecifier *BaseSpec = ON.getBase();
7049       if (BaseSpec->isVirtual())
7050         return Error(OOE);
7051 
7052       // Find the layout of the class whose base we are looking into.
7053       const RecordType *RT = CurrentType->getAs<RecordType>();
7054       if (!RT)
7055         return Error(OOE);
7056       RecordDecl *RD = RT->getDecl();
7057       if (RD->isInvalidDecl()) return false;
7058       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7059 
7060       // Find the base class itself.
7061       CurrentType = BaseSpec->getType();
7062       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7063       if (!BaseRT)
7064         return Error(OOE);
7065 
7066       // Add the offset to the base.
7067       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7068       break;
7069     }
7070     }
7071   }
7072   return Success(Result, OOE);
7073 }
7074 
7075 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7076   switch (E->getOpcode()) {
7077   default:
7078     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7079     // See C99 6.6p3.
7080     return Error(E);
7081   case UO_Extension:
7082     // FIXME: Should extension allow i-c-e extension expressions in its scope?
7083     // If so, we could clear the diagnostic ID.
7084     return Visit(E->getSubExpr());
7085   case UO_Plus:
7086     // The result is just the value.
7087     return Visit(E->getSubExpr());
7088   case UO_Minus: {
7089     if (!Visit(E->getSubExpr()))
7090       return false;
7091     if (!Result.isInt()) return Error(E);
7092     const APSInt &Value = Result.getInt();
7093     if (Value.isSigned() && Value.isMinSignedValue())
7094       HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7095                      E->getType());
7096     return Success(-Value, E);
7097   }
7098   case UO_Not: {
7099     if (!Visit(E->getSubExpr()))
7100       return false;
7101     if (!Result.isInt()) return Error(E);
7102     return Success(~Result.getInt(), E);
7103   }
7104   case UO_LNot: {
7105     bool bres;
7106     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7107       return false;
7108     return Success(!bres, E);
7109   }
7110   }
7111 }
7112 
7113 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7114 /// result type is integer.
7115 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7116   const Expr *SubExpr = E->getSubExpr();
7117   QualType DestType = E->getType();
7118   QualType SrcType = SubExpr->getType();
7119 
7120   switch (E->getCastKind()) {
7121   case CK_BaseToDerived:
7122   case CK_DerivedToBase:
7123   case CK_UncheckedDerivedToBase:
7124   case CK_Dynamic:
7125   case CK_ToUnion:
7126   case CK_ArrayToPointerDecay:
7127   case CK_FunctionToPointerDecay:
7128   case CK_NullToPointer:
7129   case CK_NullToMemberPointer:
7130   case CK_BaseToDerivedMemberPointer:
7131   case CK_DerivedToBaseMemberPointer:
7132   case CK_ReinterpretMemberPointer:
7133   case CK_ConstructorConversion:
7134   case CK_IntegralToPointer:
7135   case CK_ToVoid:
7136   case CK_VectorSplat:
7137   case CK_IntegralToFloating:
7138   case CK_FloatingCast:
7139   case CK_CPointerToObjCPointerCast:
7140   case CK_BlockPointerToObjCPointerCast:
7141   case CK_AnyPointerToBlockPointerCast:
7142   case CK_ObjCObjectLValueCast:
7143   case CK_FloatingRealToComplex:
7144   case CK_FloatingComplexToReal:
7145   case CK_FloatingComplexCast:
7146   case CK_FloatingComplexToIntegralComplex:
7147   case CK_IntegralRealToComplex:
7148   case CK_IntegralComplexCast:
7149   case CK_IntegralComplexToFloatingComplex:
7150   case CK_BuiltinFnToFnPtr:
7151   case CK_ZeroToOCLEvent:
7152   case CK_NonAtomicToAtomic:
7153   case CK_AddressSpaceConversion:
7154     llvm_unreachable("invalid cast kind for integral value");
7155 
7156   case CK_BitCast:
7157   case CK_Dependent:
7158   case CK_LValueBitCast:
7159   case CK_ARCProduceObject:
7160   case CK_ARCConsumeObject:
7161   case CK_ARCReclaimReturnedObject:
7162   case CK_ARCExtendBlockObject:
7163   case CK_CopyAndAutoreleaseBlockObject:
7164     return Error(E);
7165 
7166   case CK_UserDefinedConversion:
7167   case CK_LValueToRValue:
7168   case CK_AtomicToNonAtomic:
7169   case CK_NoOp:
7170     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7171 
7172   case CK_MemberPointerToBoolean:
7173   case CK_PointerToBoolean:
7174   case CK_IntegralToBoolean:
7175   case CK_FloatingToBoolean:
7176   case CK_FloatingComplexToBoolean:
7177   case CK_IntegralComplexToBoolean: {
7178     bool BoolResult;
7179     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7180       return false;
7181     return Success(BoolResult, E);
7182   }
7183 
7184   case CK_IntegralCast: {
7185     if (!Visit(SubExpr))
7186       return false;
7187 
7188     if (!Result.isInt()) {
7189       // Allow casts of address-of-label differences if they are no-ops
7190       // or narrowing.  (The narrowing case isn't actually guaranteed to
7191       // be constant-evaluatable except in some narrow cases which are hard
7192       // to detect here.  We let it through on the assumption the user knows
7193       // what they are doing.)
7194       if (Result.isAddrLabelDiff())
7195         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7196       // Only allow casts of lvalues if they are lossless.
7197       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7198     }
7199 
7200     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7201                                       Result.getInt()), E);
7202   }
7203 
7204   case CK_PointerToIntegral: {
7205     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7206 
7207     LValue LV;
7208     if (!EvaluatePointer(SubExpr, LV, Info))
7209       return false;
7210 
7211     if (LV.getLValueBase()) {
7212       // Only allow based lvalue casts if they are lossless.
7213       // FIXME: Allow a larger integer size than the pointer size, and allow
7214       // narrowing back down to pointer width in subsequent integral casts.
7215       // FIXME: Check integer type's active bits, not its type size.
7216       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7217         return Error(E);
7218 
7219       LV.Designator.setInvalid();
7220       LV.moveInto(Result);
7221       return true;
7222     }
7223 
7224     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7225                                          SrcType);
7226     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7227   }
7228 
7229   case CK_IntegralComplexToReal: {
7230     ComplexValue C;
7231     if (!EvaluateComplex(SubExpr, C, Info))
7232       return false;
7233     return Success(C.getComplexIntReal(), E);
7234   }
7235 
7236   case CK_FloatingToIntegral: {
7237     APFloat F(0.0);
7238     if (!EvaluateFloat(SubExpr, F, Info))
7239       return false;
7240 
7241     APSInt Value;
7242     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7243       return false;
7244     return Success(Value, E);
7245   }
7246   }
7247 
7248   llvm_unreachable("unknown cast resulting in integral value");
7249 }
7250 
7251 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7252   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7253     ComplexValue LV;
7254     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7255       return false;
7256     if (!LV.isComplexInt())
7257       return Error(E);
7258     return Success(LV.getComplexIntReal(), E);
7259   }
7260 
7261   return Visit(E->getSubExpr());
7262 }
7263 
7264 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7265   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7266     ComplexValue LV;
7267     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7268       return false;
7269     if (!LV.isComplexInt())
7270       return Error(E);
7271     return Success(LV.getComplexIntImag(), E);
7272   }
7273 
7274   VisitIgnoredValue(E->getSubExpr());
7275   return Success(0, E);
7276 }
7277 
7278 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7279   return Success(E->getPackLength(), E);
7280 }
7281 
7282 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7283   return Success(E->getValue(), E);
7284 }
7285 
7286 //===----------------------------------------------------------------------===//
7287 // Float Evaluation
7288 //===----------------------------------------------------------------------===//
7289 
7290 namespace {
7291 class FloatExprEvaluator
7292   : public ExprEvaluatorBase<FloatExprEvaluator> {
7293   APFloat &Result;
7294 public:
7295   FloatExprEvaluator(EvalInfo &info, APFloat &result)
7296     : ExprEvaluatorBaseTy(info), Result(result) {}
7297 
7298   bool Success(const APValue &V, const Expr *e) {
7299     Result = V.getFloat();
7300     return true;
7301   }
7302 
7303   bool ZeroInitialization(const Expr *E) {
7304     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7305     return true;
7306   }
7307 
7308   bool VisitCallExpr(const CallExpr *E);
7309 
7310   bool VisitUnaryOperator(const UnaryOperator *E);
7311   bool VisitBinaryOperator(const BinaryOperator *E);
7312   bool VisitFloatingLiteral(const FloatingLiteral *E);
7313   bool VisitCastExpr(const CastExpr *E);
7314 
7315   bool VisitUnaryReal(const UnaryOperator *E);
7316   bool VisitUnaryImag(const UnaryOperator *E);
7317 
7318   // FIXME: Missing: array subscript of vector, member of vector
7319 };
7320 } // end anonymous namespace
7321 
7322 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7323   assert(E->isRValue() && E->getType()->isRealFloatingType());
7324   return FloatExprEvaluator(Info, Result).Visit(E);
7325 }
7326 
7327 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7328                                   QualType ResultTy,
7329                                   const Expr *Arg,
7330                                   bool SNaN,
7331                                   llvm::APFloat &Result) {
7332   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7333   if (!S) return false;
7334 
7335   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7336 
7337   llvm::APInt fill;
7338 
7339   // Treat empty strings as if they were zero.
7340   if (S->getString().empty())
7341     fill = llvm::APInt(32, 0);
7342   else if (S->getString().getAsInteger(0, fill))
7343     return false;
7344 
7345   if (SNaN)
7346     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7347   else
7348     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7349   return true;
7350 }
7351 
7352 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7353   switch (E->getBuiltinCallee()) {
7354   default:
7355     return ExprEvaluatorBaseTy::VisitCallExpr(E);
7356 
7357   case Builtin::BI__builtin_huge_val:
7358   case Builtin::BI__builtin_huge_valf:
7359   case Builtin::BI__builtin_huge_vall:
7360   case Builtin::BI__builtin_inf:
7361   case Builtin::BI__builtin_inff:
7362   case Builtin::BI__builtin_infl: {
7363     const llvm::fltSemantics &Sem =
7364       Info.Ctx.getFloatTypeSemantics(E->getType());
7365     Result = llvm::APFloat::getInf(Sem);
7366     return true;
7367   }
7368 
7369   case Builtin::BI__builtin_nans:
7370   case Builtin::BI__builtin_nansf:
7371   case Builtin::BI__builtin_nansl:
7372     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7373                                true, Result))
7374       return Error(E);
7375     return true;
7376 
7377   case Builtin::BI__builtin_nan:
7378   case Builtin::BI__builtin_nanf:
7379   case Builtin::BI__builtin_nanl:
7380     // If this is __builtin_nan() turn this into a nan, otherwise we
7381     // can't constant fold it.
7382     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7383                                false, Result))
7384       return Error(E);
7385     return true;
7386 
7387   case Builtin::BI__builtin_fabs:
7388   case Builtin::BI__builtin_fabsf:
7389   case Builtin::BI__builtin_fabsl:
7390     if (!EvaluateFloat(E->getArg(0), Result, Info))
7391       return false;
7392 
7393     if (Result.isNegative())
7394       Result.changeSign();
7395     return true;
7396 
7397   // FIXME: Builtin::BI__builtin_powi
7398   // FIXME: Builtin::BI__builtin_powif
7399   // FIXME: Builtin::BI__builtin_powil
7400 
7401   case Builtin::BI__builtin_copysign:
7402   case Builtin::BI__builtin_copysignf:
7403   case Builtin::BI__builtin_copysignl: {
7404     APFloat RHS(0.);
7405     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7406         !EvaluateFloat(E->getArg(1), RHS, Info))
7407       return false;
7408     Result.copySign(RHS);
7409     return true;
7410   }
7411   }
7412 }
7413 
7414 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7415   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7416     ComplexValue CV;
7417     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7418       return false;
7419     Result = CV.FloatReal;
7420     return true;
7421   }
7422 
7423   return Visit(E->getSubExpr());
7424 }
7425 
7426 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7427   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7428     ComplexValue CV;
7429     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7430       return false;
7431     Result = CV.FloatImag;
7432     return true;
7433   }
7434 
7435   VisitIgnoredValue(E->getSubExpr());
7436   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7437   Result = llvm::APFloat::getZero(Sem);
7438   return true;
7439 }
7440 
7441 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7442   switch (E->getOpcode()) {
7443   default: return Error(E);
7444   case UO_Plus:
7445     return EvaluateFloat(E->getSubExpr(), Result, Info);
7446   case UO_Minus:
7447     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7448       return false;
7449     Result.changeSign();
7450     return true;
7451   }
7452 }
7453 
7454 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7455   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7456     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7457 
7458   APFloat RHS(0.0);
7459   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7460   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7461     return false;
7462   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7463          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7464 }
7465 
7466 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7467   Result = E->getValue();
7468   return true;
7469 }
7470 
7471 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7472   const Expr* SubExpr = E->getSubExpr();
7473 
7474   switch (E->getCastKind()) {
7475   default:
7476     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7477 
7478   case CK_IntegralToFloating: {
7479     APSInt IntResult;
7480     return EvaluateInteger(SubExpr, IntResult, Info) &&
7481            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7482                                 E->getType(), Result);
7483   }
7484 
7485   case CK_FloatingCast: {
7486     if (!Visit(SubExpr))
7487       return false;
7488     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7489                                   Result);
7490   }
7491 
7492   case CK_FloatingComplexToReal: {
7493     ComplexValue V;
7494     if (!EvaluateComplex(SubExpr, V, Info))
7495       return false;
7496     Result = V.getComplexFloatReal();
7497     return true;
7498   }
7499   }
7500 }
7501 
7502 //===----------------------------------------------------------------------===//
7503 // Complex Evaluation (for float and integer)
7504 //===----------------------------------------------------------------------===//
7505 
7506 namespace {
7507 class ComplexExprEvaluator
7508   : public ExprEvaluatorBase<ComplexExprEvaluator> {
7509   ComplexValue &Result;
7510 
7511 public:
7512   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7513     : ExprEvaluatorBaseTy(info), Result(Result) {}
7514 
7515   bool Success(const APValue &V, const Expr *e) {
7516     Result.setFrom(V);
7517     return true;
7518   }
7519 
7520   bool ZeroInitialization(const Expr *E);
7521 
7522   //===--------------------------------------------------------------------===//
7523   //                            Visitor Methods
7524   //===--------------------------------------------------------------------===//
7525 
7526   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7527   bool VisitCastExpr(const CastExpr *E);
7528   bool VisitBinaryOperator(const BinaryOperator *E);
7529   bool VisitUnaryOperator(const UnaryOperator *E);
7530   bool VisitInitListExpr(const InitListExpr *E);
7531 };
7532 } // end anonymous namespace
7533 
7534 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7535                             EvalInfo &Info) {
7536   assert(E->isRValue() && E->getType()->isAnyComplexType());
7537   return ComplexExprEvaluator(Info, Result).Visit(E);
7538 }
7539 
7540 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7541   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7542   if (ElemTy->isRealFloatingType()) {
7543     Result.makeComplexFloat();
7544     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7545     Result.FloatReal = Zero;
7546     Result.FloatImag = Zero;
7547   } else {
7548     Result.makeComplexInt();
7549     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7550     Result.IntReal = Zero;
7551     Result.IntImag = Zero;
7552   }
7553   return true;
7554 }
7555 
7556 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7557   const Expr* SubExpr = E->getSubExpr();
7558 
7559   if (SubExpr->getType()->isRealFloatingType()) {
7560     Result.makeComplexFloat();
7561     APFloat &Imag = Result.FloatImag;
7562     if (!EvaluateFloat(SubExpr, Imag, Info))
7563       return false;
7564 
7565     Result.FloatReal = APFloat(Imag.getSemantics());
7566     return true;
7567   } else {
7568     assert(SubExpr->getType()->isIntegerType() &&
7569            "Unexpected imaginary literal.");
7570 
7571     Result.makeComplexInt();
7572     APSInt &Imag = Result.IntImag;
7573     if (!EvaluateInteger(SubExpr, Imag, Info))
7574       return false;
7575 
7576     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7577     return true;
7578   }
7579 }
7580 
7581 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7582 
7583   switch (E->getCastKind()) {
7584   case CK_BitCast:
7585   case CK_BaseToDerived:
7586   case CK_DerivedToBase:
7587   case CK_UncheckedDerivedToBase:
7588   case CK_Dynamic:
7589   case CK_ToUnion:
7590   case CK_ArrayToPointerDecay:
7591   case CK_FunctionToPointerDecay:
7592   case CK_NullToPointer:
7593   case CK_NullToMemberPointer:
7594   case CK_BaseToDerivedMemberPointer:
7595   case CK_DerivedToBaseMemberPointer:
7596   case CK_MemberPointerToBoolean:
7597   case CK_ReinterpretMemberPointer:
7598   case CK_ConstructorConversion:
7599   case CK_IntegralToPointer:
7600   case CK_PointerToIntegral:
7601   case CK_PointerToBoolean:
7602   case CK_ToVoid:
7603   case CK_VectorSplat:
7604   case CK_IntegralCast:
7605   case CK_IntegralToBoolean:
7606   case CK_IntegralToFloating:
7607   case CK_FloatingToIntegral:
7608   case CK_FloatingToBoolean:
7609   case CK_FloatingCast:
7610   case CK_CPointerToObjCPointerCast:
7611   case CK_BlockPointerToObjCPointerCast:
7612   case CK_AnyPointerToBlockPointerCast:
7613   case CK_ObjCObjectLValueCast:
7614   case CK_FloatingComplexToReal:
7615   case CK_FloatingComplexToBoolean:
7616   case CK_IntegralComplexToReal:
7617   case CK_IntegralComplexToBoolean:
7618   case CK_ARCProduceObject:
7619   case CK_ARCConsumeObject:
7620   case CK_ARCReclaimReturnedObject:
7621   case CK_ARCExtendBlockObject:
7622   case CK_CopyAndAutoreleaseBlockObject:
7623   case CK_BuiltinFnToFnPtr:
7624   case CK_ZeroToOCLEvent:
7625   case CK_NonAtomicToAtomic:
7626   case CK_AddressSpaceConversion:
7627     llvm_unreachable("invalid cast kind for complex value");
7628 
7629   case CK_LValueToRValue:
7630   case CK_AtomicToNonAtomic:
7631   case CK_NoOp:
7632     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7633 
7634   case CK_Dependent:
7635   case CK_LValueBitCast:
7636   case CK_UserDefinedConversion:
7637     return Error(E);
7638 
7639   case CK_FloatingRealToComplex: {
7640     APFloat &Real = Result.FloatReal;
7641     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7642       return false;
7643 
7644     Result.makeComplexFloat();
7645     Result.FloatImag = APFloat(Real.getSemantics());
7646     return true;
7647   }
7648 
7649   case CK_FloatingComplexCast: {
7650     if (!Visit(E->getSubExpr()))
7651       return false;
7652 
7653     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7654     QualType From
7655       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7656 
7657     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7658            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7659   }
7660 
7661   case CK_FloatingComplexToIntegralComplex: {
7662     if (!Visit(E->getSubExpr()))
7663       return false;
7664 
7665     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7666     QualType From
7667       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7668     Result.makeComplexInt();
7669     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7670                                 To, Result.IntReal) &&
7671            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7672                                 To, Result.IntImag);
7673   }
7674 
7675   case CK_IntegralRealToComplex: {
7676     APSInt &Real = Result.IntReal;
7677     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7678       return false;
7679 
7680     Result.makeComplexInt();
7681     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7682     return true;
7683   }
7684 
7685   case CK_IntegralComplexCast: {
7686     if (!Visit(E->getSubExpr()))
7687       return false;
7688 
7689     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7690     QualType From
7691       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7692 
7693     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7694     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7695     return true;
7696   }
7697 
7698   case CK_IntegralComplexToFloatingComplex: {
7699     if (!Visit(E->getSubExpr()))
7700       return false;
7701 
7702     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7703     QualType From
7704       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7705     Result.makeComplexFloat();
7706     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7707                                 To, Result.FloatReal) &&
7708            HandleIntToFloatCast(Info, E, From, Result.IntImag,
7709                                 To, Result.FloatImag);
7710   }
7711   }
7712 
7713   llvm_unreachable("unknown cast resulting in complex value");
7714 }
7715 
7716 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7717   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7718     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7719 
7720   bool LHSOK = Visit(E->getLHS());
7721   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7722     return false;
7723 
7724   ComplexValue RHS;
7725   if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7726     return false;
7727 
7728   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7729          "Invalid operands to binary operator.");
7730   switch (E->getOpcode()) {
7731   default: return Error(E);
7732   case BO_Add:
7733     if (Result.isComplexFloat()) {
7734       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7735                                        APFloat::rmNearestTiesToEven);
7736       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7737                                        APFloat::rmNearestTiesToEven);
7738     } else {
7739       Result.getComplexIntReal() += RHS.getComplexIntReal();
7740       Result.getComplexIntImag() += RHS.getComplexIntImag();
7741     }
7742     break;
7743   case BO_Sub:
7744     if (Result.isComplexFloat()) {
7745       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7746                                             APFloat::rmNearestTiesToEven);
7747       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7748                                             APFloat::rmNearestTiesToEven);
7749     } else {
7750       Result.getComplexIntReal() -= RHS.getComplexIntReal();
7751       Result.getComplexIntImag() -= RHS.getComplexIntImag();
7752     }
7753     break;
7754   case BO_Mul:
7755     if (Result.isComplexFloat()) {
7756       ComplexValue LHS = Result;
7757       APFloat &LHS_r = LHS.getComplexFloatReal();
7758       APFloat &LHS_i = LHS.getComplexFloatImag();
7759       APFloat &RHS_r = RHS.getComplexFloatReal();
7760       APFloat &RHS_i = RHS.getComplexFloatImag();
7761 
7762       APFloat Tmp = LHS_r;
7763       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7764       Result.getComplexFloatReal() = Tmp;
7765       Tmp = LHS_i;
7766       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7767       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7768 
7769       Tmp = LHS_r;
7770       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7771       Result.getComplexFloatImag() = Tmp;
7772       Tmp = LHS_i;
7773       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7774       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7775     } else {
7776       ComplexValue LHS = Result;
7777       Result.getComplexIntReal() =
7778         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7779          LHS.getComplexIntImag() * RHS.getComplexIntImag());
7780       Result.getComplexIntImag() =
7781         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7782          LHS.getComplexIntImag() * RHS.getComplexIntReal());
7783     }
7784     break;
7785   case BO_Div:
7786     if (Result.isComplexFloat()) {
7787       ComplexValue LHS = Result;
7788       APFloat &LHS_r = LHS.getComplexFloatReal();
7789       APFloat &LHS_i = LHS.getComplexFloatImag();
7790       APFloat &RHS_r = RHS.getComplexFloatReal();
7791       APFloat &RHS_i = RHS.getComplexFloatImag();
7792       APFloat &Res_r = Result.getComplexFloatReal();
7793       APFloat &Res_i = Result.getComplexFloatImag();
7794 
7795       APFloat Den = RHS_r;
7796       Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7797       APFloat Tmp = RHS_i;
7798       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7799       Den.add(Tmp, APFloat::rmNearestTiesToEven);
7800 
7801       Res_r = LHS_r;
7802       Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7803       Tmp = LHS_i;
7804       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7805       Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7806       Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7807 
7808       Res_i = LHS_i;
7809       Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7810       Tmp = LHS_r;
7811       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7812       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7813       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7814     } else {
7815       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7816         return Error(E, diag::note_expr_divide_by_zero);
7817 
7818       ComplexValue LHS = Result;
7819       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7820         RHS.getComplexIntImag() * RHS.getComplexIntImag();
7821       Result.getComplexIntReal() =
7822         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7823          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7824       Result.getComplexIntImag() =
7825         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7826          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7827     }
7828     break;
7829   }
7830 
7831   return true;
7832 }
7833 
7834 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7835   // Get the operand value into 'Result'.
7836   if (!Visit(E->getSubExpr()))
7837     return false;
7838 
7839   switch (E->getOpcode()) {
7840   default:
7841     return Error(E);
7842   case UO_Extension:
7843     return true;
7844   case UO_Plus:
7845     // The result is always just the subexpr.
7846     return true;
7847   case UO_Minus:
7848     if (Result.isComplexFloat()) {
7849       Result.getComplexFloatReal().changeSign();
7850       Result.getComplexFloatImag().changeSign();
7851     }
7852     else {
7853       Result.getComplexIntReal() = -Result.getComplexIntReal();
7854       Result.getComplexIntImag() = -Result.getComplexIntImag();
7855     }
7856     return true;
7857   case UO_Not:
7858     if (Result.isComplexFloat())
7859       Result.getComplexFloatImag().changeSign();
7860     else
7861       Result.getComplexIntImag() = -Result.getComplexIntImag();
7862     return true;
7863   }
7864 }
7865 
7866 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7867   if (E->getNumInits() == 2) {
7868     if (E->getType()->isComplexType()) {
7869       Result.makeComplexFloat();
7870       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7871         return false;
7872       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7873         return false;
7874     } else {
7875       Result.makeComplexInt();
7876       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7877         return false;
7878       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7879         return false;
7880     }
7881     return true;
7882   }
7883   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7884 }
7885 
7886 //===----------------------------------------------------------------------===//
7887 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7888 // implicit conversion.
7889 //===----------------------------------------------------------------------===//
7890 
7891 namespace {
7892 class AtomicExprEvaluator :
7893     public ExprEvaluatorBase<AtomicExprEvaluator> {
7894   APValue &Result;
7895 public:
7896   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7897       : ExprEvaluatorBaseTy(Info), Result(Result) {}
7898 
7899   bool Success(const APValue &V, const Expr *E) {
7900     Result = V;
7901     return true;
7902   }
7903 
7904   bool ZeroInitialization(const Expr *E) {
7905     ImplicitValueInitExpr VIE(
7906         E->getType()->castAs<AtomicType>()->getValueType());
7907     return Evaluate(Result, Info, &VIE);
7908   }
7909 
7910   bool VisitCastExpr(const CastExpr *E) {
7911     switch (E->getCastKind()) {
7912     default:
7913       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7914     case CK_NonAtomicToAtomic:
7915       return Evaluate(Result, Info, E->getSubExpr());
7916     }
7917   }
7918 };
7919 } // end anonymous namespace
7920 
7921 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7922   assert(E->isRValue() && E->getType()->isAtomicType());
7923   return AtomicExprEvaluator(Info, Result).Visit(E);
7924 }
7925 
7926 //===----------------------------------------------------------------------===//
7927 // Void expression evaluation, primarily for a cast to void on the LHS of a
7928 // comma operator
7929 //===----------------------------------------------------------------------===//
7930 
7931 namespace {
7932 class VoidExprEvaluator
7933   : public ExprEvaluatorBase<VoidExprEvaluator> {
7934 public:
7935   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7936 
7937   bool Success(const APValue &V, const Expr *e) { return true; }
7938 
7939   bool VisitCastExpr(const CastExpr *E) {
7940     switch (E->getCastKind()) {
7941     default:
7942       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7943     case CK_ToVoid:
7944       VisitIgnoredValue(E->getSubExpr());
7945       return true;
7946     }
7947   }
7948 };
7949 } // end anonymous namespace
7950 
7951 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7952   assert(E->isRValue() && E->getType()->isVoidType());
7953   return VoidExprEvaluator(Info).Visit(E);
7954 }
7955 
7956 //===----------------------------------------------------------------------===//
7957 // Top level Expr::EvaluateAsRValue method.
7958 //===----------------------------------------------------------------------===//
7959 
7960 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
7961   // In C, function designators are not lvalues, but we evaluate them as if they
7962   // are.
7963   QualType T = E->getType();
7964   if (E->isGLValue() || T->isFunctionType()) {
7965     LValue LV;
7966     if (!EvaluateLValue(E, LV, Info))
7967       return false;
7968     LV.moveInto(Result);
7969   } else if (T->isVectorType()) {
7970     if (!EvaluateVector(E, Result, Info))
7971       return false;
7972   } else if (T->isIntegralOrEnumerationType()) {
7973     if (!IntExprEvaluator(Info, Result).Visit(E))
7974       return false;
7975   } else if (T->hasPointerRepresentation()) {
7976     LValue LV;
7977     if (!EvaluatePointer(E, LV, Info))
7978       return false;
7979     LV.moveInto(Result);
7980   } else if (T->isRealFloatingType()) {
7981     llvm::APFloat F(0.0);
7982     if (!EvaluateFloat(E, F, Info))
7983       return false;
7984     Result = APValue(F);
7985   } else if (T->isAnyComplexType()) {
7986     ComplexValue C;
7987     if (!EvaluateComplex(E, C, Info))
7988       return false;
7989     C.moveInto(Result);
7990   } else if (T->isMemberPointerType()) {
7991     MemberPtr P;
7992     if (!EvaluateMemberPointer(E, P, Info))
7993       return false;
7994     P.moveInto(Result);
7995     return true;
7996   } else if (T->isArrayType()) {
7997     LValue LV;
7998     LV.set(E, Info.CurrentCall->Index);
7999     APValue &Value = Info.CurrentCall->createTemporary(E, false);
8000     if (!EvaluateArray(E, LV, Value, Info))
8001       return false;
8002     Result = Value;
8003   } else if (T->isRecordType()) {
8004     LValue LV;
8005     LV.set(E, Info.CurrentCall->Index);
8006     APValue &Value = Info.CurrentCall->createTemporary(E, false);
8007     if (!EvaluateRecord(E, LV, Value, Info))
8008       return false;
8009     Result = Value;
8010   } else if (T->isVoidType()) {
8011     if (!Info.getLangOpts().CPlusPlus11)
8012       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8013         << E->getType();
8014     if (!EvaluateVoid(E, Info))
8015       return false;
8016   } else if (T->isAtomicType()) {
8017     if (!EvaluateAtomic(E, Result, Info))
8018       return false;
8019   } else if (Info.getLangOpts().CPlusPlus11) {
8020     Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8021     return false;
8022   } else {
8023     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8024     return false;
8025   }
8026 
8027   return true;
8028 }
8029 
8030 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8031 /// cases, the in-place evaluation is essential, since later initializers for
8032 /// an object can indirectly refer to subobjects which were initialized earlier.
8033 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8034                             const Expr *E, bool AllowNonLiteralTypes) {
8035   assert(!E->isValueDependent());
8036 
8037   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8038     return false;
8039 
8040   if (E->isRValue()) {
8041     // Evaluate arrays and record types in-place, so that later initializers can
8042     // refer to earlier-initialized members of the object.
8043     if (E->getType()->isArrayType())
8044       return EvaluateArray(E, This, Result, Info);
8045     else if (E->getType()->isRecordType())
8046       return EvaluateRecord(E, This, Result, Info);
8047   }
8048 
8049   // For any other type, in-place evaluation is unimportant.
8050   return Evaluate(Result, Info, E);
8051 }
8052 
8053 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8054 /// lvalue-to-rvalue cast if it is an lvalue.
8055 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8056   if (!CheckLiteralType(Info, E))
8057     return false;
8058 
8059   if (!::Evaluate(Result, Info, E))
8060     return false;
8061 
8062   if (E->isGLValue()) {
8063     LValue LV;
8064     LV.setFrom(Info.Ctx, Result);
8065     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8066       return false;
8067   }
8068 
8069   // Check this core constant expression is a constant expression.
8070   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8071 }
8072 
8073 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8074                                  const ASTContext &Ctx, bool &IsConst) {
8075   // Fast-path evaluations of integer literals, since we sometimes see files
8076   // containing vast quantities of these.
8077   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8078     Result.Val = APValue(APSInt(L->getValue(),
8079                                 L->getType()->isUnsignedIntegerType()));
8080     IsConst = true;
8081     return true;
8082   }
8083 
8084   // FIXME: Evaluating values of large array and record types can cause
8085   // performance problems. Only do so in C++11 for now.
8086   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8087                           Exp->getType()->isRecordType()) &&
8088       !Ctx.getLangOpts().CPlusPlus11) {
8089     IsConst = false;
8090     return true;
8091   }
8092   return false;
8093 }
8094 
8095 
8096 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8097 /// any crazy technique (that has nothing to do with language standards) that
8098 /// we want to.  If this function returns true, it returns the folded constant
8099 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8100 /// will be applied to the result.
8101 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8102   bool IsConst;
8103   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8104     return IsConst;
8105 
8106   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8107   return ::EvaluateAsRValue(Info, this, Result.Val);
8108 }
8109 
8110 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8111                                       const ASTContext &Ctx) const {
8112   EvalResult Scratch;
8113   return EvaluateAsRValue(Scratch, Ctx) &&
8114          HandleConversionToBool(Scratch.Val, Result);
8115 }
8116 
8117 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8118                          SideEffectsKind AllowSideEffects) const {
8119   if (!getType()->isIntegralOrEnumerationType())
8120     return false;
8121 
8122   EvalResult ExprResult;
8123   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8124       (!AllowSideEffects && ExprResult.HasSideEffects))
8125     return false;
8126 
8127   Result = ExprResult.Val.getInt();
8128   return true;
8129 }
8130 
8131 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8132   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8133 
8134   LValue LV;
8135   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8136       !CheckLValueConstantExpression(Info, getExprLoc(),
8137                                      Ctx.getLValueReferenceType(getType()), LV))
8138     return false;
8139 
8140   LV.moveInto(Result.Val);
8141   return true;
8142 }
8143 
8144 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8145                                  const VarDecl *VD,
8146                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8147   // FIXME: Evaluating initializers for large array and record types can cause
8148   // performance problems. Only do so in C++11 for now.
8149   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8150       !Ctx.getLangOpts().CPlusPlus11)
8151     return false;
8152 
8153   Expr::EvalStatus EStatus;
8154   EStatus.Diag = &Notes;
8155 
8156   EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8157   InitInfo.setEvaluatingDecl(VD, Value);
8158 
8159   LValue LVal;
8160   LVal.set(VD);
8161 
8162   // C++11 [basic.start.init]p2:
8163   //  Variables with static storage duration or thread storage duration shall be
8164   //  zero-initialized before any other initialization takes place.
8165   // This behavior is not present in C.
8166   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8167       !VD->getType()->isReferenceType()) {
8168     ImplicitValueInitExpr VIE(VD->getType());
8169     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8170                          /*AllowNonLiteralTypes=*/true))
8171       return false;
8172   }
8173 
8174   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8175                        /*AllowNonLiteralTypes=*/true) ||
8176       EStatus.HasSideEffects)
8177     return false;
8178 
8179   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8180                                  Value);
8181 }
8182 
8183 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8184 /// constant folded, but discard the result.
8185 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8186   EvalResult Result;
8187   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8188 }
8189 
8190 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8191                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8192   EvalResult EvalResult;
8193   EvalResult.Diag = Diag;
8194   bool Result = EvaluateAsRValue(EvalResult, Ctx);
8195   (void)Result;
8196   assert(Result && "Could not evaluate expression");
8197   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8198 
8199   return EvalResult.Val.getInt();
8200 }
8201 
8202 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8203   bool IsConst;
8204   EvalResult EvalResult;
8205   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8206     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8207     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8208   }
8209 }
8210 
8211 bool Expr::EvalResult::isGlobalLValue() const {
8212   assert(Val.isLValue());
8213   return IsGlobalLValue(Val.getLValueBase());
8214 }
8215 
8216 
8217 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8218 /// an integer constant expression.
8219 
8220 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8221 /// comma, etc
8222 
8223 // CheckICE - This function does the fundamental ICE checking: the returned
8224 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8225 // and a (possibly null) SourceLocation indicating the location of the problem.
8226 //
8227 // Note that to reduce code duplication, this helper does no evaluation
8228 // itself; the caller checks whether the expression is evaluatable, and
8229 // in the rare cases where CheckICE actually cares about the evaluated
8230 // value, it calls into Evalute.
8231 
8232 namespace {
8233 
8234 enum ICEKind {
8235   /// This expression is an ICE.
8236   IK_ICE,
8237   /// This expression is not an ICE, but if it isn't evaluated, it's
8238   /// a legal subexpression for an ICE. This return value is used to handle
8239   /// the comma operator in C99 mode, and non-constant subexpressions.
8240   IK_ICEIfUnevaluated,
8241   /// This expression is not an ICE, and is not a legal subexpression for one.
8242   IK_NotICE
8243 };
8244 
8245 struct ICEDiag {
8246   ICEKind Kind;
8247   SourceLocation Loc;
8248 
8249   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8250 };
8251 
8252 }
8253 
8254 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8255 
8256 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8257 
8258 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8259   Expr::EvalResult EVResult;
8260   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8261       !EVResult.Val.isInt())
8262     return ICEDiag(IK_NotICE, E->getLocStart());
8263 
8264   return NoDiag();
8265 }
8266 
8267 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8268   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8269   if (!E->getType()->isIntegralOrEnumerationType())
8270     return ICEDiag(IK_NotICE, E->getLocStart());
8271 
8272   switch (E->getStmtClass()) {
8273 #define ABSTRACT_STMT(Node)
8274 #define STMT(Node, Base) case Expr::Node##Class:
8275 #define EXPR(Node, Base)
8276 #include "clang/AST/StmtNodes.inc"
8277   case Expr::PredefinedExprClass:
8278   case Expr::FloatingLiteralClass:
8279   case Expr::ImaginaryLiteralClass:
8280   case Expr::StringLiteralClass:
8281   case Expr::ArraySubscriptExprClass:
8282   case Expr::MemberExprClass:
8283   case Expr::CompoundAssignOperatorClass:
8284   case Expr::CompoundLiteralExprClass:
8285   case Expr::ExtVectorElementExprClass:
8286   case Expr::DesignatedInitExprClass:
8287   case Expr::ImplicitValueInitExprClass:
8288   case Expr::ParenListExprClass:
8289   case Expr::VAArgExprClass:
8290   case Expr::AddrLabelExprClass:
8291   case Expr::StmtExprClass:
8292   case Expr::CXXMemberCallExprClass:
8293   case Expr::CUDAKernelCallExprClass:
8294   case Expr::CXXDynamicCastExprClass:
8295   case Expr::CXXTypeidExprClass:
8296   case Expr::CXXUuidofExprClass:
8297   case Expr::MSPropertyRefExprClass:
8298   case Expr::CXXNullPtrLiteralExprClass:
8299   case Expr::UserDefinedLiteralClass:
8300   case Expr::CXXThisExprClass:
8301   case Expr::CXXThrowExprClass:
8302   case Expr::CXXNewExprClass:
8303   case Expr::CXXDeleteExprClass:
8304   case Expr::CXXPseudoDestructorExprClass:
8305   case Expr::UnresolvedLookupExprClass:
8306   case Expr::DependentScopeDeclRefExprClass:
8307   case Expr::CXXConstructExprClass:
8308   case Expr::CXXStdInitializerListExprClass:
8309   case Expr::CXXBindTemporaryExprClass:
8310   case Expr::ExprWithCleanupsClass:
8311   case Expr::CXXTemporaryObjectExprClass:
8312   case Expr::CXXUnresolvedConstructExprClass:
8313   case Expr::CXXDependentScopeMemberExprClass:
8314   case Expr::UnresolvedMemberExprClass:
8315   case Expr::ObjCStringLiteralClass:
8316   case Expr::ObjCBoxedExprClass:
8317   case Expr::ObjCArrayLiteralClass:
8318   case Expr::ObjCDictionaryLiteralClass:
8319   case Expr::ObjCEncodeExprClass:
8320   case Expr::ObjCMessageExprClass:
8321   case Expr::ObjCSelectorExprClass:
8322   case Expr::ObjCProtocolExprClass:
8323   case Expr::ObjCIvarRefExprClass:
8324   case Expr::ObjCPropertyRefExprClass:
8325   case Expr::ObjCSubscriptRefExprClass:
8326   case Expr::ObjCIsaExprClass:
8327   case Expr::ShuffleVectorExprClass:
8328   case Expr::ConvertVectorExprClass:
8329   case Expr::BlockExprClass:
8330   case Expr::NoStmtClass:
8331   case Expr::OpaqueValueExprClass:
8332   case Expr::PackExpansionExprClass:
8333   case Expr::SubstNonTypeTemplateParmPackExprClass:
8334   case Expr::FunctionParmPackExprClass:
8335   case Expr::AsTypeExprClass:
8336   case Expr::ObjCIndirectCopyRestoreExprClass:
8337   case Expr::MaterializeTemporaryExprClass:
8338   case Expr::PseudoObjectExprClass:
8339   case Expr::AtomicExprClass:
8340   case Expr::LambdaExprClass:
8341     return ICEDiag(IK_NotICE, E->getLocStart());
8342 
8343   case Expr::InitListExprClass: {
8344     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8345     // form "T x = { a };" is equivalent to "T x = a;".
8346     // Unless we're initializing a reference, T is a scalar as it is known to be
8347     // of integral or enumeration type.
8348     if (E->isRValue())
8349       if (cast<InitListExpr>(E)->getNumInits() == 1)
8350         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8351     return ICEDiag(IK_NotICE, E->getLocStart());
8352   }
8353 
8354   case Expr::SizeOfPackExprClass:
8355   case Expr::GNUNullExprClass:
8356     // GCC considers the GNU __null value to be an integral constant expression.
8357     return NoDiag();
8358 
8359   case Expr::SubstNonTypeTemplateParmExprClass:
8360     return
8361       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8362 
8363   case Expr::ParenExprClass:
8364     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8365   case Expr::GenericSelectionExprClass:
8366     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8367   case Expr::IntegerLiteralClass:
8368   case Expr::CharacterLiteralClass:
8369   case Expr::ObjCBoolLiteralExprClass:
8370   case Expr::CXXBoolLiteralExprClass:
8371   case Expr::CXXScalarValueInitExprClass:
8372   case Expr::TypeTraitExprClass:
8373   case Expr::ArrayTypeTraitExprClass:
8374   case Expr::ExpressionTraitExprClass:
8375   case Expr::CXXNoexceptExprClass:
8376     return NoDiag();
8377   case Expr::CallExprClass:
8378   case Expr::CXXOperatorCallExprClass: {
8379     // C99 6.6/3 allows function calls within unevaluated subexpressions of
8380     // constant expressions, but they can never be ICEs because an ICE cannot
8381     // contain an operand of (pointer to) function type.
8382     const CallExpr *CE = cast<CallExpr>(E);
8383     if (CE->getBuiltinCallee())
8384       return CheckEvalInICE(E, Ctx);
8385     return ICEDiag(IK_NotICE, E->getLocStart());
8386   }
8387   case Expr::DeclRefExprClass: {
8388     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8389       return NoDiag();
8390     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8391     if (Ctx.getLangOpts().CPlusPlus &&
8392         D && IsConstNonVolatile(D->getType())) {
8393       // Parameter variables are never constants.  Without this check,
8394       // getAnyInitializer() can find a default argument, which leads
8395       // to chaos.
8396       if (isa<ParmVarDecl>(D))
8397         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8398 
8399       // C++ 7.1.5.1p2
8400       //   A variable of non-volatile const-qualified integral or enumeration
8401       //   type initialized by an ICE can be used in ICEs.
8402       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8403         if (!Dcl->getType()->isIntegralOrEnumerationType())
8404           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8405 
8406         const VarDecl *VD;
8407         // Look for a declaration of this variable that has an initializer, and
8408         // check whether it is an ICE.
8409         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8410           return NoDiag();
8411         else
8412           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8413       }
8414     }
8415     return ICEDiag(IK_NotICE, E->getLocStart());
8416   }
8417   case Expr::UnaryOperatorClass: {
8418     const UnaryOperator *Exp = cast<UnaryOperator>(E);
8419     switch (Exp->getOpcode()) {
8420     case UO_PostInc:
8421     case UO_PostDec:
8422     case UO_PreInc:
8423     case UO_PreDec:
8424     case UO_AddrOf:
8425     case UO_Deref:
8426       // C99 6.6/3 allows increment and decrement within unevaluated
8427       // subexpressions of constant expressions, but they can never be ICEs
8428       // because an ICE cannot contain an lvalue operand.
8429       return ICEDiag(IK_NotICE, E->getLocStart());
8430     case UO_Extension:
8431     case UO_LNot:
8432     case UO_Plus:
8433     case UO_Minus:
8434     case UO_Not:
8435     case UO_Real:
8436     case UO_Imag:
8437       return CheckICE(Exp->getSubExpr(), Ctx);
8438     }
8439 
8440     // OffsetOf falls through here.
8441   }
8442   case Expr::OffsetOfExprClass: {
8443     // Note that per C99, offsetof must be an ICE. And AFAIK, using
8444     // EvaluateAsRValue matches the proposed gcc behavior for cases like
8445     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
8446     // compliance: we should warn earlier for offsetof expressions with
8447     // array subscripts that aren't ICEs, and if the array subscripts
8448     // are ICEs, the value of the offsetof must be an integer constant.
8449     return CheckEvalInICE(E, Ctx);
8450   }
8451   case Expr::UnaryExprOrTypeTraitExprClass: {
8452     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8453     if ((Exp->getKind() ==  UETT_SizeOf) &&
8454         Exp->getTypeOfArgument()->isVariableArrayType())
8455       return ICEDiag(IK_NotICE, E->getLocStart());
8456     return NoDiag();
8457   }
8458   case Expr::BinaryOperatorClass: {
8459     const BinaryOperator *Exp = cast<BinaryOperator>(E);
8460     switch (Exp->getOpcode()) {
8461     case BO_PtrMemD:
8462     case BO_PtrMemI:
8463     case BO_Assign:
8464     case BO_MulAssign:
8465     case BO_DivAssign:
8466     case BO_RemAssign:
8467     case BO_AddAssign:
8468     case BO_SubAssign:
8469     case BO_ShlAssign:
8470     case BO_ShrAssign:
8471     case BO_AndAssign:
8472     case BO_XorAssign:
8473     case BO_OrAssign:
8474       // C99 6.6/3 allows assignments within unevaluated subexpressions of
8475       // constant expressions, but they can never be ICEs because an ICE cannot
8476       // contain an lvalue operand.
8477       return ICEDiag(IK_NotICE, E->getLocStart());
8478 
8479     case BO_Mul:
8480     case BO_Div:
8481     case BO_Rem:
8482     case BO_Add:
8483     case BO_Sub:
8484     case BO_Shl:
8485     case BO_Shr:
8486     case BO_LT:
8487     case BO_GT:
8488     case BO_LE:
8489     case BO_GE:
8490     case BO_EQ:
8491     case BO_NE:
8492     case BO_And:
8493     case BO_Xor:
8494     case BO_Or:
8495     case BO_Comma: {
8496       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8497       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8498       if (Exp->getOpcode() == BO_Div ||
8499           Exp->getOpcode() == BO_Rem) {
8500         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8501         // we don't evaluate one.
8502         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8503           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8504           if (REval == 0)
8505             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8506           if (REval.isSigned() && REval.isAllOnesValue()) {
8507             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8508             if (LEval.isMinSignedValue())
8509               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8510           }
8511         }
8512       }
8513       if (Exp->getOpcode() == BO_Comma) {
8514         if (Ctx.getLangOpts().C99) {
8515           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8516           // if it isn't evaluated.
8517           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8518             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8519         } else {
8520           // In both C89 and C++, commas in ICEs are illegal.
8521           return ICEDiag(IK_NotICE, E->getLocStart());
8522         }
8523       }
8524       return Worst(LHSResult, RHSResult);
8525     }
8526     case BO_LAnd:
8527     case BO_LOr: {
8528       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8529       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8530       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8531         // Rare case where the RHS has a comma "side-effect"; we need
8532         // to actually check the condition to see whether the side
8533         // with the comma is evaluated.
8534         if ((Exp->getOpcode() == BO_LAnd) !=
8535             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8536           return RHSResult;
8537         return NoDiag();
8538       }
8539 
8540       return Worst(LHSResult, RHSResult);
8541     }
8542     }
8543   }
8544   case Expr::ImplicitCastExprClass:
8545   case Expr::CStyleCastExprClass:
8546   case Expr::CXXFunctionalCastExprClass:
8547   case Expr::CXXStaticCastExprClass:
8548   case Expr::CXXReinterpretCastExprClass:
8549   case Expr::CXXConstCastExprClass:
8550   case Expr::ObjCBridgedCastExprClass: {
8551     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8552     if (isa<ExplicitCastExpr>(E)) {
8553       if (const FloatingLiteral *FL
8554             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8555         unsigned DestWidth = Ctx.getIntWidth(E->getType());
8556         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8557         APSInt IgnoredVal(DestWidth, !DestSigned);
8558         bool Ignored;
8559         // If the value does not fit in the destination type, the behavior is
8560         // undefined, so we are not required to treat it as a constant
8561         // expression.
8562         if (FL->getValue().convertToInteger(IgnoredVal,
8563                                             llvm::APFloat::rmTowardZero,
8564                                             &Ignored) & APFloat::opInvalidOp)
8565           return ICEDiag(IK_NotICE, E->getLocStart());
8566         return NoDiag();
8567       }
8568     }
8569     switch (cast<CastExpr>(E)->getCastKind()) {
8570     case CK_LValueToRValue:
8571     case CK_AtomicToNonAtomic:
8572     case CK_NonAtomicToAtomic:
8573     case CK_NoOp:
8574     case CK_IntegralToBoolean:
8575     case CK_IntegralCast:
8576       return CheckICE(SubExpr, Ctx);
8577     default:
8578       return ICEDiag(IK_NotICE, E->getLocStart());
8579     }
8580   }
8581   case Expr::BinaryConditionalOperatorClass: {
8582     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8583     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8584     if (CommonResult.Kind == IK_NotICE) return CommonResult;
8585     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8586     if (FalseResult.Kind == IK_NotICE) return FalseResult;
8587     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8588     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8589         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8590     return FalseResult;
8591   }
8592   case Expr::ConditionalOperatorClass: {
8593     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8594     // If the condition (ignoring parens) is a __builtin_constant_p call,
8595     // then only the true side is actually considered in an integer constant
8596     // expression, and it is fully evaluated.  This is an important GNU
8597     // extension.  See GCC PR38377 for discussion.
8598     if (const CallExpr *CallCE
8599         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
8600       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8601         return CheckEvalInICE(E, Ctx);
8602     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
8603     if (CondResult.Kind == IK_NotICE)
8604       return CondResult;
8605 
8606     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8607     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8608 
8609     if (TrueResult.Kind == IK_NotICE)
8610       return TrueResult;
8611     if (FalseResult.Kind == IK_NotICE)
8612       return FalseResult;
8613     if (CondResult.Kind == IK_ICEIfUnevaluated)
8614       return CondResult;
8615     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
8616       return NoDiag();
8617     // Rare case where the diagnostics depend on which side is evaluated
8618     // Note that if we get here, CondResult is 0, and at least one of
8619     // TrueResult and FalseResult is non-zero.
8620     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
8621       return FalseResult;
8622     return TrueResult;
8623   }
8624   case Expr::CXXDefaultArgExprClass:
8625     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
8626   case Expr::CXXDefaultInitExprClass:
8627     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
8628   case Expr::ChooseExprClass: {
8629     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
8630   }
8631   }
8632 
8633   llvm_unreachable("Invalid StmtClass!");
8634 }
8635 
8636 /// Evaluate an expression as a C++11 integral constant expression.
8637 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
8638                                                     const Expr *E,
8639                                                     llvm::APSInt *Value,
8640                                                     SourceLocation *Loc) {
8641   if (!E->getType()->isIntegralOrEnumerationType()) {
8642     if (Loc) *Loc = E->getExprLoc();
8643     return false;
8644   }
8645 
8646   APValue Result;
8647   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
8648     return false;
8649 
8650   assert(Result.isInt() && "pointer cast to int is not an ICE");
8651   if (Value) *Value = Result.getInt();
8652   return true;
8653 }
8654 
8655 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8656                                  SourceLocation *Loc) const {
8657   if (Ctx.getLangOpts().CPlusPlus11)
8658     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8659 
8660   ICEDiag D = CheckICE(this, Ctx);
8661   if (D.Kind != IK_ICE) {
8662     if (Loc) *Loc = D.Loc;
8663     return false;
8664   }
8665   return true;
8666 }
8667 
8668 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
8669                                  SourceLocation *Loc, bool isEvaluated) const {
8670   if (Ctx.getLangOpts().CPlusPlus11)
8671     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8672 
8673   if (!isIntegerConstantExpr(Ctx, Loc))
8674     return false;
8675   if (!EvaluateAsInt(Value, Ctx))
8676     llvm_unreachable("ICE cannot be evaluated!");
8677   return true;
8678 }
8679 
8680 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
8681   return CheckICE(this, Ctx).Kind == IK_ICE;
8682 }
8683 
8684 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
8685                                SourceLocation *Loc) const {
8686   // We support this checking in C++98 mode in order to diagnose compatibility
8687   // issues.
8688   assert(Ctx.getLangOpts().CPlusPlus);
8689 
8690   // Build evaluation settings.
8691   Expr::EvalStatus Status;
8692   SmallVector<PartialDiagnosticAt, 8> Diags;
8693   Status.Diag = &Diags;
8694   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
8695 
8696   APValue Scratch;
8697   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8698 
8699   if (!Diags.empty()) {
8700     IsConstExpr = false;
8701     if (Loc) *Loc = Diags[0].first;
8702   } else if (!IsConstExpr) {
8703     // FIXME: This shouldn't happen.
8704     if (Loc) *Loc = getExprLoc();
8705   }
8706 
8707   return IsConstExpr;
8708 }
8709 
8710 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8711                                     const FunctionDecl *Callee,
8712                                     llvm::ArrayRef<const Expr*> Args) const {
8713   Expr::EvalStatus Status;
8714   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8715 
8716   ArgVector ArgValues(Args.size());
8717   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8718        I != E; ++I) {
8719     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8720       // If evaluation fails, throw away the argument entirely.
8721       ArgValues[I - Args.begin()] = APValue();
8722     if (Info.EvalStatus.HasSideEffects)
8723       return false;
8724   }
8725 
8726   // Build fake call to Callee.
8727   CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/0,
8728                        ArgValues.data());
8729   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8730 }
8731 
8732 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
8733                                    SmallVectorImpl<
8734                                      PartialDiagnosticAt> &Diags) {
8735   // FIXME: It would be useful to check constexpr function templates, but at the
8736   // moment the constant expression evaluator cannot cope with the non-rigorous
8737   // ASTs which we build for dependent expressions.
8738   if (FD->isDependentContext())
8739     return true;
8740 
8741   Expr::EvalStatus Status;
8742   Status.Diag = &Diags;
8743 
8744   EvalInfo Info(FD->getASTContext(), Status,
8745                 EvalInfo::EM_PotentialConstantExpression);
8746 
8747   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8748   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8749 
8750   // Fabricate an arbitrary expression on the stack and pretend that it
8751   // is a temporary being used as the 'this' pointer.
8752   LValue This;
8753   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
8754   This.set(&VIE, Info.CurrentCall->Index);
8755 
8756   ArrayRef<const Expr*> Args;
8757 
8758   SourceLocation Loc = FD->getLocation();
8759 
8760   APValue Scratch;
8761   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8762     // Evaluate the call as a constant initializer, to allow the construction
8763     // of objects of non-literal types.
8764     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
8765     HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
8766   } else
8767     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8768                        Args, FD->getBody(), Info, Scratch);
8769 
8770   return Diags.empty();
8771 }
8772 
8773 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8774                                               const FunctionDecl *FD,
8775                                               SmallVectorImpl<
8776                                                 PartialDiagnosticAt> &Diags) {
8777   Expr::EvalStatus Status;
8778   Status.Diag = &Diags;
8779 
8780   EvalInfo Info(FD->getASTContext(), Status,
8781                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8782 
8783   // Fabricate a call stack frame to give the arguments a plausible cover story.
8784   ArrayRef<const Expr*> Args;
8785   ArgVector ArgValues(0);
8786   bool Success = EvaluateArgs(Args, ArgValues, Info);
8787   (void)Success;
8788   assert(Success &&
8789          "Failed to set up arguments for potential constant evaluation");
8790   CallStackFrame Frame(Info, SourceLocation(), FD, 0, ArgValues.data());
8791 
8792   APValue ResultScratch;
8793   Evaluate(ResultScratch, Info, E);
8794   return Diags.empty();
8795 }
8796