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