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