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