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