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