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     /// CallLoc - The location of the call expression for this call.
314     SourceLocation CallLoc;
315 
316     /// Callee - The function which was called.
317     const FunctionDecl *Callee;
318 
319     /// Index - The call index of this call.
320     unsigned Index;
321 
322     /// This - The binding for the this pointer in this call, if any.
323     const LValue *This;
324 
325     /// Arguments - Parameter bindings for this function call, indexed by
326     /// parameters' function scope indices.
327     APValue *Arguments;
328 
329     // Note that we intentionally use std::map here so that references to
330     // values are stable.
331     typedef std::map<const void*, APValue> MapTy;
332     typedef MapTy::const_iterator temp_iterator;
333     /// Temporaries - Temporary lvalues materialized within this stack frame.
334     MapTy Temporaries;
335 
336     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337                    const FunctionDecl *Callee, const LValue *This,
338                    APValue *Arguments);
339     ~CallStackFrame();
340 
341     APValue *getTemporary(const void *Key) {
342       MapTy::iterator I = Temporaries.find(Key);
343       return I == Temporaries.end() ? nullptr : &I->second;
344     }
345     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
346   };
347 
348   /// Temporarily override 'this'.
349   class ThisOverrideRAII {
350   public:
351     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352         : Frame(Frame), OldThis(Frame.This) {
353       if (Enable)
354         Frame.This = NewThis;
355     }
356     ~ThisOverrideRAII() {
357       Frame.This = OldThis;
358     }
359   private:
360     CallStackFrame &Frame;
361     const LValue *OldThis;
362   };
363 
364   /// A partial diagnostic which we might know in advance that we are not going
365   /// to emit.
366   class OptionalDiagnostic {
367     PartialDiagnostic *Diag;
368 
369   public:
370     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371       : Diag(Diag) {}
372 
373     template<typename T>
374     OptionalDiagnostic &operator<<(const T &v) {
375       if (Diag)
376         *Diag << v;
377       return *this;
378     }
379 
380     OptionalDiagnostic &operator<<(const APSInt &I) {
381       if (Diag) {
382         SmallVector<char, 32> Buffer;
383         I.toString(Buffer);
384         *Diag << StringRef(Buffer.data(), Buffer.size());
385       }
386       return *this;
387     }
388 
389     OptionalDiagnostic &operator<<(const APFloat &F) {
390       if (Diag) {
391         // FIXME: Force the precision of the source value down so we don't
392         // print digits which are usually useless (we don't really care here if
393         // we truncate a digit by accident in edge cases).  Ideally,
394         // APFloat::toString would automatically print the shortest
395         // representation which rounds to the correct value, but it's a bit
396         // tricky to implement.
397         unsigned precision =
398             llvm::APFloat::semanticsPrecision(F.getSemantics());
399         precision = (precision * 59 + 195) / 196;
400         SmallVector<char, 32> Buffer;
401         F.toString(Buffer, precision);
402         *Diag << StringRef(Buffer.data(), Buffer.size());
403       }
404       return *this;
405     }
406   };
407 
408   /// A cleanup, and a flag indicating whether it is lifetime-extended.
409   class Cleanup {
410     llvm::PointerIntPair<APValue*, 1, bool> Value;
411 
412   public:
413     Cleanup(APValue *Val, bool IsLifetimeExtended)
414         : Value(Val, IsLifetimeExtended) {}
415 
416     bool isLifetimeExtended() const { return Value.getInt(); }
417     void endLifetime() {
418       *Value.getPointer() = APValue();
419     }
420   };
421 
422   /// EvalInfo - This is a private struct used by the evaluator to capture
423   /// information about a subexpression as it is folded.  It retains information
424   /// about the AST context, but also maintains information about the folded
425   /// expression.
426   ///
427   /// If an expression could be evaluated, it is still possible it is not a C
428   /// "integer constant expression" or constant expression.  If not, this struct
429   /// captures information about how and why not.
430   ///
431   /// One bit of information passed *into* the request for constant folding
432   /// indicates whether the subexpression is "evaluated" or not according to C
433   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
434   /// evaluate the expression regardless of what the RHS is, but C only allows
435   /// certain things in certain situations.
436   struct EvalInfo {
437     ASTContext &Ctx;
438 
439     /// EvalStatus - Contains information about the evaluation.
440     Expr::EvalStatus &EvalStatus;
441 
442     /// CurrentCall - The top of the constexpr call stack.
443     CallStackFrame *CurrentCall;
444 
445     /// CallStackDepth - The number of calls in the call stack right now.
446     unsigned CallStackDepth;
447 
448     /// NextCallIndex - The next call index to assign.
449     unsigned NextCallIndex;
450 
451     /// StepsLeft - The remaining number of evaluation steps we're permitted
452     /// to perform. This is essentially a limit for the number of statements
453     /// we will evaluate.
454     unsigned StepsLeft;
455 
456     /// BottomFrame - The frame in which evaluation started. This must be
457     /// initialized after CurrentCall and CallStackDepth.
458     CallStackFrame BottomFrame;
459 
460     /// A stack of values whose lifetimes end at the end of some surrounding
461     /// evaluation frame.
462     llvm::SmallVector<Cleanup, 16> CleanupStack;
463 
464     /// EvaluatingDecl - This is the declaration whose initializer is being
465     /// evaluated, if any.
466     APValue::LValueBase EvaluatingDecl;
467 
468     /// EvaluatingDeclValue - This is the value being constructed for the
469     /// declaration whose initializer is being evaluated, if any.
470     APValue *EvaluatingDeclValue;
471 
472     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473     /// notes attached to it will also be stored, otherwise they will not be.
474     bool HasActiveDiagnostic;
475 
476     /// \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_ATTRIBUTE_UNUSED_RESULT 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), CallLoc(CallLoc), Callee(Callee),
965       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
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 EvaluateDecl(EvalInfo &Info, const Decl *D) {
3404   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3405     // We don't need to evaluate the initializer for a static local.
3406     if (!VD->hasLocalStorage())
3407       return true;
3408 
3409     LValue Result;
3410     Result.set(VD, Info.CurrentCall->Index);
3411     APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3412 
3413     const Expr *InitE = VD->getInit();
3414     if (!InitE) {
3415       Info.FFDiag(D->getLocStart(), diag::note_constexpr_uninitialized)
3416         << false << VD->getType();
3417       Val = APValue();
3418       return false;
3419     }
3420 
3421     if (InitE->isValueDependent())
3422       return false;
3423 
3424     if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3425       // Wipe out any partially-computed value, to allow tracking that this
3426       // evaluation failed.
3427       Val = APValue();
3428       return false;
3429     }
3430   }
3431 
3432   return true;
3433 }
3434 
3435 /// Evaluate a condition (either a variable declaration or an expression).
3436 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3437                          const Expr *Cond, bool &Result) {
3438   FullExpressionRAII Scope(Info);
3439   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3440     return false;
3441   return EvaluateAsBooleanCondition(Cond, Result, Info);
3442 }
3443 
3444 namespace {
3445 /// \brief A location where the result (returned value) of evaluating a
3446 /// statement should be stored.
3447 struct StmtResult {
3448   /// The APValue that should be filled in with the returned value.
3449   APValue &Value;
3450   /// The location containing the result, if any (used to support RVO).
3451   const LValue *Slot;
3452 };
3453 }
3454 
3455 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3456                                    const Stmt *S,
3457                                    const SwitchCase *SC = nullptr);
3458 
3459 /// Evaluate the body of a loop, and translate the result as appropriate.
3460 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3461                                        const Stmt *Body,
3462                                        const SwitchCase *Case = nullptr) {
3463   BlockScopeRAII Scope(Info);
3464   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3465   case ESR_Break:
3466     return ESR_Succeeded;
3467   case ESR_Succeeded:
3468   case ESR_Continue:
3469     return ESR_Continue;
3470   case ESR_Failed:
3471   case ESR_Returned:
3472   case ESR_CaseNotFound:
3473     return ESR;
3474   }
3475   llvm_unreachable("Invalid EvalStmtResult!");
3476 }
3477 
3478 /// Evaluate a switch statement.
3479 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3480                                      const SwitchStmt *SS) {
3481   BlockScopeRAII Scope(Info);
3482 
3483   // Evaluate the switch condition.
3484   APSInt Value;
3485   {
3486     FullExpressionRAII Scope(Info);
3487     if (const Stmt *Init = SS->getInit()) {
3488       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3489       if (ESR != ESR_Succeeded)
3490         return ESR;
3491     }
3492     if (SS->getConditionVariable() &&
3493         !EvaluateDecl(Info, SS->getConditionVariable()))
3494       return ESR_Failed;
3495     if (!EvaluateInteger(SS->getCond(), Value, Info))
3496       return ESR_Failed;
3497   }
3498 
3499   // Find the switch case corresponding to the value of the condition.
3500   // FIXME: Cache this lookup.
3501   const SwitchCase *Found = nullptr;
3502   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3503        SC = SC->getNextSwitchCase()) {
3504     if (isa<DefaultStmt>(SC)) {
3505       Found = SC;
3506       continue;
3507     }
3508 
3509     const CaseStmt *CS = cast<CaseStmt>(SC);
3510     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3511     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3512                               : LHS;
3513     if (LHS <= Value && Value <= RHS) {
3514       Found = SC;
3515       break;
3516     }
3517   }
3518 
3519   if (!Found)
3520     return ESR_Succeeded;
3521 
3522   // Search the switch body for the switch case and evaluate it from there.
3523   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3524   case ESR_Break:
3525     return ESR_Succeeded;
3526   case ESR_Succeeded:
3527   case ESR_Continue:
3528   case ESR_Failed:
3529   case ESR_Returned:
3530     return ESR;
3531   case ESR_CaseNotFound:
3532     // This can only happen if the switch case is nested within a statement
3533     // expression. We have no intention of supporting that.
3534     Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3535     return ESR_Failed;
3536   }
3537   llvm_unreachable("Invalid EvalStmtResult!");
3538 }
3539 
3540 // Evaluate a statement.
3541 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3542                                    const Stmt *S, const SwitchCase *Case) {
3543   if (!Info.nextStep(S))
3544     return ESR_Failed;
3545 
3546   // If we're hunting down a 'case' or 'default' label, recurse through
3547   // substatements until we hit the label.
3548   if (Case) {
3549     // FIXME: We don't start the lifetime of objects whose initialization we
3550     // jump over. However, such objects must be of class type with a trivial
3551     // default constructor that initialize all subobjects, so must be empty,
3552     // so this almost never matters.
3553     switch (S->getStmtClass()) {
3554     case Stmt::CompoundStmtClass:
3555       // FIXME: Precompute which substatement of a compound statement we
3556       // would jump to, and go straight there rather than performing a
3557       // linear scan each time.
3558     case Stmt::LabelStmtClass:
3559     case Stmt::AttributedStmtClass:
3560     case Stmt::DoStmtClass:
3561       break;
3562 
3563     case Stmt::CaseStmtClass:
3564     case Stmt::DefaultStmtClass:
3565       if (Case == S)
3566         Case = nullptr;
3567       break;
3568 
3569     case Stmt::IfStmtClass: {
3570       // FIXME: Precompute which side of an 'if' we would jump to, and go
3571       // straight there rather than scanning both sides.
3572       const IfStmt *IS = cast<IfStmt>(S);
3573 
3574       // Wrap the evaluation in a block scope, in case it's a DeclStmt
3575       // preceded by our switch label.
3576       BlockScopeRAII Scope(Info);
3577 
3578       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3579       if (ESR != ESR_CaseNotFound || !IS->getElse())
3580         return ESR;
3581       return EvaluateStmt(Result, Info, IS->getElse(), Case);
3582     }
3583 
3584     case Stmt::WhileStmtClass: {
3585       EvalStmtResult ESR =
3586           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3587       if (ESR != ESR_Continue)
3588         return ESR;
3589       break;
3590     }
3591 
3592     case Stmt::ForStmtClass: {
3593       const ForStmt *FS = cast<ForStmt>(S);
3594       EvalStmtResult ESR =
3595           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3596       if (ESR != ESR_Continue)
3597         return ESR;
3598       if (FS->getInc()) {
3599         FullExpressionRAII IncScope(Info);
3600         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3601           return ESR_Failed;
3602       }
3603       break;
3604     }
3605 
3606     case Stmt::DeclStmtClass:
3607       // FIXME: If the variable has initialization that can't be jumped over,
3608       // bail out of any immediately-surrounding compound-statement too.
3609     default:
3610       return ESR_CaseNotFound;
3611     }
3612   }
3613 
3614   switch (S->getStmtClass()) {
3615   default:
3616     if (const Expr *E = dyn_cast<Expr>(S)) {
3617       // Don't bother evaluating beyond an expression-statement which couldn't
3618       // be evaluated.
3619       FullExpressionRAII Scope(Info);
3620       if (!EvaluateIgnoredValue(Info, E))
3621         return ESR_Failed;
3622       return ESR_Succeeded;
3623     }
3624 
3625     Info.FFDiag(S->getLocStart());
3626     return ESR_Failed;
3627 
3628   case Stmt::NullStmtClass:
3629     return ESR_Succeeded;
3630 
3631   case Stmt::DeclStmtClass: {
3632     const DeclStmt *DS = cast<DeclStmt>(S);
3633     for (const auto *DclIt : DS->decls()) {
3634       // Each declaration initialization is its own full-expression.
3635       // FIXME: This isn't quite right; if we're performing aggregate
3636       // initialization, each braced subexpression is its own full-expression.
3637       FullExpressionRAII Scope(Info);
3638       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3639         return ESR_Failed;
3640     }
3641     return ESR_Succeeded;
3642   }
3643 
3644   case Stmt::ReturnStmtClass: {
3645     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3646     FullExpressionRAII Scope(Info);
3647     if (RetExpr &&
3648         !(Result.Slot
3649               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3650               : Evaluate(Result.Value, Info, RetExpr)))
3651       return ESR_Failed;
3652     return ESR_Returned;
3653   }
3654 
3655   case Stmt::CompoundStmtClass: {
3656     BlockScopeRAII Scope(Info);
3657 
3658     const CompoundStmt *CS = cast<CompoundStmt>(S);
3659     for (const auto *BI : CS->body()) {
3660       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3661       if (ESR == ESR_Succeeded)
3662         Case = nullptr;
3663       else if (ESR != ESR_CaseNotFound)
3664         return ESR;
3665     }
3666     return Case ? ESR_CaseNotFound : ESR_Succeeded;
3667   }
3668 
3669   case Stmt::IfStmtClass: {
3670     const IfStmt *IS = cast<IfStmt>(S);
3671 
3672     // Evaluate the condition, as either a var decl or as an expression.
3673     BlockScopeRAII Scope(Info);
3674     if (const Stmt *Init = IS->getInit()) {
3675       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3676       if (ESR != ESR_Succeeded)
3677         return ESR;
3678     }
3679     bool Cond;
3680     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3681       return ESR_Failed;
3682 
3683     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3684       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3685       if (ESR != ESR_Succeeded)
3686         return ESR;
3687     }
3688     return ESR_Succeeded;
3689   }
3690 
3691   case Stmt::WhileStmtClass: {
3692     const WhileStmt *WS = cast<WhileStmt>(S);
3693     while (true) {
3694       BlockScopeRAII Scope(Info);
3695       bool Continue;
3696       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3697                         Continue))
3698         return ESR_Failed;
3699       if (!Continue)
3700         break;
3701 
3702       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3703       if (ESR != ESR_Continue)
3704         return ESR;
3705     }
3706     return ESR_Succeeded;
3707   }
3708 
3709   case Stmt::DoStmtClass: {
3710     const DoStmt *DS = cast<DoStmt>(S);
3711     bool Continue;
3712     do {
3713       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3714       if (ESR != ESR_Continue)
3715         return ESR;
3716       Case = nullptr;
3717 
3718       FullExpressionRAII CondScope(Info);
3719       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3720         return ESR_Failed;
3721     } while (Continue);
3722     return ESR_Succeeded;
3723   }
3724 
3725   case Stmt::ForStmtClass: {
3726     const ForStmt *FS = cast<ForStmt>(S);
3727     BlockScopeRAII Scope(Info);
3728     if (FS->getInit()) {
3729       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3730       if (ESR != ESR_Succeeded)
3731         return ESR;
3732     }
3733     while (true) {
3734       BlockScopeRAII Scope(Info);
3735       bool Continue = true;
3736       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3737                                          FS->getCond(), Continue))
3738         return ESR_Failed;
3739       if (!Continue)
3740         break;
3741 
3742       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3743       if (ESR != ESR_Continue)
3744         return ESR;
3745 
3746       if (FS->getInc()) {
3747         FullExpressionRAII IncScope(Info);
3748         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3749           return ESR_Failed;
3750       }
3751     }
3752     return ESR_Succeeded;
3753   }
3754 
3755   case Stmt::CXXForRangeStmtClass: {
3756     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3757     BlockScopeRAII Scope(Info);
3758 
3759     // Initialize the __range variable.
3760     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3761     if (ESR != ESR_Succeeded)
3762       return ESR;
3763 
3764     // Create the __begin and __end iterators.
3765     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3766     if (ESR != ESR_Succeeded)
3767       return ESR;
3768     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3769     if (ESR != ESR_Succeeded)
3770       return ESR;
3771 
3772     while (true) {
3773       // Condition: __begin != __end.
3774       {
3775         bool Continue = true;
3776         FullExpressionRAII CondExpr(Info);
3777         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3778           return ESR_Failed;
3779         if (!Continue)
3780           break;
3781       }
3782 
3783       // User's variable declaration, initialized by *__begin.
3784       BlockScopeRAII InnerScope(Info);
3785       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3786       if (ESR != ESR_Succeeded)
3787         return ESR;
3788 
3789       // Loop body.
3790       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3791       if (ESR != ESR_Continue)
3792         return ESR;
3793 
3794       // Increment: ++__begin
3795       if (!EvaluateIgnoredValue(Info, FS->getInc()))
3796         return ESR_Failed;
3797     }
3798 
3799     return ESR_Succeeded;
3800   }
3801 
3802   case Stmt::SwitchStmtClass:
3803     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3804 
3805   case Stmt::ContinueStmtClass:
3806     return ESR_Continue;
3807 
3808   case Stmt::BreakStmtClass:
3809     return ESR_Break;
3810 
3811   case Stmt::LabelStmtClass:
3812     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3813 
3814   case Stmt::AttributedStmtClass:
3815     // As a general principle, C++11 attributes can be ignored without
3816     // any semantic impact.
3817     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3818                         Case);
3819 
3820   case Stmt::CaseStmtClass:
3821   case Stmt::DefaultStmtClass:
3822     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3823   }
3824 }
3825 
3826 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3827 /// default constructor. If so, we'll fold it whether or not it's marked as
3828 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3829 /// so we need special handling.
3830 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3831                                            const CXXConstructorDecl *CD,
3832                                            bool IsValueInitialization) {
3833   if (!CD->isTrivial() || !CD->isDefaultConstructor())
3834     return false;
3835 
3836   // Value-initialization does not call a trivial default constructor, so such a
3837   // call is a core constant expression whether or not the constructor is
3838   // constexpr.
3839   if (!CD->isConstexpr() && !IsValueInitialization) {
3840     if (Info.getLangOpts().CPlusPlus11) {
3841       // FIXME: If DiagDecl is an implicitly-declared special member function,
3842       // we should be much more explicit about why it's not constexpr.
3843       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3844         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3845       Info.Note(CD->getLocation(), diag::note_declared_at);
3846     } else {
3847       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3848     }
3849   }
3850   return true;
3851 }
3852 
3853 /// CheckConstexprFunction - Check that a function can be called in a constant
3854 /// expression.
3855 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3856                                    const FunctionDecl *Declaration,
3857                                    const FunctionDecl *Definition,
3858                                    const Stmt *Body) {
3859   // Potential constant expressions can contain calls to declared, but not yet
3860   // defined, constexpr functions.
3861   if (Info.checkingPotentialConstantExpression() && !Definition &&
3862       Declaration->isConstexpr())
3863     return false;
3864 
3865   // Bail out with no diagnostic if the function declaration itself is invalid.
3866   // We will have produced a relevant diagnostic while parsing it.
3867   if (Declaration->isInvalidDecl())
3868     return false;
3869 
3870   // Can we evaluate this function call?
3871   if (Definition && Definition->isConstexpr() &&
3872       !Definition->isInvalidDecl() && Body)
3873     return true;
3874 
3875   if (Info.getLangOpts().CPlusPlus11) {
3876     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3877 
3878     // If this function is not constexpr because it is an inherited
3879     // non-constexpr constructor, diagnose that directly.
3880     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3881     if (CD && CD->isInheritingConstructor()) {
3882       auto *Inherited = CD->getInheritedConstructor().getConstructor();
3883       if (!Inherited->isConstexpr())
3884         DiagDecl = CD = Inherited;
3885     }
3886 
3887     // FIXME: If DiagDecl is an implicitly-declared special member function
3888     // or an inheriting constructor, we should be much more explicit about why
3889     // it's not constexpr.
3890     if (CD && CD->isInheritingConstructor())
3891       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
3892         << CD->getInheritedConstructor().getConstructor()->getParent();
3893     else
3894       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
3895         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
3896     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3897   } else {
3898     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3899   }
3900   return false;
3901 }
3902 
3903 /// Determine if a class has any fields that might need to be copied by a
3904 /// trivial copy or move operation.
3905 static bool hasFields(const CXXRecordDecl *RD) {
3906   if (!RD || RD->isEmpty())
3907     return false;
3908   for (auto *FD : RD->fields()) {
3909     if (FD->isUnnamedBitfield())
3910       continue;
3911     return true;
3912   }
3913   for (auto &Base : RD->bases())
3914     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3915       return true;
3916   return false;
3917 }
3918 
3919 namespace {
3920 typedef SmallVector<APValue, 8> ArgVector;
3921 }
3922 
3923 /// EvaluateArgs - Evaluate the arguments to a function call.
3924 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3925                          EvalInfo &Info) {
3926   bool Success = true;
3927   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3928        I != E; ++I) {
3929     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3930       // If we're checking for a potential constant expression, evaluate all
3931       // initializers even if some of them fail.
3932       if (!Info.noteFailure())
3933         return false;
3934       Success = false;
3935     }
3936   }
3937   return Success;
3938 }
3939 
3940 /// Evaluate a function call.
3941 static bool HandleFunctionCall(SourceLocation CallLoc,
3942                                const FunctionDecl *Callee, const LValue *This,
3943                                ArrayRef<const Expr*> Args, const Stmt *Body,
3944                                EvalInfo &Info, APValue &Result,
3945                                const LValue *ResultSlot) {
3946   ArgVector ArgValues(Args.size());
3947   if (!EvaluateArgs(Args, ArgValues, Info))
3948     return false;
3949 
3950   if (!Info.CheckCallLimit(CallLoc))
3951     return false;
3952 
3953   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3954 
3955   // For a trivial copy or move assignment, perform an APValue copy. This is
3956   // essential for unions, where the operations performed by the assignment
3957   // operator cannot be represented as statements.
3958   //
3959   // Skip this for non-union classes with no fields; in that case, the defaulted
3960   // copy/move does not actually read the object.
3961   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3962   if (MD && MD->isDefaulted() &&
3963       (MD->getParent()->isUnion() ||
3964        (MD->isTrivial() && hasFields(MD->getParent())))) {
3965     assert(This &&
3966            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3967     LValue RHS;
3968     RHS.setFrom(Info.Ctx, ArgValues[0]);
3969     APValue RHSValue;
3970     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3971                                         RHS, RHSValue))
3972       return false;
3973     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3974                           RHSValue))
3975       return false;
3976     This->moveInto(Result);
3977     return true;
3978   }
3979 
3980   StmtResult Ret = {Result, ResultSlot};
3981   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
3982   if (ESR == ESR_Succeeded) {
3983     if (Callee->getReturnType()->isVoidType())
3984       return true;
3985     Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3986   }
3987   return ESR == ESR_Returned;
3988 }
3989 
3990 /// Evaluate a constructor call.
3991 static bool HandleConstructorCall(const Expr *E, const LValue &This,
3992                                   APValue *ArgValues,
3993                                   const CXXConstructorDecl *Definition,
3994                                   EvalInfo &Info, APValue &Result) {
3995   SourceLocation CallLoc = E->getExprLoc();
3996   if (!Info.CheckCallLimit(CallLoc))
3997     return false;
3998 
3999   const CXXRecordDecl *RD = Definition->getParent();
4000   if (RD->getNumVBases()) {
4001     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4002     return false;
4003   }
4004 
4005   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4006 
4007   // FIXME: Creating an APValue just to hold a nonexistent return value is
4008   // wasteful.
4009   APValue RetVal;
4010   StmtResult Ret = {RetVal, nullptr};
4011 
4012   // If it's a delegating constructor, delegate.
4013   if (Definition->isDelegatingConstructor()) {
4014     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4015     {
4016       FullExpressionRAII InitScope(Info);
4017       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4018         return false;
4019     }
4020     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4021   }
4022 
4023   // For a trivial copy or move constructor, perform an APValue copy. This is
4024   // essential for unions (or classes with anonymous union members), where the
4025   // operations performed by the constructor cannot be represented by
4026   // ctor-initializers.
4027   //
4028   // Skip this for empty non-union classes; we should not perform an
4029   // lvalue-to-rvalue conversion on them because their copy constructor does not
4030   // actually read them.
4031   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4032       (Definition->getParent()->isUnion() ||
4033        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4034     LValue RHS;
4035     RHS.setFrom(Info.Ctx, ArgValues[0]);
4036     return handleLValueToRValueConversion(
4037         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4038         RHS, Result);
4039   }
4040 
4041   // Reserve space for the struct members.
4042   if (!RD->isUnion() && Result.isUninit())
4043     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4044                      std::distance(RD->field_begin(), RD->field_end()));
4045 
4046   if (RD->isInvalidDecl()) return false;
4047   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4048 
4049   // A scope for temporaries lifetime-extended by reference members.
4050   BlockScopeRAII LifetimeExtendedScope(Info);
4051 
4052   bool Success = true;
4053   unsigned BasesSeen = 0;
4054 #ifndef NDEBUG
4055   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4056 #endif
4057   for (const auto *I : Definition->inits()) {
4058     LValue Subobject = This;
4059     APValue *Value = &Result;
4060 
4061     // Determine the subobject to initialize.
4062     FieldDecl *FD = nullptr;
4063     if (I->isBaseInitializer()) {
4064       QualType BaseType(I->getBaseClass(), 0);
4065 #ifndef NDEBUG
4066       // Non-virtual base classes are initialized in the order in the class
4067       // definition. We have already checked for virtual base classes.
4068       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4069       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4070              "base class initializers not in expected order");
4071       ++BaseIt;
4072 #endif
4073       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4074                                   BaseType->getAsCXXRecordDecl(), &Layout))
4075         return false;
4076       Value = &Result.getStructBase(BasesSeen++);
4077     } else if ((FD = I->getMember())) {
4078       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4079         return false;
4080       if (RD->isUnion()) {
4081         Result = APValue(FD);
4082         Value = &Result.getUnionValue();
4083       } else {
4084         Value = &Result.getStructField(FD->getFieldIndex());
4085       }
4086     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4087       // Walk the indirect field decl's chain to find the object to initialize,
4088       // and make sure we've initialized every step along it.
4089       for (auto *C : IFD->chain()) {
4090         FD = cast<FieldDecl>(C);
4091         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4092         // Switch the union field if it differs. This happens if we had
4093         // preceding zero-initialization, and we're now initializing a union
4094         // subobject other than the first.
4095         // FIXME: In this case, the values of the other subobjects are
4096         // specified, since zero-initialization sets all padding bits to zero.
4097         if (Value->isUninit() ||
4098             (Value->isUnion() && Value->getUnionField() != FD)) {
4099           if (CD->isUnion())
4100             *Value = APValue(FD);
4101           else
4102             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4103                              std::distance(CD->field_begin(), CD->field_end()));
4104         }
4105         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4106           return false;
4107         if (CD->isUnion())
4108           Value = &Value->getUnionValue();
4109         else
4110           Value = &Value->getStructField(FD->getFieldIndex());
4111       }
4112     } else {
4113       llvm_unreachable("unknown base initializer kind");
4114     }
4115 
4116     FullExpressionRAII InitScope(Info);
4117     if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4118         (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4119                                                           *Value, FD))) {
4120       // If we're checking for a potential constant expression, evaluate all
4121       // initializers even if some of them fail.
4122       if (!Info.noteFailure())
4123         return false;
4124       Success = false;
4125     }
4126   }
4127 
4128   return Success &&
4129          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4130 }
4131 
4132 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4133                                   ArrayRef<const Expr*> Args,
4134                                   const CXXConstructorDecl *Definition,
4135                                   EvalInfo &Info, APValue &Result) {
4136   ArgVector ArgValues(Args.size());
4137   if (!EvaluateArgs(Args, ArgValues, Info))
4138     return false;
4139 
4140   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4141                                Info, Result);
4142 }
4143 
4144 //===----------------------------------------------------------------------===//
4145 // Generic Evaluation
4146 //===----------------------------------------------------------------------===//
4147 namespace {
4148 
4149 template <class Derived>
4150 class ExprEvaluatorBase
4151   : public ConstStmtVisitor<Derived, bool> {
4152 private:
4153   Derived &getDerived() { return static_cast<Derived&>(*this); }
4154   bool DerivedSuccess(const APValue &V, const Expr *E) {
4155     return getDerived().Success(V, E);
4156   }
4157   bool DerivedZeroInitialization(const Expr *E) {
4158     return getDerived().ZeroInitialization(E);
4159   }
4160 
4161   // Check whether a conditional operator with a non-constant condition is a
4162   // potential constant expression. If neither arm is a potential constant
4163   // expression, then the conditional operator is not either.
4164   template<typename ConditionalOperator>
4165   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4166     assert(Info.checkingPotentialConstantExpression());
4167 
4168     // Speculatively evaluate both arms.
4169     SmallVector<PartialDiagnosticAt, 8> Diag;
4170     {
4171       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4172       StmtVisitorTy::Visit(E->getFalseExpr());
4173       if (Diag.empty())
4174         return;
4175     }
4176 
4177     {
4178       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4179       Diag.clear();
4180       StmtVisitorTy::Visit(E->getTrueExpr());
4181       if (Diag.empty())
4182         return;
4183     }
4184 
4185     Error(E, diag::note_constexpr_conditional_never_const);
4186   }
4187 
4188 
4189   template<typename ConditionalOperator>
4190   bool HandleConditionalOperator(const ConditionalOperator *E) {
4191     bool BoolResult;
4192     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4193       if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4194         CheckPotentialConstantConditional(E);
4195       return false;
4196     }
4197 
4198     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4199     return StmtVisitorTy::Visit(EvalExpr);
4200   }
4201 
4202 protected:
4203   EvalInfo &Info;
4204   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4205   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4206 
4207   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4208     return Info.CCEDiag(E, D);
4209   }
4210 
4211   bool ZeroInitialization(const Expr *E) { return Error(E); }
4212 
4213 public:
4214   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4215 
4216   EvalInfo &getEvalInfo() { return Info; }
4217 
4218   /// Report an evaluation error. This should only be called when an error is
4219   /// first discovered. When propagating an error, just return false.
4220   bool Error(const Expr *E, diag::kind D) {
4221     Info.FFDiag(E, D);
4222     return false;
4223   }
4224   bool Error(const Expr *E) {
4225     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4226   }
4227 
4228   bool VisitStmt(const Stmt *) {
4229     llvm_unreachable("Expression evaluator should not be called on stmts");
4230   }
4231   bool VisitExpr(const Expr *E) {
4232     return Error(E);
4233   }
4234 
4235   bool VisitParenExpr(const ParenExpr *E)
4236     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4237   bool VisitUnaryExtension(const UnaryOperator *E)
4238     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4239   bool VisitUnaryPlus(const UnaryOperator *E)
4240     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4241   bool VisitChooseExpr(const ChooseExpr *E)
4242     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4243   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4244     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4245   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4246     { return StmtVisitorTy::Visit(E->getReplacement()); }
4247   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4248     { return StmtVisitorTy::Visit(E->getExpr()); }
4249   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4250     // The initializer may not have been parsed yet, or might be erroneous.
4251     if (!E->getExpr())
4252       return Error(E);
4253     return StmtVisitorTy::Visit(E->getExpr());
4254   }
4255   // We cannot create any objects for which cleanups are required, so there is
4256   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4257   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4258     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4259 
4260   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4261     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4262     return static_cast<Derived*>(this)->VisitCastExpr(E);
4263   }
4264   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4265     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4266     return static_cast<Derived*>(this)->VisitCastExpr(E);
4267   }
4268 
4269   bool VisitBinaryOperator(const BinaryOperator *E) {
4270     switch (E->getOpcode()) {
4271     default:
4272       return Error(E);
4273 
4274     case BO_Comma:
4275       VisitIgnoredValue(E->getLHS());
4276       return StmtVisitorTy::Visit(E->getRHS());
4277 
4278     case BO_PtrMemD:
4279     case BO_PtrMemI: {
4280       LValue Obj;
4281       if (!HandleMemberPointerAccess(Info, E, Obj))
4282         return false;
4283       APValue Result;
4284       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4285         return false;
4286       return DerivedSuccess(Result, E);
4287     }
4288     }
4289   }
4290 
4291   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4292     // Evaluate and cache the common expression. We treat it as a temporary,
4293     // even though it's not quite the same thing.
4294     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4295                   Info, E->getCommon()))
4296       return false;
4297 
4298     return HandleConditionalOperator(E);
4299   }
4300 
4301   bool VisitConditionalOperator(const ConditionalOperator *E) {
4302     bool IsBcpCall = false;
4303     // If the condition (ignoring parens) is a __builtin_constant_p call,
4304     // the result is a constant expression if it can be folded without
4305     // side-effects. This is an important GNU extension. See GCC PR38377
4306     // for discussion.
4307     if (const CallExpr *CallCE =
4308           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4309       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4310         IsBcpCall = true;
4311 
4312     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4313     // constant expression; we can't check whether it's potentially foldable.
4314     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4315       return false;
4316 
4317     FoldConstant Fold(Info, IsBcpCall);
4318     if (!HandleConditionalOperator(E)) {
4319       Fold.keepDiagnostics();
4320       return false;
4321     }
4322 
4323     return true;
4324   }
4325 
4326   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4327     if (APValue *Value = Info.CurrentCall->getTemporary(E))
4328       return DerivedSuccess(*Value, E);
4329 
4330     const Expr *Source = E->getSourceExpr();
4331     if (!Source)
4332       return Error(E);
4333     if (Source == E) { // sanity checking.
4334       assert(0 && "OpaqueValueExpr recursively refers to itself");
4335       return Error(E);
4336     }
4337     return StmtVisitorTy::Visit(Source);
4338   }
4339 
4340   bool VisitCallExpr(const CallExpr *E) {
4341     APValue Result;
4342     if (!handleCallExpr(E, Result, nullptr))
4343       return false;
4344     return DerivedSuccess(Result, E);
4345   }
4346 
4347   bool handleCallExpr(const CallExpr *E, APValue &Result,
4348                      const LValue *ResultSlot) {
4349     const Expr *Callee = E->getCallee()->IgnoreParens();
4350     QualType CalleeType = Callee->getType();
4351 
4352     const FunctionDecl *FD = nullptr;
4353     LValue *This = nullptr, ThisVal;
4354     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4355     bool HasQualifier = false;
4356 
4357     // Extract function decl and 'this' pointer from the callee.
4358     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4359       const ValueDecl *Member = nullptr;
4360       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4361         // Explicit bound member calls, such as x.f() or p->g();
4362         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4363           return false;
4364         Member = ME->getMemberDecl();
4365         This = &ThisVal;
4366         HasQualifier = ME->hasQualifier();
4367       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4368         // Indirect bound member calls ('.*' or '->*').
4369         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4370         if (!Member) return false;
4371         This = &ThisVal;
4372       } else
4373         return Error(Callee);
4374 
4375       FD = dyn_cast<FunctionDecl>(Member);
4376       if (!FD)
4377         return Error(Callee);
4378     } else if (CalleeType->isFunctionPointerType()) {
4379       LValue Call;
4380       if (!EvaluatePointer(Callee, Call, Info))
4381         return false;
4382 
4383       if (!Call.getLValueOffset().isZero())
4384         return Error(Callee);
4385       FD = dyn_cast_or_null<FunctionDecl>(
4386                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4387       if (!FD)
4388         return Error(Callee);
4389 
4390       // Overloaded operator calls to member functions are represented as normal
4391       // calls with '*this' as the first argument.
4392       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4393       if (MD && !MD->isStatic()) {
4394         // FIXME: When selecting an implicit conversion for an overloaded
4395         // operator delete, we sometimes try to evaluate calls to conversion
4396         // operators without a 'this' parameter!
4397         if (Args.empty())
4398           return Error(E);
4399 
4400         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4401           return false;
4402         This = &ThisVal;
4403         Args = Args.slice(1);
4404       }
4405 
4406       // Don't call function pointers which have been cast to some other type.
4407       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4408         return Error(E);
4409     } else
4410       return Error(E);
4411 
4412     if (This && !This->checkSubobject(Info, E, CSK_This))
4413       return false;
4414 
4415     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4416     // calls to such functions in constant expressions.
4417     if (This && !HasQualifier &&
4418         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4419       return Error(E, diag::note_constexpr_virtual_call);
4420 
4421     const FunctionDecl *Definition = nullptr;
4422     Stmt *Body = FD->getBody(Definition);
4423 
4424     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4425         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4426                             Result, ResultSlot))
4427       return false;
4428 
4429     return true;
4430   }
4431 
4432   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4433     return StmtVisitorTy::Visit(E->getInitializer());
4434   }
4435   bool VisitInitListExpr(const InitListExpr *E) {
4436     if (E->getNumInits() == 0)
4437       return DerivedZeroInitialization(E);
4438     if (E->getNumInits() == 1)
4439       return StmtVisitorTy::Visit(E->getInit(0));
4440     return Error(E);
4441   }
4442   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4443     return DerivedZeroInitialization(E);
4444   }
4445   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4446     return DerivedZeroInitialization(E);
4447   }
4448   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4449     return DerivedZeroInitialization(E);
4450   }
4451 
4452   /// A member expression where the object is a prvalue is itself a prvalue.
4453   bool VisitMemberExpr(const MemberExpr *E) {
4454     assert(!E->isArrow() && "missing call to bound member function?");
4455 
4456     APValue Val;
4457     if (!Evaluate(Val, Info, E->getBase()))
4458       return false;
4459 
4460     QualType BaseTy = E->getBase()->getType();
4461 
4462     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4463     if (!FD) return Error(E);
4464     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4465     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4466            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4467 
4468     CompleteObject Obj(&Val, BaseTy);
4469     SubobjectDesignator Designator(BaseTy);
4470     Designator.addDeclUnchecked(FD);
4471 
4472     APValue Result;
4473     return extractSubobject(Info, E, Obj, Designator, Result) &&
4474            DerivedSuccess(Result, E);
4475   }
4476 
4477   bool VisitCastExpr(const CastExpr *E) {
4478     switch (E->getCastKind()) {
4479     default:
4480       break;
4481 
4482     case CK_AtomicToNonAtomic: {
4483       APValue AtomicVal;
4484       if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4485         return false;
4486       return DerivedSuccess(AtomicVal, E);
4487     }
4488 
4489     case CK_NoOp:
4490     case CK_UserDefinedConversion:
4491       return StmtVisitorTy::Visit(E->getSubExpr());
4492 
4493     case CK_LValueToRValue: {
4494       LValue LVal;
4495       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4496         return false;
4497       APValue RVal;
4498       // Note, we use the subexpression's type in order to retain cv-qualifiers.
4499       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4500                                           LVal, RVal))
4501         return false;
4502       return DerivedSuccess(RVal, E);
4503     }
4504     }
4505 
4506     return Error(E);
4507   }
4508 
4509   bool VisitUnaryPostInc(const UnaryOperator *UO) {
4510     return VisitUnaryPostIncDec(UO);
4511   }
4512   bool VisitUnaryPostDec(const UnaryOperator *UO) {
4513     return VisitUnaryPostIncDec(UO);
4514   }
4515   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4516     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4517       return Error(UO);
4518 
4519     LValue LVal;
4520     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4521       return false;
4522     APValue RVal;
4523     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4524                       UO->isIncrementOp(), &RVal))
4525       return false;
4526     return DerivedSuccess(RVal, UO);
4527   }
4528 
4529   bool VisitStmtExpr(const StmtExpr *E) {
4530     // We will have checked the full-expressions inside the statement expression
4531     // when they were completed, and don't need to check them again now.
4532     if (Info.checkingForOverflow())
4533       return Error(E);
4534 
4535     BlockScopeRAII Scope(Info);
4536     const CompoundStmt *CS = E->getSubStmt();
4537     if (CS->body_empty())
4538       return true;
4539 
4540     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4541                                            BE = CS->body_end();
4542          /**/; ++BI) {
4543       if (BI + 1 == BE) {
4544         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4545         if (!FinalExpr) {
4546           Info.FFDiag((*BI)->getLocStart(),
4547                     diag::note_constexpr_stmt_expr_unsupported);
4548           return false;
4549         }
4550         return this->Visit(FinalExpr);
4551       }
4552 
4553       APValue ReturnValue;
4554       StmtResult Result = { ReturnValue, nullptr };
4555       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4556       if (ESR != ESR_Succeeded) {
4557         // FIXME: If the statement-expression terminated due to 'return',
4558         // 'break', or 'continue', it would be nice to propagate that to
4559         // the outer statement evaluation rather than bailing out.
4560         if (ESR != ESR_Failed)
4561           Info.FFDiag((*BI)->getLocStart(),
4562                     diag::note_constexpr_stmt_expr_unsupported);
4563         return false;
4564       }
4565     }
4566 
4567     llvm_unreachable("Return from function from the loop above.");
4568   }
4569 
4570   /// Visit a value which is evaluated, but whose value is ignored.
4571   void VisitIgnoredValue(const Expr *E) {
4572     EvaluateIgnoredValue(Info, E);
4573   }
4574 
4575   /// Potentially visit a MemberExpr's base expression.
4576   void VisitIgnoredBaseExpression(const Expr *E) {
4577     // While MSVC doesn't evaluate the base expression, it does diagnose the
4578     // presence of side-effecting behavior.
4579     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4580       return;
4581     VisitIgnoredValue(E);
4582   }
4583 };
4584 
4585 }
4586 
4587 //===----------------------------------------------------------------------===//
4588 // Common base class for lvalue and temporary evaluation.
4589 //===----------------------------------------------------------------------===//
4590 namespace {
4591 template<class Derived>
4592 class LValueExprEvaluatorBase
4593   : public ExprEvaluatorBase<Derived> {
4594 protected:
4595   LValue &Result;
4596   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4597   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4598 
4599   bool Success(APValue::LValueBase B) {
4600     Result.set(B);
4601     return true;
4602   }
4603 
4604 public:
4605   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4606     ExprEvaluatorBaseTy(Info), Result(Result) {}
4607 
4608   bool Success(const APValue &V, const Expr *E) {
4609     Result.setFrom(this->Info.Ctx, V);
4610     return true;
4611   }
4612 
4613   bool VisitMemberExpr(const MemberExpr *E) {
4614     // Handle non-static data members.
4615     QualType BaseTy;
4616     bool EvalOK;
4617     if (E->isArrow()) {
4618       EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
4619       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4620     } else if (E->getBase()->isRValue()) {
4621       assert(E->getBase()->getType()->isRecordType());
4622       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4623       BaseTy = E->getBase()->getType();
4624     } else {
4625       EvalOK = this->Visit(E->getBase());
4626       BaseTy = E->getBase()->getType();
4627     }
4628     if (!EvalOK) {
4629       if (!this->Info.allowInvalidBaseExpr())
4630         return false;
4631       Result.setInvalid(E);
4632       return true;
4633     }
4634 
4635     const ValueDecl *MD = E->getMemberDecl();
4636     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4637       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4638              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4639       (void)BaseTy;
4640       if (!HandleLValueMember(this->Info, E, Result, FD))
4641         return false;
4642     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4643       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4644         return false;
4645     } else
4646       return this->Error(E);
4647 
4648     if (MD->getType()->isReferenceType()) {
4649       APValue RefValue;
4650       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4651                                           RefValue))
4652         return false;
4653       return Success(RefValue, E);
4654     }
4655     return true;
4656   }
4657 
4658   bool VisitBinaryOperator(const BinaryOperator *E) {
4659     switch (E->getOpcode()) {
4660     default:
4661       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4662 
4663     case BO_PtrMemD:
4664     case BO_PtrMemI:
4665       return HandleMemberPointerAccess(this->Info, E, Result);
4666     }
4667   }
4668 
4669   bool VisitCastExpr(const CastExpr *E) {
4670     switch (E->getCastKind()) {
4671     default:
4672       return ExprEvaluatorBaseTy::VisitCastExpr(E);
4673 
4674     case CK_DerivedToBase:
4675     case CK_UncheckedDerivedToBase:
4676       if (!this->Visit(E->getSubExpr()))
4677         return false;
4678 
4679       // Now figure out the necessary offset to add to the base LV to get from
4680       // the derived class to the base class.
4681       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4682                                   Result);
4683     }
4684   }
4685 };
4686 }
4687 
4688 //===----------------------------------------------------------------------===//
4689 // LValue Evaluation
4690 //
4691 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4692 // function designators (in C), decl references to void objects (in C), and
4693 // temporaries (if building with -Wno-address-of-temporary).
4694 //
4695 // LValue evaluation produces values comprising a base expression of one of the
4696 // following types:
4697 // - Declarations
4698 //  * VarDecl
4699 //  * FunctionDecl
4700 // - Literals
4701 //  * CompoundLiteralExpr in C
4702 //  * StringLiteral
4703 //  * CXXTypeidExpr
4704 //  * PredefinedExpr
4705 //  * ObjCStringLiteralExpr
4706 //  * ObjCEncodeExpr
4707 //  * AddrLabelExpr
4708 //  * BlockExpr
4709 //  * CallExpr for a MakeStringConstant builtin
4710 // - Locals and temporaries
4711 //  * MaterializeTemporaryExpr
4712 //  * Any Expr, with a CallIndex indicating the function in which the temporary
4713 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
4714 //    from the AST (FIXME).
4715 //  * A MaterializeTemporaryExpr that has static storage duration, with no
4716 //    CallIndex, for a lifetime-extended temporary.
4717 // plus an offset in bytes.
4718 //===----------------------------------------------------------------------===//
4719 namespace {
4720 class LValueExprEvaluator
4721   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4722 public:
4723   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4724     LValueExprEvaluatorBaseTy(Info, Result) {}
4725 
4726   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4727   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4728 
4729   bool VisitDeclRefExpr(const DeclRefExpr *E);
4730   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4731   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4732   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4733   bool VisitMemberExpr(const MemberExpr *E);
4734   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4735   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4736   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4737   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4738   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4739   bool VisitUnaryDeref(const UnaryOperator *E);
4740   bool VisitUnaryReal(const UnaryOperator *E);
4741   bool VisitUnaryImag(const UnaryOperator *E);
4742   bool VisitUnaryPreInc(const UnaryOperator *UO) {
4743     return VisitUnaryPreIncDec(UO);
4744   }
4745   bool VisitUnaryPreDec(const UnaryOperator *UO) {
4746     return VisitUnaryPreIncDec(UO);
4747   }
4748   bool VisitBinAssign(const BinaryOperator *BO);
4749   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4750 
4751   bool VisitCastExpr(const CastExpr *E) {
4752     switch (E->getCastKind()) {
4753     default:
4754       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4755 
4756     case CK_LValueBitCast:
4757       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4758       if (!Visit(E->getSubExpr()))
4759         return false;
4760       Result.Designator.setInvalid();
4761       return true;
4762 
4763     case CK_BaseToDerived:
4764       if (!Visit(E->getSubExpr()))
4765         return false;
4766       return HandleBaseToDerivedCast(Info, E, Result);
4767     }
4768   }
4769 };
4770 } // end anonymous namespace
4771 
4772 /// Evaluate an expression as an lvalue. This can be legitimately called on
4773 /// expressions which are not glvalues, in three cases:
4774 ///  * function designators in C, and
4775 ///  * "extern void" objects
4776 ///  * @selector() expressions in Objective-C
4777 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4778   assert(E->isGLValue() || E->getType()->isFunctionType() ||
4779          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4780   return LValueExprEvaluator(Info, Result).Visit(E);
4781 }
4782 
4783 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4784   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4785     return Success(FD);
4786   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4787     return VisitVarDecl(E, VD);
4788   return Error(E);
4789 }
4790 
4791 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4792   CallStackFrame *Frame = nullptr;
4793   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4794     Frame = Info.CurrentCall;
4795 
4796   if (!VD->getType()->isReferenceType()) {
4797     if (Frame) {
4798       Result.set(VD, Frame->Index);
4799       return true;
4800     }
4801     return Success(VD);
4802   }
4803 
4804   APValue *V;
4805   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4806     return false;
4807   if (V->isUninit()) {
4808     if (!Info.checkingPotentialConstantExpression())
4809       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
4810     return false;
4811   }
4812   return Success(*V, E);
4813 }
4814 
4815 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4816     const MaterializeTemporaryExpr *E) {
4817   // Walk through the expression to find the materialized temporary itself.
4818   SmallVector<const Expr *, 2> CommaLHSs;
4819   SmallVector<SubobjectAdjustment, 2> Adjustments;
4820   const Expr *Inner = E->GetTemporaryExpr()->
4821       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4822 
4823   // If we passed any comma operators, evaluate their LHSs.
4824   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4825     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4826       return false;
4827 
4828   // A materialized temporary with static storage duration can appear within the
4829   // result of a constant expression evaluation, so we need to preserve its
4830   // value for use outside this evaluation.
4831   APValue *Value;
4832   if (E->getStorageDuration() == SD_Static) {
4833     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4834     *Value = APValue();
4835     Result.set(E);
4836   } else {
4837     Value = &Info.CurrentCall->
4838         createTemporary(E, E->getStorageDuration() == SD_Automatic);
4839     Result.set(E, Info.CurrentCall->Index);
4840   }
4841 
4842   QualType Type = Inner->getType();
4843 
4844   // Materialize the temporary itself.
4845   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4846       (E->getStorageDuration() == SD_Static &&
4847        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4848     *Value = APValue();
4849     return false;
4850   }
4851 
4852   // Adjust our lvalue to refer to the desired subobject.
4853   for (unsigned I = Adjustments.size(); I != 0; /**/) {
4854     --I;
4855     switch (Adjustments[I].Kind) {
4856     case SubobjectAdjustment::DerivedToBaseAdjustment:
4857       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4858                                 Type, Result))
4859         return false;
4860       Type = Adjustments[I].DerivedToBase.BasePath->getType();
4861       break;
4862 
4863     case SubobjectAdjustment::FieldAdjustment:
4864       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4865         return false;
4866       Type = Adjustments[I].Field->getType();
4867       break;
4868 
4869     case SubobjectAdjustment::MemberPointerAdjustment:
4870       if (!HandleMemberPointerAccess(this->Info, Type, Result,
4871                                      Adjustments[I].Ptr.RHS))
4872         return false;
4873       Type = Adjustments[I].Ptr.MPT->getPointeeType();
4874       break;
4875     }
4876   }
4877 
4878   return true;
4879 }
4880 
4881 bool
4882 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4883   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4884   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4885   // only see this when folding in C, so there's no standard to follow here.
4886   return Success(E);
4887 }
4888 
4889 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4890   if (!E->isPotentiallyEvaluated())
4891     return Success(E);
4892 
4893   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
4894     << E->getExprOperand()->getType()
4895     << E->getExprOperand()->getSourceRange();
4896   return false;
4897 }
4898 
4899 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4900   return Success(E);
4901 }
4902 
4903 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4904   // Handle static data members.
4905   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4906     VisitIgnoredBaseExpression(E->getBase());
4907     return VisitVarDecl(E, VD);
4908   }
4909 
4910   // Handle static member functions.
4911   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4912     if (MD->isStatic()) {
4913       VisitIgnoredBaseExpression(E->getBase());
4914       return Success(MD);
4915     }
4916   }
4917 
4918   // Handle non-static data members.
4919   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4920 }
4921 
4922 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4923   // FIXME: Deal with vectors as array subscript bases.
4924   if (E->getBase()->getType()->isVectorType())
4925     return Error(E);
4926 
4927   if (!EvaluatePointer(E->getBase(), Result, Info))
4928     return false;
4929 
4930   APSInt Index;
4931   if (!EvaluateInteger(E->getIdx(), Index, Info))
4932     return false;
4933 
4934   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4935                                      getExtValue(Index));
4936 }
4937 
4938 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4939   return EvaluatePointer(E->getSubExpr(), Result, Info);
4940 }
4941 
4942 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4943   if (!Visit(E->getSubExpr()))
4944     return false;
4945   // __real is a no-op on scalar lvalues.
4946   if (E->getSubExpr()->getType()->isAnyComplexType())
4947     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4948   return true;
4949 }
4950 
4951 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4952   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4953          "lvalue __imag__ on scalar?");
4954   if (!Visit(E->getSubExpr()))
4955     return false;
4956   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4957   return true;
4958 }
4959 
4960 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4961   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4962     return Error(UO);
4963 
4964   if (!this->Visit(UO->getSubExpr()))
4965     return false;
4966 
4967   return handleIncDec(
4968       this->Info, UO, Result, UO->getSubExpr()->getType(),
4969       UO->isIncrementOp(), nullptr);
4970 }
4971 
4972 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4973     const CompoundAssignOperator *CAO) {
4974   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4975     return Error(CAO);
4976 
4977   APValue RHS;
4978 
4979   // The overall lvalue result is the result of evaluating the LHS.
4980   if (!this->Visit(CAO->getLHS())) {
4981     if (Info.noteFailure())
4982       Evaluate(RHS, this->Info, CAO->getRHS());
4983     return false;
4984   }
4985 
4986   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4987     return false;
4988 
4989   return handleCompoundAssignment(
4990       this->Info, CAO,
4991       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4992       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4993 }
4994 
4995 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4996   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4997     return Error(E);
4998 
4999   APValue NewVal;
5000 
5001   if (!this->Visit(E->getLHS())) {
5002     if (Info.noteFailure())
5003       Evaluate(NewVal, this->Info, E->getRHS());
5004     return false;
5005   }
5006 
5007   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5008     return false;
5009 
5010   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5011                           NewVal);
5012 }
5013 
5014 //===----------------------------------------------------------------------===//
5015 // Pointer Evaluation
5016 //===----------------------------------------------------------------------===//
5017 
5018 namespace {
5019 class PointerExprEvaluator
5020   : public ExprEvaluatorBase<PointerExprEvaluator> {
5021   LValue &Result;
5022 
5023   bool Success(const Expr *E) {
5024     Result.set(E);
5025     return true;
5026   }
5027 public:
5028 
5029   PointerExprEvaluator(EvalInfo &info, LValue &Result)
5030     : ExprEvaluatorBaseTy(info), Result(Result) {}
5031 
5032   bool Success(const APValue &V, const Expr *E) {
5033     Result.setFrom(Info.Ctx, V);
5034     return true;
5035   }
5036   bool ZeroInitialization(const Expr *E) {
5037     return Success((Expr*)nullptr);
5038   }
5039 
5040   bool VisitBinaryOperator(const BinaryOperator *E);
5041   bool VisitCastExpr(const CastExpr* E);
5042   bool VisitUnaryAddrOf(const UnaryOperator *E);
5043   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5044       { return Success(E); }
5045   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5046       { return Success(E); }
5047   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5048       { return Success(E); }
5049   bool VisitCallExpr(const CallExpr *E);
5050   bool VisitBlockExpr(const BlockExpr *E) {
5051     if (!E->getBlockDecl()->hasCaptures())
5052       return Success(E);
5053     return Error(E);
5054   }
5055   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5056     // Can't look at 'this' when checking a potential constant expression.
5057     if (Info.checkingPotentialConstantExpression())
5058       return false;
5059     if (!Info.CurrentCall->This) {
5060       if (Info.getLangOpts().CPlusPlus11)
5061         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5062       else
5063         Info.FFDiag(E);
5064       return false;
5065     }
5066     Result = *Info.CurrentCall->This;
5067     return true;
5068   }
5069 
5070   // FIXME: Missing: @protocol, @selector
5071 };
5072 } // end anonymous namespace
5073 
5074 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
5075   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5076   return PointerExprEvaluator(Info, Result).Visit(E);
5077 }
5078 
5079 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5080   if (E->getOpcode() != BO_Add &&
5081       E->getOpcode() != BO_Sub)
5082     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5083 
5084   const Expr *PExp = E->getLHS();
5085   const Expr *IExp = E->getRHS();
5086   if (IExp->getType()->isPointerType())
5087     std::swap(PExp, IExp);
5088 
5089   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
5090   if (!EvalPtrOK && !Info.noteFailure())
5091     return false;
5092 
5093   llvm::APSInt Offset;
5094   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5095     return false;
5096 
5097   int64_t AdditionalOffset = getExtValue(Offset);
5098   if (E->getOpcode() == BO_Sub)
5099     AdditionalOffset = -AdditionalOffset;
5100 
5101   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5102   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5103                                      AdditionalOffset);
5104 }
5105 
5106 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5107   return EvaluateLValue(E->getSubExpr(), Result, Info);
5108 }
5109 
5110 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5111   const Expr* SubExpr = E->getSubExpr();
5112 
5113   switch (E->getCastKind()) {
5114   default:
5115     break;
5116 
5117   case CK_BitCast:
5118   case CK_CPointerToObjCPointerCast:
5119   case CK_BlockPointerToObjCPointerCast:
5120   case CK_AnyPointerToBlockPointerCast:
5121   case CK_AddressSpaceConversion:
5122     if (!Visit(SubExpr))
5123       return false;
5124     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5125     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5126     // also static_casts, but we disallow them as a resolution to DR1312.
5127     if (!E->getType()->isVoidPointerType()) {
5128       Result.Designator.setInvalid();
5129       if (SubExpr->getType()->isVoidPointerType())
5130         CCEDiag(E, diag::note_constexpr_invalid_cast)
5131           << 3 << SubExpr->getType();
5132       else
5133         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5134     }
5135     return true;
5136 
5137   case CK_DerivedToBase:
5138   case CK_UncheckedDerivedToBase:
5139     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
5140       return false;
5141     if (!Result.Base && Result.Offset.isZero())
5142       return true;
5143 
5144     // Now figure out the necessary offset to add to the base LV to get from
5145     // the derived class to the base class.
5146     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5147                                   castAs<PointerType>()->getPointeeType(),
5148                                 Result);
5149 
5150   case CK_BaseToDerived:
5151     if (!Visit(E->getSubExpr()))
5152       return false;
5153     if (!Result.Base && Result.Offset.isZero())
5154       return true;
5155     return HandleBaseToDerivedCast(Info, E, Result);
5156 
5157   case CK_NullToPointer:
5158     VisitIgnoredValue(E->getSubExpr());
5159     return ZeroInitialization(E);
5160 
5161   case CK_IntegralToPointer: {
5162     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5163 
5164     APValue Value;
5165     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5166       break;
5167 
5168     if (Value.isInt()) {
5169       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5170       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5171       Result.Base = (Expr*)nullptr;
5172       Result.InvalidBase = false;
5173       Result.Offset = CharUnits::fromQuantity(N);
5174       Result.CallIndex = 0;
5175       Result.Designator.setInvalid();
5176       return true;
5177     } else {
5178       // Cast is of an lvalue, no need to change value.
5179       Result.setFrom(Info.Ctx, Value);
5180       return true;
5181     }
5182   }
5183   case CK_ArrayToPointerDecay:
5184     if (SubExpr->isGLValue()) {
5185       if (!EvaluateLValue(SubExpr, Result, Info))
5186         return false;
5187     } else {
5188       Result.set(SubExpr, Info.CurrentCall->Index);
5189       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5190                            Info, Result, SubExpr))
5191         return false;
5192     }
5193     // The result is a pointer to the first element of the array.
5194     if (const ConstantArrayType *CAT
5195           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5196       Result.addArray(Info, E, CAT);
5197     else
5198       Result.Designator.setInvalid();
5199     return true;
5200 
5201   case CK_FunctionToPointerDecay:
5202     return EvaluateLValue(SubExpr, Result, Info);
5203   }
5204 
5205   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5206 }
5207 
5208 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5209   // C++ [expr.alignof]p3:
5210   //     When alignof is applied to a reference type, the result is the
5211   //     alignment of the referenced type.
5212   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5213     T = Ref->getPointeeType();
5214 
5215   // __alignof is defined to return the preferred alignment.
5216   return Info.Ctx.toCharUnitsFromBits(
5217     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5218 }
5219 
5220 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5221   E = E->IgnoreParens();
5222 
5223   // The kinds of expressions that we have special-case logic here for
5224   // should be kept up to date with the special checks for those
5225   // expressions in Sema.
5226 
5227   // alignof decl is always accepted, even if it doesn't make sense: we default
5228   // to 1 in those cases.
5229   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5230     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5231                                  /*RefAsPointee*/true);
5232 
5233   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5234     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5235                                  /*RefAsPointee*/true);
5236 
5237   return GetAlignOfType(Info, E->getType());
5238 }
5239 
5240 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5241   if (IsStringLiteralCall(E))
5242     return Success(E);
5243 
5244   switch (E->getBuiltinCallee()) {
5245   case Builtin::BI__builtin_addressof:
5246     return EvaluateLValue(E->getArg(0), Result, Info);
5247   case Builtin::BI__builtin_assume_aligned: {
5248     // We need to be very careful here because: if the pointer does not have the
5249     // asserted alignment, then the behavior is undefined, and undefined
5250     // behavior is non-constant.
5251     if (!EvaluatePointer(E->getArg(0), Result, Info))
5252       return false;
5253 
5254     LValue OffsetResult(Result);
5255     APSInt Alignment;
5256     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5257       return false;
5258     CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5259 
5260     if (E->getNumArgs() > 2) {
5261       APSInt Offset;
5262       if (!EvaluateInteger(E->getArg(2), Offset, Info))
5263         return false;
5264 
5265       int64_t AdditionalOffset = -getExtValue(Offset);
5266       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5267     }
5268 
5269     // If there is a base object, then it must have the correct alignment.
5270     if (OffsetResult.Base) {
5271       CharUnits BaseAlignment;
5272       if (const ValueDecl *VD =
5273           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5274         BaseAlignment = Info.Ctx.getDeclAlign(VD);
5275       } else {
5276         BaseAlignment =
5277           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5278       }
5279 
5280       if (BaseAlignment < Align) {
5281         Result.Designator.setInvalid();
5282 	// FIXME: Quantities here cast to integers because the plural modifier
5283 	// does not work on APSInts yet.
5284         CCEDiag(E->getArg(0),
5285                 diag::note_constexpr_baa_insufficient_alignment) << 0
5286           << (int) BaseAlignment.getQuantity()
5287           << (unsigned) getExtValue(Alignment);
5288         return false;
5289       }
5290     }
5291 
5292     // The offset must also have the correct alignment.
5293     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5294       Result.Designator.setInvalid();
5295       APSInt Offset(64, false);
5296       Offset = OffsetResult.Offset.getQuantity();
5297 
5298       if (OffsetResult.Base)
5299         CCEDiag(E->getArg(0),
5300                 diag::note_constexpr_baa_insufficient_alignment) << 1
5301           << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5302       else
5303         CCEDiag(E->getArg(0),
5304                 diag::note_constexpr_baa_value_insufficient_alignment)
5305           << Offset << (unsigned) getExtValue(Alignment);
5306 
5307       return false;
5308     }
5309 
5310     return true;
5311   }
5312   default:
5313     return ExprEvaluatorBaseTy::VisitCallExpr(E);
5314   }
5315 }
5316 
5317 //===----------------------------------------------------------------------===//
5318 // Member Pointer Evaluation
5319 //===----------------------------------------------------------------------===//
5320 
5321 namespace {
5322 class MemberPointerExprEvaluator
5323   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5324   MemberPtr &Result;
5325 
5326   bool Success(const ValueDecl *D) {
5327     Result = MemberPtr(D);
5328     return true;
5329   }
5330 public:
5331 
5332   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5333     : ExprEvaluatorBaseTy(Info), Result(Result) {}
5334 
5335   bool Success(const APValue &V, const Expr *E) {
5336     Result.setFrom(V);
5337     return true;
5338   }
5339   bool ZeroInitialization(const Expr *E) {
5340     return Success((const ValueDecl*)nullptr);
5341   }
5342 
5343   bool VisitCastExpr(const CastExpr *E);
5344   bool VisitUnaryAddrOf(const UnaryOperator *E);
5345 };
5346 } // end anonymous namespace
5347 
5348 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5349                                   EvalInfo &Info) {
5350   assert(E->isRValue() && E->getType()->isMemberPointerType());
5351   return MemberPointerExprEvaluator(Info, Result).Visit(E);
5352 }
5353 
5354 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5355   switch (E->getCastKind()) {
5356   default:
5357     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5358 
5359   case CK_NullToMemberPointer:
5360     VisitIgnoredValue(E->getSubExpr());
5361     return ZeroInitialization(E);
5362 
5363   case CK_BaseToDerivedMemberPointer: {
5364     if (!Visit(E->getSubExpr()))
5365       return false;
5366     if (E->path_empty())
5367       return true;
5368     // Base-to-derived member pointer casts store the path in derived-to-base
5369     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5370     // the wrong end of the derived->base arc, so stagger the path by one class.
5371     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5372     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5373          PathI != PathE; ++PathI) {
5374       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5375       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5376       if (!Result.castToDerived(Derived))
5377         return Error(E);
5378     }
5379     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5380     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5381       return Error(E);
5382     return true;
5383   }
5384 
5385   case CK_DerivedToBaseMemberPointer:
5386     if (!Visit(E->getSubExpr()))
5387       return false;
5388     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5389          PathE = E->path_end(); PathI != PathE; ++PathI) {
5390       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5391       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5392       if (!Result.castToBase(Base))
5393         return Error(E);
5394     }
5395     return true;
5396   }
5397 }
5398 
5399 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5400   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5401   // member can be formed.
5402   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5403 }
5404 
5405 //===----------------------------------------------------------------------===//
5406 // Record Evaluation
5407 //===----------------------------------------------------------------------===//
5408 
5409 namespace {
5410   class RecordExprEvaluator
5411   : public ExprEvaluatorBase<RecordExprEvaluator> {
5412     const LValue &This;
5413     APValue &Result;
5414   public:
5415 
5416     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5417       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5418 
5419     bool Success(const APValue &V, const Expr *E) {
5420       Result = V;
5421       return true;
5422     }
5423     bool ZeroInitialization(const Expr *E) {
5424       return ZeroInitialization(E, E->getType());
5425     }
5426     bool ZeroInitialization(const Expr *E, QualType T);
5427 
5428     bool VisitCallExpr(const CallExpr *E) {
5429       return handleCallExpr(E, Result, &This);
5430     }
5431     bool VisitCastExpr(const CastExpr *E);
5432     bool VisitInitListExpr(const InitListExpr *E);
5433     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5434       return VisitCXXConstructExpr(E, E->getType());
5435     }
5436     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5437     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5438     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5439   };
5440 }
5441 
5442 /// Perform zero-initialization on an object of non-union class type.
5443 /// C++11 [dcl.init]p5:
5444 ///  To zero-initialize an object or reference of type T means:
5445 ///    [...]
5446 ///    -- if T is a (possibly cv-qualified) non-union class type,
5447 ///       each non-static data member and each base-class subobject is
5448 ///       zero-initialized
5449 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5450                                           const RecordDecl *RD,
5451                                           const LValue &This, APValue &Result) {
5452   assert(!RD->isUnion() && "Expected non-union class type");
5453   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5454   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5455                    std::distance(RD->field_begin(), RD->field_end()));
5456 
5457   if (RD->isInvalidDecl()) return false;
5458   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5459 
5460   if (CD) {
5461     unsigned Index = 0;
5462     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5463            End = CD->bases_end(); I != End; ++I, ++Index) {
5464       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5465       LValue Subobject = This;
5466       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5467         return false;
5468       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5469                                          Result.getStructBase(Index)))
5470         return false;
5471     }
5472   }
5473 
5474   for (const auto *I : RD->fields()) {
5475     // -- if T is a reference type, no initialization is performed.
5476     if (I->getType()->isReferenceType())
5477       continue;
5478 
5479     LValue Subobject = This;
5480     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5481       return false;
5482 
5483     ImplicitValueInitExpr VIE(I->getType());
5484     if (!EvaluateInPlace(
5485           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5486       return false;
5487   }
5488 
5489   return true;
5490 }
5491 
5492 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5493   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5494   if (RD->isInvalidDecl()) return false;
5495   if (RD->isUnion()) {
5496     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5497     // object's first non-static named data member is zero-initialized
5498     RecordDecl::field_iterator I = RD->field_begin();
5499     if (I == RD->field_end()) {
5500       Result = APValue((const FieldDecl*)nullptr);
5501       return true;
5502     }
5503 
5504     LValue Subobject = This;
5505     if (!HandleLValueMember(Info, E, Subobject, *I))
5506       return false;
5507     Result = APValue(*I);
5508     ImplicitValueInitExpr VIE(I->getType());
5509     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5510   }
5511 
5512   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5513     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5514     return false;
5515   }
5516 
5517   return HandleClassZeroInitialization(Info, E, RD, This, Result);
5518 }
5519 
5520 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5521   switch (E->getCastKind()) {
5522   default:
5523     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5524 
5525   case CK_ConstructorConversion:
5526     return Visit(E->getSubExpr());
5527 
5528   case CK_DerivedToBase:
5529   case CK_UncheckedDerivedToBase: {
5530     APValue DerivedObject;
5531     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5532       return false;
5533     if (!DerivedObject.isStruct())
5534       return Error(E->getSubExpr());
5535 
5536     // Derived-to-base rvalue conversion: just slice off the derived part.
5537     APValue *Value = &DerivedObject;
5538     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5539     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5540          PathE = E->path_end(); PathI != PathE; ++PathI) {
5541       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5542       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5543       Value = &Value->getStructBase(getBaseIndex(RD, Base));
5544       RD = Base;
5545     }
5546     Result = *Value;
5547     return true;
5548   }
5549   }
5550 }
5551 
5552 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5553   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5554   if (RD->isInvalidDecl()) return false;
5555   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5556 
5557   if (RD->isUnion()) {
5558     const FieldDecl *Field = E->getInitializedFieldInUnion();
5559     Result = APValue(Field);
5560     if (!Field)
5561       return true;
5562 
5563     // If the initializer list for a union does not contain any elements, the
5564     // first element of the union is value-initialized.
5565     // FIXME: The element should be initialized from an initializer list.
5566     //        Is this difference ever observable for initializer lists which
5567     //        we don't build?
5568     ImplicitValueInitExpr VIE(Field->getType());
5569     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5570 
5571     LValue Subobject = This;
5572     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5573       return false;
5574 
5575     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5576     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5577                                   isa<CXXDefaultInitExpr>(InitExpr));
5578 
5579     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5580   }
5581 
5582   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
5583   if (Result.isUninit())
5584     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5585                      std::distance(RD->field_begin(), RD->field_end()));
5586   unsigned ElementNo = 0;
5587   bool Success = true;
5588 
5589   // Initialize base classes.
5590   if (CXXRD) {
5591     for (const auto &Base : CXXRD->bases()) {
5592       assert(ElementNo < E->getNumInits() && "missing init for base class");
5593       const Expr *Init = E->getInit(ElementNo);
5594 
5595       LValue Subobject = This;
5596       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5597         return false;
5598 
5599       APValue &FieldVal = Result.getStructBase(ElementNo);
5600       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
5601         if (!Info.noteFailure())
5602           return false;
5603         Success = false;
5604       }
5605       ++ElementNo;
5606     }
5607   }
5608 
5609   // Initialize members.
5610   for (const auto *Field : RD->fields()) {
5611     // Anonymous bit-fields are not considered members of the class for
5612     // purposes of aggregate initialization.
5613     if (Field->isUnnamedBitfield())
5614       continue;
5615 
5616     LValue Subobject = This;
5617 
5618     bool HaveInit = ElementNo < E->getNumInits();
5619 
5620     // FIXME: Diagnostics here should point to the end of the initializer
5621     // list, not the start.
5622     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5623                             Subobject, Field, &Layout))
5624       return false;
5625 
5626     // Perform an implicit value-initialization for members beyond the end of
5627     // the initializer list.
5628     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5629     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5630 
5631     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5632     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5633                                   isa<CXXDefaultInitExpr>(Init));
5634 
5635     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5636     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5637         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5638                                                        FieldVal, Field))) {
5639       if (!Info.noteFailure())
5640         return false;
5641       Success = false;
5642     }
5643   }
5644 
5645   return Success;
5646 }
5647 
5648 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5649                                                 QualType T) {
5650   // Note that E's type is not necessarily the type of our class here; we might
5651   // be initializing an array element instead.
5652   const CXXConstructorDecl *FD = E->getConstructor();
5653   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5654 
5655   bool ZeroInit = E->requiresZeroInitialization();
5656   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5657     // If we've already performed zero-initialization, we're already done.
5658     if (!Result.isUninit())
5659       return true;
5660 
5661     // We can get here in two different ways:
5662     //  1) We're performing value-initialization, and should zero-initialize
5663     //     the object, or
5664     //  2) We're performing default-initialization of an object with a trivial
5665     //     constexpr default constructor, in which case we should start the
5666     //     lifetimes of all the base subobjects (there can be no data member
5667     //     subobjects in this case) per [basic.life]p1.
5668     // Either way, ZeroInitialization is appropriate.
5669     return ZeroInitialization(E, T);
5670   }
5671 
5672   const FunctionDecl *Definition = nullptr;
5673   auto Body = FD->getBody(Definition);
5674 
5675   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5676     return false;
5677 
5678   // Avoid materializing a temporary for an elidable copy/move constructor.
5679   if (E->isElidable() && !ZeroInit)
5680     if (const MaterializeTemporaryExpr *ME
5681           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5682       return Visit(ME->GetTemporaryExpr());
5683 
5684   if (ZeroInit && !ZeroInitialization(E, T))
5685     return false;
5686 
5687   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5688   return HandleConstructorCall(E, This, Args,
5689                                cast<CXXConstructorDecl>(Definition), Info,
5690                                Result);
5691 }
5692 
5693 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5694     const CXXInheritedCtorInitExpr *E) {
5695   if (!Info.CurrentCall) {
5696     assert(Info.checkingPotentialConstantExpression());
5697     return false;
5698   }
5699 
5700   const CXXConstructorDecl *FD = E->getConstructor();
5701   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5702     return false;
5703 
5704   const FunctionDecl *Definition = nullptr;
5705   auto Body = FD->getBody(Definition);
5706 
5707   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5708     return false;
5709 
5710   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
5711                                cast<CXXConstructorDecl>(Definition), Info,
5712                                Result);
5713 }
5714 
5715 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5716     const CXXStdInitializerListExpr *E) {
5717   const ConstantArrayType *ArrayType =
5718       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5719 
5720   LValue Array;
5721   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5722     return false;
5723 
5724   // Get a pointer to the first element of the array.
5725   Array.addArray(Info, E, ArrayType);
5726 
5727   // FIXME: Perform the checks on the field types in SemaInit.
5728   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5729   RecordDecl::field_iterator Field = Record->field_begin();
5730   if (Field == Record->field_end())
5731     return Error(E);
5732 
5733   // Start pointer.
5734   if (!Field->getType()->isPointerType() ||
5735       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5736                             ArrayType->getElementType()))
5737     return Error(E);
5738 
5739   // FIXME: What if the initializer_list type has base classes, etc?
5740   Result = APValue(APValue::UninitStruct(), 0, 2);
5741   Array.moveInto(Result.getStructField(0));
5742 
5743   if (++Field == Record->field_end())
5744     return Error(E);
5745 
5746   if (Field->getType()->isPointerType() &&
5747       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5748                            ArrayType->getElementType())) {
5749     // End pointer.
5750     if (!HandleLValueArrayAdjustment(Info, E, Array,
5751                                      ArrayType->getElementType(),
5752                                      ArrayType->getSize().getZExtValue()))
5753       return false;
5754     Array.moveInto(Result.getStructField(1));
5755   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5756     // Length.
5757     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5758   else
5759     return Error(E);
5760 
5761   if (++Field != Record->field_end())
5762     return Error(E);
5763 
5764   return true;
5765 }
5766 
5767 static bool EvaluateRecord(const Expr *E, const LValue &This,
5768                            APValue &Result, EvalInfo &Info) {
5769   assert(E->isRValue() && E->getType()->isRecordType() &&
5770          "can't evaluate expression as a record rvalue");
5771   return RecordExprEvaluator(Info, This, Result).Visit(E);
5772 }
5773 
5774 //===----------------------------------------------------------------------===//
5775 // Temporary Evaluation
5776 //
5777 // Temporaries are represented in the AST as rvalues, but generally behave like
5778 // lvalues. The full-object of which the temporary is a subobject is implicitly
5779 // materialized so that a reference can bind to it.
5780 //===----------------------------------------------------------------------===//
5781 namespace {
5782 class TemporaryExprEvaluator
5783   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5784 public:
5785   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5786     LValueExprEvaluatorBaseTy(Info, Result) {}
5787 
5788   /// Visit an expression which constructs the value of this temporary.
5789   bool VisitConstructExpr(const Expr *E) {
5790     Result.set(E, Info.CurrentCall->Index);
5791     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5792                            Info, Result, E);
5793   }
5794 
5795   bool VisitCastExpr(const CastExpr *E) {
5796     switch (E->getCastKind()) {
5797     default:
5798       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5799 
5800     case CK_ConstructorConversion:
5801       return VisitConstructExpr(E->getSubExpr());
5802     }
5803   }
5804   bool VisitInitListExpr(const InitListExpr *E) {
5805     return VisitConstructExpr(E);
5806   }
5807   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5808     return VisitConstructExpr(E);
5809   }
5810   bool VisitCallExpr(const CallExpr *E) {
5811     return VisitConstructExpr(E);
5812   }
5813   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5814     return VisitConstructExpr(E);
5815   }
5816 };
5817 } // end anonymous namespace
5818 
5819 /// Evaluate an expression of record type as a temporary.
5820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5821   assert(E->isRValue() && E->getType()->isRecordType());
5822   return TemporaryExprEvaluator(Info, Result).Visit(E);
5823 }
5824 
5825 //===----------------------------------------------------------------------===//
5826 // Vector Evaluation
5827 //===----------------------------------------------------------------------===//
5828 
5829 namespace {
5830   class VectorExprEvaluator
5831   : public ExprEvaluatorBase<VectorExprEvaluator> {
5832     APValue &Result;
5833   public:
5834 
5835     VectorExprEvaluator(EvalInfo &info, APValue &Result)
5836       : ExprEvaluatorBaseTy(info), Result(Result) {}
5837 
5838     bool Success(ArrayRef<APValue> V, const Expr *E) {
5839       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5840       // FIXME: remove this APValue copy.
5841       Result = APValue(V.data(), V.size());
5842       return true;
5843     }
5844     bool Success(const APValue &V, const Expr *E) {
5845       assert(V.isVector());
5846       Result = V;
5847       return true;
5848     }
5849     bool ZeroInitialization(const Expr *E);
5850 
5851     bool VisitUnaryReal(const UnaryOperator *E)
5852       { return Visit(E->getSubExpr()); }
5853     bool VisitCastExpr(const CastExpr* E);
5854     bool VisitInitListExpr(const InitListExpr *E);
5855     bool VisitUnaryImag(const UnaryOperator *E);
5856     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5857     //                 binary comparisons, binary and/or/xor,
5858     //                 shufflevector, ExtVectorElementExpr
5859   };
5860 } // end anonymous namespace
5861 
5862 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5863   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5864   return VectorExprEvaluator(Info, Result).Visit(E);
5865 }
5866 
5867 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
5868   const VectorType *VTy = E->getType()->castAs<VectorType>();
5869   unsigned NElts = VTy->getNumElements();
5870 
5871   const Expr *SE = E->getSubExpr();
5872   QualType SETy = SE->getType();
5873 
5874   switch (E->getCastKind()) {
5875   case CK_VectorSplat: {
5876     APValue Val = APValue();
5877     if (SETy->isIntegerType()) {
5878       APSInt IntResult;
5879       if (!EvaluateInteger(SE, IntResult, Info))
5880         return false;
5881       Val = APValue(std::move(IntResult));
5882     } else if (SETy->isRealFloatingType()) {
5883       APFloat FloatResult(0.0);
5884       if (!EvaluateFloat(SE, FloatResult, Info))
5885         return false;
5886       Val = APValue(std::move(FloatResult));
5887     } else {
5888       return Error(E);
5889     }
5890 
5891     // Splat and create vector APValue.
5892     SmallVector<APValue, 4> Elts(NElts, Val);
5893     return Success(Elts, E);
5894   }
5895   case CK_BitCast: {
5896     // Evaluate the operand into an APInt we can extract from.
5897     llvm::APInt SValInt;
5898     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5899       return false;
5900     // Extract the elements
5901     QualType EltTy = VTy->getElementType();
5902     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5903     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5904     SmallVector<APValue, 4> Elts;
5905     if (EltTy->isRealFloatingType()) {
5906       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5907       unsigned FloatEltSize = EltSize;
5908       if (&Sem == &APFloat::x87DoubleExtended)
5909         FloatEltSize = 80;
5910       for (unsigned i = 0; i < NElts; i++) {
5911         llvm::APInt Elt;
5912         if (BigEndian)
5913           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5914         else
5915           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5916         Elts.push_back(APValue(APFloat(Sem, Elt)));
5917       }
5918     } else if (EltTy->isIntegerType()) {
5919       for (unsigned i = 0; i < NElts; i++) {
5920         llvm::APInt Elt;
5921         if (BigEndian)
5922           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5923         else
5924           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5925         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5926       }
5927     } else {
5928       return Error(E);
5929     }
5930     return Success(Elts, E);
5931   }
5932   default:
5933     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5934   }
5935 }
5936 
5937 bool
5938 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5939   const VectorType *VT = E->getType()->castAs<VectorType>();
5940   unsigned NumInits = E->getNumInits();
5941   unsigned NumElements = VT->getNumElements();
5942 
5943   QualType EltTy = VT->getElementType();
5944   SmallVector<APValue, 4> Elements;
5945 
5946   // The number of initializers can be less than the number of
5947   // vector elements. For OpenCL, this can be due to nested vector
5948   // initialization. For GCC compatibility, missing trailing elements
5949   // should be initialized with zeroes.
5950   unsigned CountInits = 0, CountElts = 0;
5951   while (CountElts < NumElements) {
5952     // Handle nested vector initialization.
5953     if (CountInits < NumInits
5954         && E->getInit(CountInits)->getType()->isVectorType()) {
5955       APValue v;
5956       if (!EvaluateVector(E->getInit(CountInits), v, Info))
5957         return Error(E);
5958       unsigned vlen = v.getVectorLength();
5959       for (unsigned j = 0; j < vlen; j++)
5960         Elements.push_back(v.getVectorElt(j));
5961       CountElts += vlen;
5962     } else if (EltTy->isIntegerType()) {
5963       llvm::APSInt sInt(32);
5964       if (CountInits < NumInits) {
5965         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5966           return false;
5967       } else // trailing integer zero.
5968         sInt = Info.Ctx.MakeIntValue(0, EltTy);
5969       Elements.push_back(APValue(sInt));
5970       CountElts++;
5971     } else {
5972       llvm::APFloat f(0.0);
5973       if (CountInits < NumInits) {
5974         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5975           return false;
5976       } else // trailing float zero.
5977         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5978       Elements.push_back(APValue(f));
5979       CountElts++;
5980     }
5981     CountInits++;
5982   }
5983   return Success(Elements, E);
5984 }
5985 
5986 bool
5987 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5988   const VectorType *VT = E->getType()->getAs<VectorType>();
5989   QualType EltTy = VT->getElementType();
5990   APValue ZeroElement;
5991   if (EltTy->isIntegerType())
5992     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5993   else
5994     ZeroElement =
5995         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5996 
5997   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5998   return Success(Elements, E);
5999 }
6000 
6001 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6002   VisitIgnoredValue(E->getSubExpr());
6003   return ZeroInitialization(E);
6004 }
6005 
6006 //===----------------------------------------------------------------------===//
6007 // Array Evaluation
6008 //===----------------------------------------------------------------------===//
6009 
6010 namespace {
6011   class ArrayExprEvaluator
6012   : public ExprEvaluatorBase<ArrayExprEvaluator> {
6013     const LValue &This;
6014     APValue &Result;
6015   public:
6016 
6017     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6018       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6019 
6020     bool Success(const APValue &V, const Expr *E) {
6021       assert((V.isArray() || V.isLValue()) &&
6022              "expected array or string literal");
6023       Result = V;
6024       return true;
6025     }
6026 
6027     bool ZeroInitialization(const Expr *E) {
6028       const ConstantArrayType *CAT =
6029           Info.Ctx.getAsConstantArrayType(E->getType());
6030       if (!CAT)
6031         return Error(E);
6032 
6033       Result = APValue(APValue::UninitArray(), 0,
6034                        CAT->getSize().getZExtValue());
6035       if (!Result.hasArrayFiller()) return true;
6036 
6037       // Zero-initialize all elements.
6038       LValue Subobject = This;
6039       Subobject.addArray(Info, E, CAT);
6040       ImplicitValueInitExpr VIE(CAT->getElementType());
6041       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6042     }
6043 
6044     bool VisitCallExpr(const CallExpr *E) {
6045       return handleCallExpr(E, Result, &This);
6046     }
6047     bool VisitInitListExpr(const InitListExpr *E);
6048     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6049     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6050                                const LValue &Subobject,
6051                                APValue *Value, QualType Type);
6052   };
6053 } // end anonymous namespace
6054 
6055 static bool EvaluateArray(const Expr *E, const LValue &This,
6056                           APValue &Result, EvalInfo &Info) {
6057   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6058   return ArrayExprEvaluator(Info, This, Result).Visit(E);
6059 }
6060 
6061 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6062   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6063   if (!CAT)
6064     return Error(E);
6065 
6066   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6067   // an appropriately-typed string literal enclosed in braces.
6068   if (E->isStringLiteralInit()) {
6069     LValue LV;
6070     if (!EvaluateLValue(E->getInit(0), LV, Info))
6071       return false;
6072     APValue Val;
6073     LV.moveInto(Val);
6074     return Success(Val, E);
6075   }
6076 
6077   bool Success = true;
6078 
6079   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6080          "zero-initialized array shouldn't have any initialized elts");
6081   APValue Filler;
6082   if (Result.isArray() && Result.hasArrayFiller())
6083     Filler = Result.getArrayFiller();
6084 
6085   unsigned NumEltsToInit = E->getNumInits();
6086   unsigned NumElts = CAT->getSize().getZExtValue();
6087   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6088 
6089   // If the initializer might depend on the array index, run it for each
6090   // array element. For now, just whitelist non-class value-initialization.
6091   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6092     NumEltsToInit = NumElts;
6093 
6094   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6095 
6096   // If the array was previously zero-initialized, preserve the
6097   // zero-initialized values.
6098   if (!Filler.isUninit()) {
6099     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6100       Result.getArrayInitializedElt(I) = Filler;
6101     if (Result.hasArrayFiller())
6102       Result.getArrayFiller() = Filler;
6103   }
6104 
6105   LValue Subobject = This;
6106   Subobject.addArray(Info, E, CAT);
6107   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6108     const Expr *Init =
6109         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6110     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6111                          Info, Subobject, Init) ||
6112         !HandleLValueArrayAdjustment(Info, Init, Subobject,
6113                                      CAT->getElementType(), 1)) {
6114       if (!Info.noteFailure())
6115         return false;
6116       Success = false;
6117     }
6118   }
6119 
6120   if (!Result.hasArrayFiller())
6121     return Success;
6122 
6123   // If we get here, we have a trivial filler, which we can just evaluate
6124   // once and splat over the rest of the array elements.
6125   assert(FillerExpr && "no array filler for incomplete init list");
6126   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6127                          FillerExpr) && Success;
6128 }
6129 
6130 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6131   return VisitCXXConstructExpr(E, This, &Result, E->getType());
6132 }
6133 
6134 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6135                                                const LValue &Subobject,
6136                                                APValue *Value,
6137                                                QualType Type) {
6138   bool HadZeroInit = !Value->isUninit();
6139 
6140   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6141     unsigned N = CAT->getSize().getZExtValue();
6142 
6143     // Preserve the array filler if we had prior zero-initialization.
6144     APValue Filler =
6145       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6146                                              : APValue();
6147 
6148     *Value = APValue(APValue::UninitArray(), N, N);
6149 
6150     if (HadZeroInit)
6151       for (unsigned I = 0; I != N; ++I)
6152         Value->getArrayInitializedElt(I) = Filler;
6153 
6154     // Initialize the elements.
6155     LValue ArrayElt = Subobject;
6156     ArrayElt.addArray(Info, E, CAT);
6157     for (unsigned I = 0; I != N; ++I)
6158       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6159                                  CAT->getElementType()) ||
6160           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6161                                        CAT->getElementType(), 1))
6162         return false;
6163 
6164     return true;
6165   }
6166 
6167   if (!Type->isRecordType())
6168     return Error(E);
6169 
6170   return RecordExprEvaluator(Info, Subobject, *Value)
6171              .VisitCXXConstructExpr(E, Type);
6172 }
6173 
6174 //===----------------------------------------------------------------------===//
6175 // Integer Evaluation
6176 //
6177 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6178 // types and back in constant folding. Integer values are thus represented
6179 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6180 //===----------------------------------------------------------------------===//
6181 
6182 namespace {
6183 class IntExprEvaluator
6184   : public ExprEvaluatorBase<IntExprEvaluator> {
6185   APValue &Result;
6186 public:
6187   IntExprEvaluator(EvalInfo &info, APValue &result)
6188     : ExprEvaluatorBaseTy(info), Result(result) {}
6189 
6190   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6191     assert(E->getType()->isIntegralOrEnumerationType() &&
6192            "Invalid evaluation result.");
6193     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6194            "Invalid evaluation result.");
6195     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6196            "Invalid evaluation result.");
6197     Result = APValue(SI);
6198     return true;
6199   }
6200   bool Success(const llvm::APSInt &SI, const Expr *E) {
6201     return Success(SI, E, Result);
6202   }
6203 
6204   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6205     assert(E->getType()->isIntegralOrEnumerationType() &&
6206            "Invalid evaluation result.");
6207     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6208            "Invalid evaluation result.");
6209     Result = APValue(APSInt(I));
6210     Result.getInt().setIsUnsigned(
6211                             E->getType()->isUnsignedIntegerOrEnumerationType());
6212     return true;
6213   }
6214   bool Success(const llvm::APInt &I, const Expr *E) {
6215     return Success(I, E, Result);
6216   }
6217 
6218   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6219     assert(E->getType()->isIntegralOrEnumerationType() &&
6220            "Invalid evaluation result.");
6221     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6222     return true;
6223   }
6224   bool Success(uint64_t Value, const Expr *E) {
6225     return Success(Value, E, Result);
6226   }
6227 
6228   bool Success(CharUnits Size, const Expr *E) {
6229     return Success(Size.getQuantity(), E);
6230   }
6231 
6232   bool Success(const APValue &V, const Expr *E) {
6233     if (V.isLValue() || V.isAddrLabelDiff()) {
6234       Result = V;
6235       return true;
6236     }
6237     return Success(V.getInt(), E);
6238   }
6239 
6240   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6241 
6242   //===--------------------------------------------------------------------===//
6243   //                            Visitor Methods
6244   //===--------------------------------------------------------------------===//
6245 
6246   bool VisitIntegerLiteral(const IntegerLiteral *E) {
6247     return Success(E->getValue(), E);
6248   }
6249   bool VisitCharacterLiteral(const CharacterLiteral *E) {
6250     return Success(E->getValue(), E);
6251   }
6252 
6253   bool CheckReferencedDecl(const Expr *E, const Decl *D);
6254   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6255     if (CheckReferencedDecl(E, E->getDecl()))
6256       return true;
6257 
6258     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6259   }
6260   bool VisitMemberExpr(const MemberExpr *E) {
6261     if (CheckReferencedDecl(E, E->getMemberDecl())) {
6262       VisitIgnoredBaseExpression(E->getBase());
6263       return true;
6264     }
6265 
6266     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6267   }
6268 
6269   bool VisitCallExpr(const CallExpr *E);
6270   bool VisitBinaryOperator(const BinaryOperator *E);
6271   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6272   bool VisitUnaryOperator(const UnaryOperator *E);
6273 
6274   bool VisitCastExpr(const CastExpr* E);
6275   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6276 
6277   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6278     return Success(E->getValue(), E);
6279   }
6280 
6281   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6282     return Success(E->getValue(), E);
6283   }
6284 
6285   // Note, GNU defines __null as an integer, not a pointer.
6286   bool VisitGNUNullExpr(const GNUNullExpr *E) {
6287     return ZeroInitialization(E);
6288   }
6289 
6290   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6291     return Success(E->getValue(), E);
6292   }
6293 
6294   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6295     return Success(E->getValue(), E);
6296   }
6297 
6298   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6299     return Success(E->getValue(), E);
6300   }
6301 
6302   bool VisitUnaryReal(const UnaryOperator *E);
6303   bool VisitUnaryImag(const UnaryOperator *E);
6304 
6305   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6306   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6307 
6308 private:
6309   bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
6310   // FIXME: Missing: array subscript of vector, member of vector
6311 };
6312 } // end anonymous namespace
6313 
6314 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6315 /// produce either the integer value or a pointer.
6316 ///
6317 /// GCC has a heinous extension which folds casts between pointer types and
6318 /// pointer-sized integral types. We support this by allowing the evaluation of
6319 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6320 /// Some simple arithmetic on such values is supported (they are treated much
6321 /// like char*).
6322 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6323                                     EvalInfo &Info) {
6324   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6325   return IntExprEvaluator(Info, Result).Visit(E);
6326 }
6327 
6328 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6329   APValue Val;
6330   if (!EvaluateIntegerOrLValue(E, Val, Info))
6331     return false;
6332   if (!Val.isInt()) {
6333     // FIXME: It would be better to produce the diagnostic for casting
6334     //        a pointer to an integer.
6335     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6336     return false;
6337   }
6338   Result = Val.getInt();
6339   return true;
6340 }
6341 
6342 /// Check whether the given declaration can be directly converted to an integral
6343 /// rvalue. If not, no diagnostic is produced; there are other things we can
6344 /// try.
6345 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6346   // Enums are integer constant exprs.
6347   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6348     // Check for signedness/width mismatches between E type and ECD value.
6349     bool SameSign = (ECD->getInitVal().isSigned()
6350                      == E->getType()->isSignedIntegerOrEnumerationType());
6351     bool SameWidth = (ECD->getInitVal().getBitWidth()
6352                       == Info.Ctx.getIntWidth(E->getType()));
6353     if (SameSign && SameWidth)
6354       return Success(ECD->getInitVal(), E);
6355     else {
6356       // Get rid of mismatch (otherwise Success assertions will fail)
6357       // by computing a new value matching the type of E.
6358       llvm::APSInt Val = ECD->getInitVal();
6359       if (!SameSign)
6360         Val.setIsSigned(!ECD->getInitVal().isSigned());
6361       if (!SameWidth)
6362         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6363       return Success(Val, E);
6364     }
6365   }
6366   return false;
6367 }
6368 
6369 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6370 /// as GCC.
6371 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6372                                        const LangOptions &LangOpts) {
6373   // The following enum mimics the values returned by GCC.
6374   // FIXME: Does GCC differ between lvalue and rvalue references here?
6375   enum gcc_type_class {
6376     no_type_class = -1,
6377     void_type_class, integer_type_class, char_type_class,
6378     enumeral_type_class, boolean_type_class,
6379     pointer_type_class, reference_type_class, offset_type_class,
6380     real_type_class, complex_type_class,
6381     function_type_class, method_type_class,
6382     record_type_class, union_type_class,
6383     array_type_class, string_type_class,
6384     lang_type_class
6385   };
6386 
6387   // If no argument was supplied, default to "no_type_class". This isn't
6388   // ideal, however it is what gcc does.
6389   if (E->getNumArgs() == 0)
6390     return no_type_class;
6391 
6392   QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6393   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6394 
6395   switch (CanTy->getTypeClass()) {
6396 #define TYPE(ID, BASE)
6397 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6398 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6399 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6400 #include "clang/AST/TypeNodes.def"
6401       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6402 
6403   case Type::Builtin:
6404     switch (BT->getKind()) {
6405 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6406 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6407 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6408 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6409 #include "clang/AST/BuiltinTypes.def"
6410     case BuiltinType::Void:
6411       return void_type_class;
6412 
6413     case BuiltinType::Bool:
6414       return boolean_type_class;
6415 
6416     case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6417     case BuiltinType::UChar:
6418     case BuiltinType::UShort:
6419     case BuiltinType::UInt:
6420     case BuiltinType::ULong:
6421     case BuiltinType::ULongLong:
6422     case BuiltinType::UInt128:
6423       return integer_type_class;
6424 
6425     case BuiltinType::NullPtr:
6426       return pointer_type_class;
6427 
6428     case BuiltinType::WChar_U:
6429     case BuiltinType::Char16:
6430     case BuiltinType::Char32:
6431     case BuiltinType::ObjCId:
6432     case BuiltinType::ObjCClass:
6433     case BuiltinType::ObjCSel:
6434 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6435     case BuiltinType::Id:
6436 #include "clang/Basic/OpenCLImageTypes.def"
6437     case BuiltinType::OCLSampler:
6438     case BuiltinType::OCLEvent:
6439     case BuiltinType::OCLClkEvent:
6440     case BuiltinType::OCLQueue:
6441     case BuiltinType::OCLNDRange:
6442     case BuiltinType::OCLReserveID:
6443     case BuiltinType::Dependent:
6444       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6445     };
6446 
6447   case Type::Enum:
6448     return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6449     break;
6450 
6451   case Type::Pointer:
6452     return pointer_type_class;
6453     break;
6454 
6455   case Type::MemberPointer:
6456     if (CanTy->isMemberDataPointerType())
6457       return offset_type_class;
6458     else {
6459       // We expect member pointers to be either data or function pointers,
6460       // nothing else.
6461       assert(CanTy->isMemberFunctionPointerType());
6462       return method_type_class;
6463     }
6464 
6465   case Type::Complex:
6466     return complex_type_class;
6467 
6468   case Type::FunctionNoProto:
6469   case Type::FunctionProto:
6470     return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6471 
6472   case Type::Record:
6473     if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6474       switch (RT->getDecl()->getTagKind()) {
6475       case TagTypeKind::TTK_Struct:
6476       case TagTypeKind::TTK_Class:
6477       case TagTypeKind::TTK_Interface:
6478         return record_type_class;
6479 
6480       case TagTypeKind::TTK_Enum:
6481         return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6482 
6483       case TagTypeKind::TTK_Union:
6484         return union_type_class;
6485       }
6486     }
6487     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6488 
6489   case Type::ConstantArray:
6490   case Type::VariableArray:
6491   case Type::IncompleteArray:
6492     return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6493 
6494   case Type::BlockPointer:
6495   case Type::LValueReference:
6496   case Type::RValueReference:
6497   case Type::Vector:
6498   case Type::ExtVector:
6499   case Type::Auto:
6500   case Type::ObjCObject:
6501   case Type::ObjCInterface:
6502   case Type::ObjCObjectPointer:
6503   case Type::Pipe:
6504   case Type::Atomic:
6505     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6506   }
6507 
6508   llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6509 }
6510 
6511 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6512 /// __builtin_constant_p when applied to the given lvalue.
6513 ///
6514 /// An lvalue is only "constant" if it is a pointer or reference to the first
6515 /// character of a string literal.
6516 template<typename LValue>
6517 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6518   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6519   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6520 }
6521 
6522 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6523 /// GCC as we can manage.
6524 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6525   QualType ArgType = Arg->getType();
6526 
6527   // __builtin_constant_p always has one operand. The rules which gcc follows
6528   // are not precisely documented, but are as follows:
6529   //
6530   //  - If the operand is of integral, floating, complex or enumeration type,
6531   //    and can be folded to a known value of that type, it returns 1.
6532   //  - If the operand and can be folded to a pointer to the first character
6533   //    of a string literal (or such a pointer cast to an integral type), it
6534   //    returns 1.
6535   //
6536   // Otherwise, it returns 0.
6537   //
6538   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6539   // its support for this does not currently work.
6540   if (ArgType->isIntegralOrEnumerationType()) {
6541     Expr::EvalResult Result;
6542     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6543       return false;
6544 
6545     APValue &V = Result.Val;
6546     if (V.getKind() == APValue::Int)
6547       return true;
6548     if (V.getKind() == APValue::LValue)
6549       return EvaluateBuiltinConstantPForLValue(V);
6550   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6551     return Arg->isEvaluatable(Ctx);
6552   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6553     LValue LV;
6554     Expr::EvalStatus Status;
6555     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6556     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6557                           : EvaluatePointer(Arg, LV, Info)) &&
6558         !Status.HasSideEffects)
6559       return EvaluateBuiltinConstantPForLValue(LV);
6560   }
6561 
6562   // Anything else isn't considered to be sufficiently constant.
6563   return false;
6564 }
6565 
6566 /// Retrieves the "underlying object type" of the given expression,
6567 /// as used by __builtin_object_size.
6568 static QualType getObjectType(APValue::LValueBase B) {
6569   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6570     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6571       return VD->getType();
6572   } else if (const Expr *E = B.get<const Expr*>()) {
6573     if (isa<CompoundLiteralExpr>(E))
6574       return E->getType();
6575   }
6576 
6577   return QualType();
6578 }
6579 
6580 /// A more selective version of E->IgnoreParenCasts for
6581 /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6582 /// to change the type of E.
6583 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6584 ///
6585 /// Always returns an RValue with a pointer representation.
6586 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6587   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6588 
6589   auto *NoParens = E->IgnoreParens();
6590   auto *Cast = dyn_cast<CastExpr>(NoParens);
6591   if (Cast == nullptr)
6592     return NoParens;
6593 
6594   // We only conservatively allow a few kinds of casts, because this code is
6595   // inherently a simple solution that seeks to support the common case.
6596   auto CastKind = Cast->getCastKind();
6597   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6598       CastKind != CK_AddressSpaceConversion)
6599     return NoParens;
6600 
6601   auto *SubExpr = Cast->getSubExpr();
6602   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6603     return NoParens;
6604   return ignorePointerCastsAndParens(SubExpr);
6605 }
6606 
6607 /// Checks to see if the given LValue's Designator is at the end of the LValue's
6608 /// record layout. e.g.
6609 ///   struct { struct { int a, b; } fst, snd; } obj;
6610 ///   obj.fst   // no
6611 ///   obj.snd   // yes
6612 ///   obj.fst.a // no
6613 ///   obj.fst.b // no
6614 ///   obj.snd.a // no
6615 ///   obj.snd.b // yes
6616 ///
6617 /// Please note: this function is specialized for how __builtin_object_size
6618 /// views "objects".
6619 ///
6620 /// If this encounters an invalid RecordDecl, it will always return true.
6621 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6622   assert(!LVal.Designator.Invalid);
6623 
6624   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6625     const RecordDecl *Parent = FD->getParent();
6626     Invalid = Parent->isInvalidDecl();
6627     if (Invalid || Parent->isUnion())
6628       return true;
6629     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
6630     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6631   };
6632 
6633   auto &Base = LVal.getLValueBase();
6634   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6635     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6636       bool Invalid;
6637       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6638         return Invalid;
6639     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6640       for (auto *FD : IFD->chain()) {
6641         bool Invalid;
6642         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6643           return Invalid;
6644       }
6645     }
6646   }
6647 
6648   QualType BaseType = getType(Base);
6649   for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6650     if (BaseType->isArrayType()) {
6651       // Because __builtin_object_size treats arrays as objects, we can ignore
6652       // the index iff this is the last array in the Designator.
6653       if (I + 1 == E)
6654         return true;
6655       auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6656       uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6657       if (Index + 1 != CAT->getSize())
6658         return false;
6659       BaseType = CAT->getElementType();
6660     } else if (BaseType->isAnyComplexType()) {
6661       auto *CT = BaseType->castAs<ComplexType>();
6662       uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6663       if (Index != 1)
6664         return false;
6665       BaseType = CT->getElementType();
6666     } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6667       bool Invalid;
6668       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6669         return Invalid;
6670       BaseType = FD->getType();
6671     } else {
6672       assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6673              "Expecting cast to a base class");
6674       return false;
6675     }
6676   }
6677   return true;
6678 }
6679 
6680 /// Tests to see if the LValue has a designator (that isn't necessarily valid).
6681 static bool refersToCompleteObject(const LValue &LVal) {
6682   if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6683     return false;
6684 
6685   if (!LVal.InvalidBase)
6686     return true;
6687 
6688   auto *E = LVal.Base.dyn_cast<const Expr *>();
6689   (void)E;
6690   assert(E != nullptr && isa<MemberExpr>(E));
6691   return false;
6692 }
6693 
6694 /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6695 /// true and stores the result in @p Size.
6696 ///
6697 /// If @p WasError is non-null, this will report whether the failure to evaluate
6698 /// is to be treated as an Error in IntExprEvaluator.
6699 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6700                                          EvalInfo &Info, uint64_t &Size,
6701                                          bool *WasError = nullptr) {
6702   if (WasError != nullptr)
6703     *WasError = false;
6704 
6705   auto Error = [&](const Expr *E) {
6706     if (WasError != nullptr)
6707       *WasError = true;
6708     return false;
6709   };
6710 
6711   auto Success = [&](uint64_t S, const Expr *E) {
6712     Size = S;
6713     return true;
6714   };
6715 
6716   // Determine the denoted object.
6717   LValue Base;
6718   {
6719     // The operand of __builtin_object_size is never evaluated for side-effects.
6720     // If there are any, but we can determine the pointed-to object anyway, then
6721     // ignore the side-effects.
6722     SpeculativeEvaluationRAII SpeculativeEval(Info);
6723     FoldOffsetRAII Fold(Info, Type & 1);
6724 
6725     if (E->isGLValue()) {
6726       // It's possible for us to be given GLValues if we're called via
6727       // Expr::tryEvaluateObjectSize.
6728       APValue RVal;
6729       if (!EvaluateAsRValue(Info, E, RVal))
6730         return false;
6731       Base.setFrom(Info.Ctx, RVal);
6732     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
6733       return false;
6734   }
6735 
6736   CharUnits BaseOffset = Base.getLValueOffset();
6737   // If we point to before the start of the object, there are no accessible
6738   // bytes.
6739   if (BaseOffset.isNegative())
6740     return Success(0, E);
6741 
6742   // In the case where we're not dealing with a subobject, we discard the
6743   // subobject bit.
6744   bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
6745 
6746   // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6747   // exist. If we can't verify the base, then we can't do that.
6748   //
6749   // As a special case, we produce a valid object size for an unknown object
6750   // with a known designator if Type & 1 is 1. For instance:
6751   //
6752   //   extern struct X { char buff[32]; int a, b, c; } *p;
6753   //   int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6754   //   int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6755   //
6756   // This matches GCC's behavior.
6757   if (Base.InvalidBase && !SubobjectOnly)
6758     return Error(E);
6759 
6760   // If we're not examining only the subobject, then we reset to a complete
6761   // object designator
6762   //
6763   // If Type is 1 and we've lost track of the subobject, just find the complete
6764   // object instead. (If Type is 3, that's not correct behavior and we should
6765   // return 0 instead.)
6766   LValue End = Base;
6767   if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
6768     QualType T = getObjectType(End.getLValueBase());
6769     if (T.isNull())
6770       End.Designator.setInvalid();
6771     else {
6772       End.Designator = SubobjectDesignator(T);
6773       End.Offset = CharUnits::Zero();
6774     }
6775   }
6776 
6777   // If it is not possible to determine which objects ptr points to at compile
6778   // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6779   // and (size_t) 0 for type 2 or 3.
6780   if (End.Designator.Invalid)
6781     return false;
6782 
6783   // According to the GCC documentation, we want the size of the subobject
6784   // denoted by the pointer. But that's not quite right -- what we actually
6785   // want is the size of the immediately-enclosing array, if there is one.
6786   int64_t AmountToAdd = 1;
6787   if (End.Designator.MostDerivedIsArrayElement &&
6788       End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6789     // We got a pointer to an array. Step to its end.
6790     AmountToAdd = End.Designator.MostDerivedArraySize -
6791                   End.Designator.Entries.back().ArrayIndex;
6792   } else if (End.Designator.isOnePastTheEnd()) {
6793     // We're already pointing at the end of the object.
6794     AmountToAdd = 0;
6795   }
6796 
6797   QualType PointeeType = End.Designator.MostDerivedType;
6798   assert(!PointeeType.isNull());
6799   if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
6800     return Error(E);
6801 
6802   if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6803                                    AmountToAdd))
6804     return false;
6805 
6806   auto EndOffset = End.getLValueOffset();
6807 
6808   // The following is a moderately common idiom in C:
6809   //
6810   // struct Foo { int a; char c[1]; };
6811   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6812   // strcpy(&F->c[0], Bar);
6813   //
6814   // So, if we see that we're examining a 1-length (or 0-length) array at the
6815   // end of a struct with an unknown base, we give up instead of breaking code
6816   // that behaves this way. Note that we only do this when Type=1, because
6817   // Type=3 is a lower bound, so answering conservatively is fine.
6818   if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6819       End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6820       End.Designator.MostDerivedIsArrayElement &&
6821       End.Designator.MostDerivedArraySize < 2 &&
6822       isDesignatorAtObjectEnd(Info.Ctx, End))
6823     return false;
6824 
6825   if (BaseOffset > EndOffset)
6826     return Success(0, E);
6827 
6828   return Success((EndOffset - BaseOffset).getQuantity(), E);
6829 }
6830 
6831 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6832                                                     unsigned Type) {
6833   uint64_t Size;
6834   bool WasError;
6835   if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6836     return Success(Size, E);
6837   if (WasError)
6838     return Error(E);
6839   return false;
6840 }
6841 
6842 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6843   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6844   default:
6845     return ExprEvaluatorBaseTy::VisitCallExpr(E);
6846 
6847   case Builtin::BI__builtin_object_size: {
6848     // The type was checked when we built the expression.
6849     unsigned Type =
6850         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6851     assert(Type <= 3 && "unexpected type");
6852 
6853     if (TryEvaluateBuiltinObjectSize(E, Type))
6854       return true;
6855 
6856     if (E->getArg(0)->HasSideEffects(Info.Ctx))
6857       return Success((Type & 2) ? 0 : -1, E);
6858 
6859     // Expression had no side effects, but we couldn't statically determine the
6860     // size of the referenced object.
6861     switch (Info.EvalMode) {
6862     case EvalInfo::EM_ConstantExpression:
6863     case EvalInfo::EM_PotentialConstantExpression:
6864     case EvalInfo::EM_ConstantFold:
6865     case EvalInfo::EM_EvaluateForOverflow:
6866     case EvalInfo::EM_IgnoreSideEffects:
6867     case EvalInfo::EM_DesignatorFold:
6868       // Leave it to IR generation.
6869       return Error(E);
6870     case EvalInfo::EM_ConstantExpressionUnevaluated:
6871     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6872       // Reduce it to a constant now.
6873       return Success((Type & 2) ? 0 : -1, E);
6874     }
6875 
6876     llvm_unreachable("unexpected EvalMode");
6877   }
6878 
6879   case Builtin::BI__builtin_bswap16:
6880   case Builtin::BI__builtin_bswap32:
6881   case Builtin::BI__builtin_bswap64: {
6882     APSInt Val;
6883     if (!EvaluateInteger(E->getArg(0), Val, Info))
6884       return false;
6885 
6886     return Success(Val.byteSwap(), E);
6887   }
6888 
6889   case Builtin::BI__builtin_classify_type:
6890     return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
6891 
6892   // FIXME: BI__builtin_clrsb
6893   // FIXME: BI__builtin_clrsbl
6894   // FIXME: BI__builtin_clrsbll
6895 
6896   case Builtin::BI__builtin_clz:
6897   case Builtin::BI__builtin_clzl:
6898   case Builtin::BI__builtin_clzll:
6899   case Builtin::BI__builtin_clzs: {
6900     APSInt Val;
6901     if (!EvaluateInteger(E->getArg(0), Val, Info))
6902       return false;
6903     if (!Val)
6904       return Error(E);
6905 
6906     return Success(Val.countLeadingZeros(), E);
6907   }
6908 
6909   case Builtin::BI__builtin_constant_p:
6910     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6911 
6912   case Builtin::BI__builtin_ctz:
6913   case Builtin::BI__builtin_ctzl:
6914   case Builtin::BI__builtin_ctzll:
6915   case Builtin::BI__builtin_ctzs: {
6916     APSInt Val;
6917     if (!EvaluateInteger(E->getArg(0), Val, Info))
6918       return false;
6919     if (!Val)
6920       return Error(E);
6921 
6922     return Success(Val.countTrailingZeros(), E);
6923   }
6924 
6925   case Builtin::BI__builtin_eh_return_data_regno: {
6926     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6927     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6928     return Success(Operand, E);
6929   }
6930 
6931   case Builtin::BI__builtin_expect:
6932     return Visit(E->getArg(0));
6933 
6934   case Builtin::BI__builtin_ffs:
6935   case Builtin::BI__builtin_ffsl:
6936   case Builtin::BI__builtin_ffsll: {
6937     APSInt Val;
6938     if (!EvaluateInteger(E->getArg(0), Val, Info))
6939       return false;
6940 
6941     unsigned N = Val.countTrailingZeros();
6942     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6943   }
6944 
6945   case Builtin::BI__builtin_fpclassify: {
6946     APFloat Val(0.0);
6947     if (!EvaluateFloat(E->getArg(5), Val, Info))
6948       return false;
6949     unsigned Arg;
6950     switch (Val.getCategory()) {
6951     case APFloat::fcNaN: Arg = 0; break;
6952     case APFloat::fcInfinity: Arg = 1; break;
6953     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6954     case APFloat::fcZero: Arg = 4; break;
6955     }
6956     return Visit(E->getArg(Arg));
6957   }
6958 
6959   case Builtin::BI__builtin_isinf_sign: {
6960     APFloat Val(0.0);
6961     return EvaluateFloat(E->getArg(0), Val, Info) &&
6962            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6963   }
6964 
6965   case Builtin::BI__builtin_isinf: {
6966     APFloat Val(0.0);
6967     return EvaluateFloat(E->getArg(0), Val, Info) &&
6968            Success(Val.isInfinity() ? 1 : 0, E);
6969   }
6970 
6971   case Builtin::BI__builtin_isfinite: {
6972     APFloat Val(0.0);
6973     return EvaluateFloat(E->getArg(0), Val, Info) &&
6974            Success(Val.isFinite() ? 1 : 0, E);
6975   }
6976 
6977   case Builtin::BI__builtin_isnan: {
6978     APFloat Val(0.0);
6979     return EvaluateFloat(E->getArg(0), Val, Info) &&
6980            Success(Val.isNaN() ? 1 : 0, E);
6981   }
6982 
6983   case Builtin::BI__builtin_isnormal: {
6984     APFloat Val(0.0);
6985     return EvaluateFloat(E->getArg(0), Val, Info) &&
6986            Success(Val.isNormal() ? 1 : 0, E);
6987   }
6988 
6989   case Builtin::BI__builtin_parity:
6990   case Builtin::BI__builtin_parityl:
6991   case Builtin::BI__builtin_parityll: {
6992     APSInt Val;
6993     if (!EvaluateInteger(E->getArg(0), Val, Info))
6994       return false;
6995 
6996     return Success(Val.countPopulation() % 2, E);
6997   }
6998 
6999   case Builtin::BI__builtin_popcount:
7000   case Builtin::BI__builtin_popcountl:
7001   case Builtin::BI__builtin_popcountll: {
7002     APSInt Val;
7003     if (!EvaluateInteger(E->getArg(0), Val, Info))
7004       return false;
7005 
7006     return Success(Val.countPopulation(), E);
7007   }
7008 
7009   case Builtin::BIstrlen:
7010     // A call to strlen is not a constant expression.
7011     if (Info.getLangOpts().CPlusPlus11)
7012       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7013         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
7014     else
7015       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7016     // Fall through.
7017   case Builtin::BI__builtin_strlen: {
7018     // As an extension, we support __builtin_strlen() as a constant expression,
7019     // and support folding strlen() to a constant.
7020     LValue String;
7021     if (!EvaluatePointer(E->getArg(0), String, Info))
7022       return false;
7023 
7024     // Fast path: if it's a string literal, search the string value.
7025     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7026             String.getLValueBase().dyn_cast<const Expr *>())) {
7027       // The string literal may have embedded null characters. Find the first
7028       // one and truncate there.
7029       StringRef Str = S->getBytes();
7030       int64_t Off = String.Offset.getQuantity();
7031       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7032           S->getCharByteWidth() == 1) {
7033         Str = Str.substr(Off);
7034 
7035         StringRef::size_type Pos = Str.find(0);
7036         if (Pos != StringRef::npos)
7037           Str = Str.substr(0, Pos);
7038 
7039         return Success(Str.size(), E);
7040       }
7041 
7042       // Fall through to slow path to issue appropriate diagnostic.
7043     }
7044 
7045     // Slow path: scan the bytes of the string looking for the terminating 0.
7046     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7047     for (uint64_t Strlen = 0; /**/; ++Strlen) {
7048       APValue Char;
7049       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7050           !Char.isInt())
7051         return false;
7052       if (!Char.getInt())
7053         return Success(Strlen, E);
7054       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7055         return false;
7056     }
7057   }
7058 
7059   case Builtin::BI__atomic_always_lock_free:
7060   case Builtin::BI__atomic_is_lock_free:
7061   case Builtin::BI__c11_atomic_is_lock_free: {
7062     APSInt SizeVal;
7063     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7064       return false;
7065 
7066     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7067     // of two less than the maximum inline atomic width, we know it is
7068     // lock-free.  If the size isn't a power of two, or greater than the
7069     // maximum alignment where we promote atomics, we know it is not lock-free
7070     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
7071     // the answer can only be determined at runtime; for example, 16-byte
7072     // atomics have lock-free implementations on some, but not all,
7073     // x86-64 processors.
7074 
7075     // Check power-of-two.
7076     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7077     if (Size.isPowerOfTwo()) {
7078       // Check against inlining width.
7079       unsigned InlineWidthBits =
7080           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7081       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7082         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7083             Size == CharUnits::One() ||
7084             E->getArg(1)->isNullPointerConstant(Info.Ctx,
7085                                                 Expr::NPC_NeverValueDependent))
7086           // OK, we will inline appropriately-aligned operations of this size,
7087           // and _Atomic(T) is appropriately-aligned.
7088           return Success(1, E);
7089 
7090         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7091           castAs<PointerType>()->getPointeeType();
7092         if (!PointeeType->isIncompleteType() &&
7093             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7094           // OK, we will inline operations on this object.
7095           return Success(1, E);
7096         }
7097       }
7098     }
7099 
7100     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7101         Success(0, E) : Error(E);
7102   }
7103   }
7104 }
7105 
7106 static bool HasSameBase(const LValue &A, const LValue &B) {
7107   if (!A.getLValueBase())
7108     return !B.getLValueBase();
7109   if (!B.getLValueBase())
7110     return false;
7111 
7112   if (A.getLValueBase().getOpaqueValue() !=
7113       B.getLValueBase().getOpaqueValue()) {
7114     const Decl *ADecl = GetLValueBaseDecl(A);
7115     if (!ADecl)
7116       return false;
7117     const Decl *BDecl = GetLValueBaseDecl(B);
7118     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7119       return false;
7120   }
7121 
7122   return IsGlobalLValue(A.getLValueBase()) ||
7123          A.getLValueCallIndex() == B.getLValueCallIndex();
7124 }
7125 
7126 /// \brief Determine whether this is a pointer past the end of the complete
7127 /// object referred to by the lvalue.
7128 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7129                                             const LValue &LV) {
7130   // A null pointer can be viewed as being "past the end" but we don't
7131   // choose to look at it that way here.
7132   if (!LV.getLValueBase())
7133     return false;
7134 
7135   // If the designator is valid and refers to a subobject, we're not pointing
7136   // past the end.
7137   if (!LV.getLValueDesignator().Invalid &&
7138       !LV.getLValueDesignator().isOnePastTheEnd())
7139     return false;
7140 
7141   // A pointer to an incomplete type might be past-the-end if the type's size is
7142   // zero.  We cannot tell because the type is incomplete.
7143   QualType Ty = getType(LV.getLValueBase());
7144   if (Ty->isIncompleteType())
7145     return true;
7146 
7147   // We're a past-the-end pointer if we point to the byte after the object,
7148   // no matter what our type or path is.
7149   auto Size = Ctx.getTypeSizeInChars(Ty);
7150   return LV.getLValueOffset() == Size;
7151 }
7152 
7153 namespace {
7154 
7155 /// \brief Data recursive integer evaluator of certain binary operators.
7156 ///
7157 /// We use a data recursive algorithm for binary operators so that we are able
7158 /// to handle extreme cases of chained binary operators without causing stack
7159 /// overflow.
7160 class DataRecursiveIntBinOpEvaluator {
7161   struct EvalResult {
7162     APValue Val;
7163     bool Failed;
7164 
7165     EvalResult() : Failed(false) { }
7166 
7167     void swap(EvalResult &RHS) {
7168       Val.swap(RHS.Val);
7169       Failed = RHS.Failed;
7170       RHS.Failed = false;
7171     }
7172   };
7173 
7174   struct Job {
7175     const Expr *E;
7176     EvalResult LHSResult; // meaningful only for binary operator expression.
7177     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7178 
7179     Job() = default;
7180     Job(Job &&J)
7181         : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
7182           SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
7183 
7184     void startSpeculativeEval(EvalInfo &Info) {
7185       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7186     }
7187 
7188   private:
7189     SpeculativeEvaluationRAII SpecEvalRAII;
7190   };
7191 
7192   SmallVector<Job, 16> Queue;
7193 
7194   IntExprEvaluator &IntEval;
7195   EvalInfo &Info;
7196   APValue &FinalResult;
7197 
7198 public:
7199   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7200     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7201 
7202   /// \brief True if \param E is a binary operator that we are going to handle
7203   /// data recursively.
7204   /// We handle binary operators that are comma, logical, or that have operands
7205   /// with integral or enumeration type.
7206   static bool shouldEnqueue(const BinaryOperator *E) {
7207     return E->getOpcode() == BO_Comma ||
7208            E->isLogicalOp() ||
7209            (E->isRValue() &&
7210             E->getType()->isIntegralOrEnumerationType() &&
7211             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7212             E->getRHS()->getType()->isIntegralOrEnumerationType());
7213   }
7214 
7215   bool Traverse(const BinaryOperator *E) {
7216     enqueue(E);
7217     EvalResult PrevResult;
7218     while (!Queue.empty())
7219       process(PrevResult);
7220 
7221     if (PrevResult.Failed) return false;
7222 
7223     FinalResult.swap(PrevResult.Val);
7224     return true;
7225   }
7226 
7227 private:
7228   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7229     return IntEval.Success(Value, E, Result);
7230   }
7231   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7232     return IntEval.Success(Value, E, Result);
7233   }
7234   bool Error(const Expr *E) {
7235     return IntEval.Error(E);
7236   }
7237   bool Error(const Expr *E, diag::kind D) {
7238     return IntEval.Error(E, D);
7239   }
7240 
7241   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7242     return Info.CCEDiag(E, D);
7243   }
7244 
7245   // \brief Returns true if visiting the RHS is necessary, false otherwise.
7246   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7247                          bool &SuppressRHSDiags);
7248 
7249   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7250                   const BinaryOperator *E, APValue &Result);
7251 
7252   void EvaluateExpr(const Expr *E, EvalResult &Result) {
7253     Result.Failed = !Evaluate(Result.Val, Info, E);
7254     if (Result.Failed)
7255       Result.Val = APValue();
7256   }
7257 
7258   void process(EvalResult &Result);
7259 
7260   void enqueue(const Expr *E) {
7261     E = E->IgnoreParens();
7262     Queue.resize(Queue.size()+1);
7263     Queue.back().E = E;
7264     Queue.back().Kind = Job::AnyExprKind;
7265   }
7266 };
7267 
7268 }
7269 
7270 bool DataRecursiveIntBinOpEvaluator::
7271        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7272                          bool &SuppressRHSDiags) {
7273   if (E->getOpcode() == BO_Comma) {
7274     // Ignore LHS but note if we could not evaluate it.
7275     if (LHSResult.Failed)
7276       return Info.noteSideEffect();
7277     return true;
7278   }
7279 
7280   if (E->isLogicalOp()) {
7281     bool LHSAsBool;
7282     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7283       // We were able to evaluate the LHS, see if we can get away with not
7284       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7285       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7286         Success(LHSAsBool, E, LHSResult.Val);
7287         return false; // Ignore RHS
7288       }
7289     } else {
7290       LHSResult.Failed = true;
7291 
7292       // Since we weren't able to evaluate the left hand side, it
7293       // might have had side effects.
7294       if (!Info.noteSideEffect())
7295         return false;
7296 
7297       // We can't evaluate the LHS; however, sometimes the result
7298       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7299       // Don't ignore RHS and suppress diagnostics from this arm.
7300       SuppressRHSDiags = true;
7301     }
7302 
7303     return true;
7304   }
7305 
7306   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7307          E->getRHS()->getType()->isIntegralOrEnumerationType());
7308 
7309   if (LHSResult.Failed && !Info.noteFailure())
7310     return false; // Ignore RHS;
7311 
7312   return true;
7313 }
7314 
7315 bool DataRecursiveIntBinOpEvaluator::
7316        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7317                   const BinaryOperator *E, APValue &Result) {
7318   if (E->getOpcode() == BO_Comma) {
7319     if (RHSResult.Failed)
7320       return false;
7321     Result = RHSResult.Val;
7322     return true;
7323   }
7324 
7325   if (E->isLogicalOp()) {
7326     bool lhsResult, rhsResult;
7327     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7328     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7329 
7330     if (LHSIsOK) {
7331       if (RHSIsOK) {
7332         if (E->getOpcode() == BO_LOr)
7333           return Success(lhsResult || rhsResult, E, Result);
7334         else
7335           return Success(lhsResult && rhsResult, E, Result);
7336       }
7337     } else {
7338       if (RHSIsOK) {
7339         // We can't evaluate the LHS; however, sometimes the result
7340         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7341         if (rhsResult == (E->getOpcode() == BO_LOr))
7342           return Success(rhsResult, E, Result);
7343       }
7344     }
7345 
7346     return false;
7347   }
7348 
7349   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7350          E->getRHS()->getType()->isIntegralOrEnumerationType());
7351 
7352   if (LHSResult.Failed || RHSResult.Failed)
7353     return false;
7354 
7355   const APValue &LHSVal = LHSResult.Val;
7356   const APValue &RHSVal = RHSResult.Val;
7357 
7358   // Handle cases like (unsigned long)&a + 4.
7359   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7360     Result = LHSVal;
7361     CharUnits AdditionalOffset =
7362         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7363     if (E->getOpcode() == BO_Add)
7364       Result.getLValueOffset() += AdditionalOffset;
7365     else
7366       Result.getLValueOffset() -= AdditionalOffset;
7367     return true;
7368   }
7369 
7370   // Handle cases like 4 + (unsigned long)&a
7371   if (E->getOpcode() == BO_Add &&
7372       RHSVal.isLValue() && LHSVal.isInt()) {
7373     Result = RHSVal;
7374     Result.getLValueOffset() +=
7375         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
7376     return true;
7377   }
7378 
7379   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7380     // Handle (intptr_t)&&A - (intptr_t)&&B.
7381     if (!LHSVal.getLValueOffset().isZero() ||
7382         !RHSVal.getLValueOffset().isZero())
7383       return false;
7384     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7385     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7386     if (!LHSExpr || !RHSExpr)
7387       return false;
7388     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7389     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7390     if (!LHSAddrExpr || !RHSAddrExpr)
7391       return false;
7392     // Make sure both labels come from the same function.
7393     if (LHSAddrExpr->getLabel()->getDeclContext() !=
7394         RHSAddrExpr->getLabel()->getDeclContext())
7395       return false;
7396     Result = APValue(LHSAddrExpr, RHSAddrExpr);
7397     return true;
7398   }
7399 
7400   // All the remaining cases expect both operands to be an integer
7401   if (!LHSVal.isInt() || !RHSVal.isInt())
7402     return Error(E);
7403 
7404   // Set up the width and signedness manually, in case it can't be deduced
7405   // from the operation we're performing.
7406   // FIXME: Don't do this in the cases where we can deduce it.
7407   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7408                E->getType()->isUnsignedIntegerOrEnumerationType());
7409   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7410                          RHSVal.getInt(), Value))
7411     return false;
7412   return Success(Value, E, Result);
7413 }
7414 
7415 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
7416   Job &job = Queue.back();
7417 
7418   switch (job.Kind) {
7419     case Job::AnyExprKind: {
7420       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7421         if (shouldEnqueue(Bop)) {
7422           job.Kind = Job::BinOpKind;
7423           enqueue(Bop->getLHS());
7424           return;
7425         }
7426       }
7427 
7428       EvaluateExpr(job.E, Result);
7429       Queue.pop_back();
7430       return;
7431     }
7432 
7433     case Job::BinOpKind: {
7434       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7435       bool SuppressRHSDiags = false;
7436       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
7437         Queue.pop_back();
7438         return;
7439       }
7440       if (SuppressRHSDiags)
7441         job.startSpeculativeEval(Info);
7442       job.LHSResult.swap(Result);
7443       job.Kind = Job::BinOpVisitedLHSKind;
7444       enqueue(Bop->getRHS());
7445       return;
7446     }
7447 
7448     case Job::BinOpVisitedLHSKind: {
7449       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7450       EvalResult RHS;
7451       RHS.swap(Result);
7452       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
7453       Queue.pop_back();
7454       return;
7455     }
7456   }
7457 
7458   llvm_unreachable("Invalid Job::Kind!");
7459 }
7460 
7461 namespace {
7462 /// Used when we determine that we should fail, but can keep evaluating prior to
7463 /// noting that we had a failure.
7464 class DelayedNoteFailureRAII {
7465   EvalInfo &Info;
7466   bool NoteFailure;
7467 
7468 public:
7469   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7470       : Info(Info), NoteFailure(NoteFailure) {}
7471   ~DelayedNoteFailureRAII() {
7472     if (NoteFailure) {
7473       bool ContinueAfterFailure = Info.noteFailure();
7474       (void)ContinueAfterFailure;
7475       assert(ContinueAfterFailure &&
7476              "Shouldn't have kept evaluating on failure.");
7477     }
7478   }
7479 };
7480 }
7481 
7482 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7483   // We don't call noteFailure immediately because the assignment happens after
7484   // we evaluate LHS and RHS.
7485   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
7486     return Error(E);
7487 
7488   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
7489   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7490     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
7491 
7492   QualType LHSTy = E->getLHS()->getType();
7493   QualType RHSTy = E->getRHS()->getType();
7494 
7495   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
7496     ComplexValue LHS, RHS;
7497     bool LHSOK;
7498     if (E->isAssignmentOp()) {
7499       LValue LV;
7500       EvaluateLValue(E->getLHS(), LV, Info);
7501       LHSOK = false;
7502     } else if (LHSTy->isRealFloatingType()) {
7503       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7504       if (LHSOK) {
7505         LHS.makeComplexFloat();
7506         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7507       }
7508     } else {
7509       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7510     }
7511     if (!LHSOK && !Info.noteFailure())
7512       return false;
7513 
7514     if (E->getRHS()->getType()->isRealFloatingType()) {
7515       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7516         return false;
7517       RHS.makeComplexFloat();
7518       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7519     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7520       return false;
7521 
7522     if (LHS.isComplexFloat()) {
7523       APFloat::cmpResult CR_r =
7524         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
7525       APFloat::cmpResult CR_i =
7526         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7527 
7528       if (E->getOpcode() == BO_EQ)
7529         return Success((CR_r == APFloat::cmpEqual &&
7530                         CR_i == APFloat::cmpEqual), E);
7531       else {
7532         assert(E->getOpcode() == BO_NE &&
7533                "Invalid complex comparison.");
7534         return Success(((CR_r == APFloat::cmpGreaterThan ||
7535                          CR_r == APFloat::cmpLessThan ||
7536                          CR_r == APFloat::cmpUnordered) ||
7537                         (CR_i == APFloat::cmpGreaterThan ||
7538                          CR_i == APFloat::cmpLessThan ||
7539                          CR_i == APFloat::cmpUnordered)), E);
7540       }
7541     } else {
7542       if (E->getOpcode() == BO_EQ)
7543         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7544                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7545       else {
7546         assert(E->getOpcode() == BO_NE &&
7547                "Invalid compex comparison.");
7548         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7549                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7550       }
7551     }
7552   }
7553 
7554   if (LHSTy->isRealFloatingType() &&
7555       RHSTy->isRealFloatingType()) {
7556     APFloat RHS(0.0), LHS(0.0);
7557 
7558     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7559     if (!LHSOK && !Info.noteFailure())
7560       return false;
7561 
7562     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
7563       return false;
7564 
7565     APFloat::cmpResult CR = LHS.compare(RHS);
7566 
7567     switch (E->getOpcode()) {
7568     default:
7569       llvm_unreachable("Invalid binary operator!");
7570     case BO_LT:
7571       return Success(CR == APFloat::cmpLessThan, E);
7572     case BO_GT:
7573       return Success(CR == APFloat::cmpGreaterThan, E);
7574     case BO_LE:
7575       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
7576     case BO_GE:
7577       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
7578                      E);
7579     case BO_EQ:
7580       return Success(CR == APFloat::cmpEqual, E);
7581     case BO_NE:
7582       return Success(CR == APFloat::cmpGreaterThan
7583                      || CR == APFloat::cmpLessThan
7584                      || CR == APFloat::cmpUnordered, E);
7585     }
7586   }
7587 
7588   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
7589     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
7590       LValue LHSValue, RHSValue;
7591 
7592       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7593       if (!LHSOK && !Info.noteFailure())
7594         return false;
7595 
7596       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7597         return false;
7598 
7599       // Reject differing bases from the normal codepath; we special-case
7600       // comparisons to null.
7601       if (!HasSameBase(LHSValue, RHSValue)) {
7602         if (E->getOpcode() == BO_Sub) {
7603           // Handle &&A - &&B.
7604           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7605             return Error(E);
7606           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
7607           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
7608           if (!LHSExpr || !RHSExpr)
7609             return Error(E);
7610           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7611           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7612           if (!LHSAddrExpr || !RHSAddrExpr)
7613             return Error(E);
7614           // Make sure both labels come from the same function.
7615           if (LHSAddrExpr->getLabel()->getDeclContext() !=
7616               RHSAddrExpr->getLabel()->getDeclContext())
7617             return Error(E);
7618           return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
7619         }
7620         // Inequalities and subtractions between unrelated pointers have
7621         // unspecified or undefined behavior.
7622         if (!E->isEqualityOp())
7623           return Error(E);
7624         // A constant address may compare equal to the address of a symbol.
7625         // The one exception is that address of an object cannot compare equal
7626         // to a null pointer constant.
7627         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7628             (!RHSValue.Base && !RHSValue.Offset.isZero()))
7629           return Error(E);
7630         // It's implementation-defined whether distinct literals will have
7631         // distinct addresses. In clang, the result of such a comparison is
7632         // unspecified, so it is not a constant expression. However, we do know
7633         // that the address of a literal will be non-null.
7634         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7635             LHSValue.Base && RHSValue.Base)
7636           return Error(E);
7637         // We can't tell whether weak symbols will end up pointing to the same
7638         // object.
7639         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
7640           return Error(E);
7641         // We can't compare the address of the start of one object with the
7642         // past-the-end address of another object, per C++ DR1652.
7643         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7644              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7645             (RHSValue.Base && RHSValue.Offset.isZero() &&
7646              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7647           return Error(E);
7648         // We can't tell whether an object is at the same address as another
7649         // zero sized object.
7650         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7651             (LHSValue.Base && isZeroSized(RHSValue)))
7652           return Error(E);
7653         // Pointers with different bases cannot represent the same object.
7654         // (Note that clang defaults to -fmerge-all-constants, which can
7655         // lead to inconsistent results for comparisons involving the address
7656         // of a constant; this generally doesn't matter in practice.)
7657         return Success(E->getOpcode() == BO_NE, E);
7658       }
7659 
7660       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7661       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7662 
7663       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7664       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7665 
7666       if (E->getOpcode() == BO_Sub) {
7667         // C++11 [expr.add]p6:
7668         //   Unless both pointers point to elements of the same array object, or
7669         //   one past the last element of the array object, the behavior is
7670         //   undefined.
7671         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7672             !AreElementsOfSameArray(getType(LHSValue.Base),
7673                                     LHSDesignator, RHSDesignator))
7674           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7675 
7676         QualType Type = E->getLHS()->getType();
7677         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7678 
7679         CharUnits ElementSize;
7680         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7681           return false;
7682 
7683         // As an extension, a type may have zero size (empty struct or union in
7684         // C, array of zero length). Pointer subtraction in such cases has
7685         // undefined behavior, so is not constant.
7686         if (ElementSize.isZero()) {
7687           Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7688             << ElementType;
7689           return false;
7690         }
7691 
7692         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7693         // and produce incorrect results when it overflows. Such behavior
7694         // appears to be non-conforming, but is common, so perhaps we should
7695         // assume the standard intended for such cases to be undefined behavior
7696         // and check for them.
7697 
7698         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7699         // overflow in the final conversion to ptrdiff_t.
7700         APSInt LHS(
7701           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7702         APSInt RHS(
7703           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7704         APSInt ElemSize(
7705           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7706         APSInt TrueResult = (LHS - RHS) / ElemSize;
7707         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7708 
7709         if (Result.extend(65) != TrueResult &&
7710             !HandleOverflow(Info, E, TrueResult, E->getType()))
7711           return false;
7712         return Success(Result, E);
7713       }
7714 
7715       // C++11 [expr.rel]p3:
7716       //   Pointers to void (after pointer conversions) can be compared, with a
7717       //   result defined as follows: If both pointers represent the same
7718       //   address or are both the null pointer value, the result is true if the
7719       //   operator is <= or >= and false otherwise; otherwise the result is
7720       //   unspecified.
7721       // We interpret this as applying to pointers to *cv* void.
7722       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7723           E->isRelationalOp())
7724         CCEDiag(E, diag::note_constexpr_void_comparison);
7725 
7726       // C++11 [expr.rel]p2:
7727       // - If two pointers point to non-static data members of the same object,
7728       //   or to subobjects or array elements fo such members, recursively, the
7729       //   pointer to the later declared member compares greater provided the
7730       //   two members have the same access control and provided their class is
7731       //   not a union.
7732       //   [...]
7733       // - Otherwise pointer comparisons are unspecified.
7734       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7735           E->isRelationalOp()) {
7736         bool WasArrayIndex;
7737         unsigned Mismatch =
7738           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7739                                  RHSDesignator, WasArrayIndex);
7740         // At the point where the designators diverge, the comparison has a
7741         // specified value if:
7742         //  - we are comparing array indices
7743         //  - we are comparing fields of a union, or fields with the same access
7744         // Otherwise, the result is unspecified and thus the comparison is not a
7745         // constant expression.
7746         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7747             Mismatch < RHSDesignator.Entries.size()) {
7748           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7749           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7750           if (!LF && !RF)
7751             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7752           else if (!LF)
7753             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7754               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7755               << RF->getParent() << RF;
7756           else if (!RF)
7757             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7758               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7759               << LF->getParent() << LF;
7760           else if (!LF->getParent()->isUnion() &&
7761                    LF->getAccess() != RF->getAccess())
7762             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7763               << LF << LF->getAccess() << RF << RF->getAccess()
7764               << LF->getParent();
7765         }
7766       }
7767 
7768       // The comparison here must be unsigned, and performed with the same
7769       // width as the pointer.
7770       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7771       uint64_t CompareLHS = LHSOffset.getQuantity();
7772       uint64_t CompareRHS = RHSOffset.getQuantity();
7773       assert(PtrSize <= 64 && "Unexpected pointer width");
7774       uint64_t Mask = ~0ULL >> (64 - PtrSize);
7775       CompareLHS &= Mask;
7776       CompareRHS &= Mask;
7777 
7778       // If there is a base and this is a relational operator, we can only
7779       // compare pointers within the object in question; otherwise, the result
7780       // depends on where the object is located in memory.
7781       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7782         QualType BaseTy = getType(LHSValue.Base);
7783         if (BaseTy->isIncompleteType())
7784           return Error(E);
7785         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7786         uint64_t OffsetLimit = Size.getQuantity();
7787         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7788           return Error(E);
7789       }
7790 
7791       switch (E->getOpcode()) {
7792       default: llvm_unreachable("missing comparison operator");
7793       case BO_LT: return Success(CompareLHS < CompareRHS, E);
7794       case BO_GT: return Success(CompareLHS > CompareRHS, E);
7795       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7796       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7797       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7798       case BO_NE: return Success(CompareLHS != CompareRHS, E);
7799       }
7800     }
7801   }
7802 
7803   if (LHSTy->isMemberPointerType()) {
7804     assert(E->isEqualityOp() && "unexpected member pointer operation");
7805     assert(RHSTy->isMemberPointerType() && "invalid comparison");
7806 
7807     MemberPtr LHSValue, RHSValue;
7808 
7809     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7810     if (!LHSOK && !Info.noteFailure())
7811       return false;
7812 
7813     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7814       return false;
7815 
7816     // C++11 [expr.eq]p2:
7817     //   If both operands are null, they compare equal. Otherwise if only one is
7818     //   null, they compare unequal.
7819     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7820       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7821       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7822     }
7823 
7824     //   Otherwise if either is a pointer to a virtual member function, the
7825     //   result is unspecified.
7826     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7827       if (MD->isVirtual())
7828         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7829     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7830       if (MD->isVirtual())
7831         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7832 
7833     //   Otherwise they compare equal if and only if they would refer to the
7834     //   same member of the same most derived object or the same subobject if
7835     //   they were dereferenced with a hypothetical object of the associated
7836     //   class type.
7837     bool Equal = LHSValue == RHSValue;
7838     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7839   }
7840 
7841   if (LHSTy->isNullPtrType()) {
7842     assert(E->isComparisonOp() && "unexpected nullptr operation");
7843     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7844     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7845     // are compared, the result is true of the operator is <=, >= or ==, and
7846     // false otherwise.
7847     BinaryOperator::Opcode Opcode = E->getOpcode();
7848     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7849   }
7850 
7851   assert((!LHSTy->isIntegralOrEnumerationType() ||
7852           !RHSTy->isIntegralOrEnumerationType()) &&
7853          "DataRecursiveIntBinOpEvaluator should have handled integral types");
7854   // We can't continue from here for non-integral types.
7855   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7856 }
7857 
7858 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7859 /// a result as the expression's type.
7860 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7861                                     const UnaryExprOrTypeTraitExpr *E) {
7862   switch(E->getKind()) {
7863   case UETT_AlignOf: {
7864     if (E->isArgumentType())
7865       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7866     else
7867       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7868   }
7869 
7870   case UETT_VecStep: {
7871     QualType Ty = E->getTypeOfArgument();
7872 
7873     if (Ty->isVectorType()) {
7874       unsigned n = Ty->castAs<VectorType>()->getNumElements();
7875 
7876       // The vec_step built-in functions that take a 3-component
7877       // vector return 4. (OpenCL 1.1 spec 6.11.12)
7878       if (n == 3)
7879         n = 4;
7880 
7881       return Success(n, E);
7882     } else
7883       return Success(1, E);
7884   }
7885 
7886   case UETT_SizeOf: {
7887     QualType SrcTy = E->getTypeOfArgument();
7888     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7889     //   the result is the size of the referenced type."
7890     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7891       SrcTy = Ref->getPointeeType();
7892 
7893     CharUnits Sizeof;
7894     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7895       return false;
7896     return Success(Sizeof, E);
7897   }
7898   case UETT_OpenMPRequiredSimdAlign:
7899     assert(E->isArgumentType());
7900     return Success(
7901         Info.Ctx.toCharUnitsFromBits(
7902                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7903             .getQuantity(),
7904         E);
7905   }
7906 
7907   llvm_unreachable("unknown expr/type trait");
7908 }
7909 
7910 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7911   CharUnits Result;
7912   unsigned n = OOE->getNumComponents();
7913   if (n == 0)
7914     return Error(OOE);
7915   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7916   for (unsigned i = 0; i != n; ++i) {
7917     OffsetOfNode ON = OOE->getComponent(i);
7918     switch (ON.getKind()) {
7919     case OffsetOfNode::Array: {
7920       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7921       APSInt IdxResult;
7922       if (!EvaluateInteger(Idx, IdxResult, Info))
7923         return false;
7924       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7925       if (!AT)
7926         return Error(OOE);
7927       CurrentType = AT->getElementType();
7928       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7929       Result += IdxResult.getSExtValue() * ElementSize;
7930       break;
7931     }
7932 
7933     case OffsetOfNode::Field: {
7934       FieldDecl *MemberDecl = ON.getField();
7935       const RecordType *RT = CurrentType->getAs<RecordType>();
7936       if (!RT)
7937         return Error(OOE);
7938       RecordDecl *RD = RT->getDecl();
7939       if (RD->isInvalidDecl()) return false;
7940       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7941       unsigned i = MemberDecl->getFieldIndex();
7942       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7943       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7944       CurrentType = MemberDecl->getType().getNonReferenceType();
7945       break;
7946     }
7947 
7948     case OffsetOfNode::Identifier:
7949       llvm_unreachable("dependent __builtin_offsetof");
7950 
7951     case OffsetOfNode::Base: {
7952       CXXBaseSpecifier *BaseSpec = ON.getBase();
7953       if (BaseSpec->isVirtual())
7954         return Error(OOE);
7955 
7956       // Find the layout of the class whose base we are looking into.
7957       const RecordType *RT = CurrentType->getAs<RecordType>();
7958       if (!RT)
7959         return Error(OOE);
7960       RecordDecl *RD = RT->getDecl();
7961       if (RD->isInvalidDecl()) return false;
7962       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7963 
7964       // Find the base class itself.
7965       CurrentType = BaseSpec->getType();
7966       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7967       if (!BaseRT)
7968         return Error(OOE);
7969 
7970       // Add the offset to the base.
7971       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7972       break;
7973     }
7974     }
7975   }
7976   return Success(Result, OOE);
7977 }
7978 
7979 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7980   switch (E->getOpcode()) {
7981   default:
7982     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7983     // See C99 6.6p3.
7984     return Error(E);
7985   case UO_Extension:
7986     // FIXME: Should extension allow i-c-e extension expressions in its scope?
7987     // If so, we could clear the diagnostic ID.
7988     return Visit(E->getSubExpr());
7989   case UO_Plus:
7990     // The result is just the value.
7991     return Visit(E->getSubExpr());
7992   case UO_Minus: {
7993     if (!Visit(E->getSubExpr()))
7994       return false;
7995     if (!Result.isInt()) return Error(E);
7996     const APSInt &Value = Result.getInt();
7997     if (Value.isSigned() && Value.isMinSignedValue() &&
7998         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7999                         E->getType()))
8000       return false;
8001     return Success(-Value, E);
8002   }
8003   case UO_Not: {
8004     if (!Visit(E->getSubExpr()))
8005       return false;
8006     if (!Result.isInt()) return Error(E);
8007     return Success(~Result.getInt(), E);
8008   }
8009   case UO_LNot: {
8010     bool bres;
8011     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8012       return false;
8013     return Success(!bres, E);
8014   }
8015   }
8016 }
8017 
8018 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8019 /// result type is integer.
8020 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8021   const Expr *SubExpr = E->getSubExpr();
8022   QualType DestType = E->getType();
8023   QualType SrcType = SubExpr->getType();
8024 
8025   switch (E->getCastKind()) {
8026   case CK_BaseToDerived:
8027   case CK_DerivedToBase:
8028   case CK_UncheckedDerivedToBase:
8029   case CK_Dynamic:
8030   case CK_ToUnion:
8031   case CK_ArrayToPointerDecay:
8032   case CK_FunctionToPointerDecay:
8033   case CK_NullToPointer:
8034   case CK_NullToMemberPointer:
8035   case CK_BaseToDerivedMemberPointer:
8036   case CK_DerivedToBaseMemberPointer:
8037   case CK_ReinterpretMemberPointer:
8038   case CK_ConstructorConversion:
8039   case CK_IntegralToPointer:
8040   case CK_ToVoid:
8041   case CK_VectorSplat:
8042   case CK_IntegralToFloating:
8043   case CK_FloatingCast:
8044   case CK_CPointerToObjCPointerCast:
8045   case CK_BlockPointerToObjCPointerCast:
8046   case CK_AnyPointerToBlockPointerCast:
8047   case CK_ObjCObjectLValueCast:
8048   case CK_FloatingRealToComplex:
8049   case CK_FloatingComplexToReal:
8050   case CK_FloatingComplexCast:
8051   case CK_FloatingComplexToIntegralComplex:
8052   case CK_IntegralRealToComplex:
8053   case CK_IntegralComplexCast:
8054   case CK_IntegralComplexToFloatingComplex:
8055   case CK_BuiltinFnToFnPtr:
8056   case CK_ZeroToOCLEvent:
8057   case CK_NonAtomicToAtomic:
8058   case CK_AddressSpaceConversion:
8059     llvm_unreachable("invalid cast kind for integral value");
8060 
8061   case CK_BitCast:
8062   case CK_Dependent:
8063   case CK_LValueBitCast:
8064   case CK_ARCProduceObject:
8065   case CK_ARCConsumeObject:
8066   case CK_ARCReclaimReturnedObject:
8067   case CK_ARCExtendBlockObject:
8068   case CK_CopyAndAutoreleaseBlockObject:
8069     return Error(E);
8070 
8071   case CK_UserDefinedConversion:
8072   case CK_LValueToRValue:
8073   case CK_AtomicToNonAtomic:
8074   case CK_NoOp:
8075     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8076 
8077   case CK_MemberPointerToBoolean:
8078   case CK_PointerToBoolean:
8079   case CK_IntegralToBoolean:
8080   case CK_FloatingToBoolean:
8081   case CK_BooleanToSignedIntegral:
8082   case CK_FloatingComplexToBoolean:
8083   case CK_IntegralComplexToBoolean: {
8084     bool BoolResult;
8085     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8086       return false;
8087     uint64_t IntResult = BoolResult;
8088     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8089       IntResult = (uint64_t)-1;
8090     return Success(IntResult, E);
8091   }
8092 
8093   case CK_IntegralCast: {
8094     if (!Visit(SubExpr))
8095       return false;
8096 
8097     if (!Result.isInt()) {
8098       // Allow casts of address-of-label differences if they are no-ops
8099       // or narrowing.  (The narrowing case isn't actually guaranteed to
8100       // be constant-evaluatable except in some narrow cases which are hard
8101       // to detect here.  We let it through on the assumption the user knows
8102       // what they are doing.)
8103       if (Result.isAddrLabelDiff())
8104         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8105       // Only allow casts of lvalues if they are lossless.
8106       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8107     }
8108 
8109     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8110                                       Result.getInt()), E);
8111   }
8112 
8113   case CK_PointerToIntegral: {
8114     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8115 
8116     LValue LV;
8117     if (!EvaluatePointer(SubExpr, LV, Info))
8118       return false;
8119 
8120     if (LV.getLValueBase()) {
8121       // Only allow based lvalue casts if they are lossless.
8122       // FIXME: Allow a larger integer size than the pointer size, and allow
8123       // narrowing back down to pointer width in subsequent integral casts.
8124       // FIXME: Check integer type's active bits, not its type size.
8125       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8126         return Error(E);
8127 
8128       LV.Designator.setInvalid();
8129       LV.moveInto(Result);
8130       return true;
8131     }
8132 
8133     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8134                                          SrcType);
8135     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8136   }
8137 
8138   case CK_IntegralComplexToReal: {
8139     ComplexValue C;
8140     if (!EvaluateComplex(SubExpr, C, Info))
8141       return false;
8142     return Success(C.getComplexIntReal(), E);
8143   }
8144 
8145   case CK_FloatingToIntegral: {
8146     APFloat F(0.0);
8147     if (!EvaluateFloat(SubExpr, F, Info))
8148       return false;
8149 
8150     APSInt Value;
8151     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8152       return false;
8153     return Success(Value, E);
8154   }
8155   }
8156 
8157   llvm_unreachable("unknown cast resulting in integral value");
8158 }
8159 
8160 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8161   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8162     ComplexValue LV;
8163     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8164       return false;
8165     if (!LV.isComplexInt())
8166       return Error(E);
8167     return Success(LV.getComplexIntReal(), E);
8168   }
8169 
8170   return Visit(E->getSubExpr());
8171 }
8172 
8173 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8174   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8175     ComplexValue LV;
8176     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8177       return false;
8178     if (!LV.isComplexInt())
8179       return Error(E);
8180     return Success(LV.getComplexIntImag(), E);
8181   }
8182 
8183   VisitIgnoredValue(E->getSubExpr());
8184   return Success(0, E);
8185 }
8186 
8187 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8188   return Success(E->getPackLength(), E);
8189 }
8190 
8191 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8192   return Success(E->getValue(), E);
8193 }
8194 
8195 //===----------------------------------------------------------------------===//
8196 // Float Evaluation
8197 //===----------------------------------------------------------------------===//
8198 
8199 namespace {
8200 class FloatExprEvaluator
8201   : public ExprEvaluatorBase<FloatExprEvaluator> {
8202   APFloat &Result;
8203 public:
8204   FloatExprEvaluator(EvalInfo &info, APFloat &result)
8205     : ExprEvaluatorBaseTy(info), Result(result) {}
8206 
8207   bool Success(const APValue &V, const Expr *e) {
8208     Result = V.getFloat();
8209     return true;
8210   }
8211 
8212   bool ZeroInitialization(const Expr *E) {
8213     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8214     return true;
8215   }
8216 
8217   bool VisitCallExpr(const CallExpr *E);
8218 
8219   bool VisitUnaryOperator(const UnaryOperator *E);
8220   bool VisitBinaryOperator(const BinaryOperator *E);
8221   bool VisitFloatingLiteral(const FloatingLiteral *E);
8222   bool VisitCastExpr(const CastExpr *E);
8223 
8224   bool VisitUnaryReal(const UnaryOperator *E);
8225   bool VisitUnaryImag(const UnaryOperator *E);
8226 
8227   // FIXME: Missing: array subscript of vector, member of vector
8228 };
8229 } // end anonymous namespace
8230 
8231 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8232   assert(E->isRValue() && E->getType()->isRealFloatingType());
8233   return FloatExprEvaluator(Info, Result).Visit(E);
8234 }
8235 
8236 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8237                                   QualType ResultTy,
8238                                   const Expr *Arg,
8239                                   bool SNaN,
8240                                   llvm::APFloat &Result) {
8241   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8242   if (!S) return false;
8243 
8244   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8245 
8246   llvm::APInt fill;
8247 
8248   // Treat empty strings as if they were zero.
8249   if (S->getString().empty())
8250     fill = llvm::APInt(32, 0);
8251   else if (S->getString().getAsInteger(0, fill))
8252     return false;
8253 
8254   if (Context.getTargetInfo().isNan2008()) {
8255     if (SNaN)
8256       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8257     else
8258       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8259   } else {
8260     // Prior to IEEE 754-2008, architectures were allowed to choose whether
8261     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8262     // a different encoding to what became a standard in 2008, and for pre-
8263     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8264     // sNaN. This is now known as "legacy NaN" encoding.
8265     if (SNaN)
8266       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8267     else
8268       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8269   }
8270 
8271   return true;
8272 }
8273 
8274 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8275   switch (E->getBuiltinCallee()) {
8276   default:
8277     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8278 
8279   case Builtin::BI__builtin_huge_val:
8280   case Builtin::BI__builtin_huge_valf:
8281   case Builtin::BI__builtin_huge_vall:
8282   case Builtin::BI__builtin_inf:
8283   case Builtin::BI__builtin_inff:
8284   case Builtin::BI__builtin_infl: {
8285     const llvm::fltSemantics &Sem =
8286       Info.Ctx.getFloatTypeSemantics(E->getType());
8287     Result = llvm::APFloat::getInf(Sem);
8288     return true;
8289   }
8290 
8291   case Builtin::BI__builtin_nans:
8292   case Builtin::BI__builtin_nansf:
8293   case Builtin::BI__builtin_nansl:
8294     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8295                                true, Result))
8296       return Error(E);
8297     return true;
8298 
8299   case Builtin::BI__builtin_nan:
8300   case Builtin::BI__builtin_nanf:
8301   case Builtin::BI__builtin_nanl:
8302     // If this is __builtin_nan() turn this into a nan, otherwise we
8303     // can't constant fold it.
8304     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8305                                false, Result))
8306       return Error(E);
8307     return true;
8308 
8309   case Builtin::BI__builtin_fabs:
8310   case Builtin::BI__builtin_fabsf:
8311   case Builtin::BI__builtin_fabsl:
8312     if (!EvaluateFloat(E->getArg(0), Result, Info))
8313       return false;
8314 
8315     if (Result.isNegative())
8316       Result.changeSign();
8317     return true;
8318 
8319   // FIXME: Builtin::BI__builtin_powi
8320   // FIXME: Builtin::BI__builtin_powif
8321   // FIXME: Builtin::BI__builtin_powil
8322 
8323   case Builtin::BI__builtin_copysign:
8324   case Builtin::BI__builtin_copysignf:
8325   case Builtin::BI__builtin_copysignl: {
8326     APFloat RHS(0.);
8327     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8328         !EvaluateFloat(E->getArg(1), RHS, Info))
8329       return false;
8330     Result.copySign(RHS);
8331     return true;
8332   }
8333   }
8334 }
8335 
8336 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8337   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8338     ComplexValue CV;
8339     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8340       return false;
8341     Result = CV.FloatReal;
8342     return true;
8343   }
8344 
8345   return Visit(E->getSubExpr());
8346 }
8347 
8348 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8349   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8350     ComplexValue CV;
8351     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8352       return false;
8353     Result = CV.FloatImag;
8354     return true;
8355   }
8356 
8357   VisitIgnoredValue(E->getSubExpr());
8358   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8359   Result = llvm::APFloat::getZero(Sem);
8360   return true;
8361 }
8362 
8363 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8364   switch (E->getOpcode()) {
8365   default: return Error(E);
8366   case UO_Plus:
8367     return EvaluateFloat(E->getSubExpr(), Result, Info);
8368   case UO_Minus:
8369     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8370       return false;
8371     Result.changeSign();
8372     return true;
8373   }
8374 }
8375 
8376 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8377   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8378     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8379 
8380   APFloat RHS(0.0);
8381   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8382   if (!LHSOK && !Info.noteFailure())
8383     return false;
8384   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8385          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
8386 }
8387 
8388 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8389   Result = E->getValue();
8390   return true;
8391 }
8392 
8393 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8394   const Expr* SubExpr = E->getSubExpr();
8395 
8396   switch (E->getCastKind()) {
8397   default:
8398     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8399 
8400   case CK_IntegralToFloating: {
8401     APSInt IntResult;
8402     return EvaluateInteger(SubExpr, IntResult, Info) &&
8403            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8404                                 E->getType(), Result);
8405   }
8406 
8407   case CK_FloatingCast: {
8408     if (!Visit(SubExpr))
8409       return false;
8410     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8411                                   Result);
8412   }
8413 
8414   case CK_FloatingComplexToReal: {
8415     ComplexValue V;
8416     if (!EvaluateComplex(SubExpr, V, Info))
8417       return false;
8418     Result = V.getComplexFloatReal();
8419     return true;
8420   }
8421   }
8422 }
8423 
8424 //===----------------------------------------------------------------------===//
8425 // Complex Evaluation (for float and integer)
8426 //===----------------------------------------------------------------------===//
8427 
8428 namespace {
8429 class ComplexExprEvaluator
8430   : public ExprEvaluatorBase<ComplexExprEvaluator> {
8431   ComplexValue &Result;
8432 
8433 public:
8434   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
8435     : ExprEvaluatorBaseTy(info), Result(Result) {}
8436 
8437   bool Success(const APValue &V, const Expr *e) {
8438     Result.setFrom(V);
8439     return true;
8440   }
8441 
8442   bool ZeroInitialization(const Expr *E);
8443 
8444   //===--------------------------------------------------------------------===//
8445   //                            Visitor Methods
8446   //===--------------------------------------------------------------------===//
8447 
8448   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
8449   bool VisitCastExpr(const CastExpr *E);
8450   bool VisitBinaryOperator(const BinaryOperator *E);
8451   bool VisitUnaryOperator(const UnaryOperator *E);
8452   bool VisitInitListExpr(const InitListExpr *E);
8453 };
8454 } // end anonymous namespace
8455 
8456 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8457                             EvalInfo &Info) {
8458   assert(E->isRValue() && E->getType()->isAnyComplexType());
8459   return ComplexExprEvaluator(Info, Result).Visit(E);
8460 }
8461 
8462 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
8463   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
8464   if (ElemTy->isRealFloatingType()) {
8465     Result.makeComplexFloat();
8466     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8467     Result.FloatReal = Zero;
8468     Result.FloatImag = Zero;
8469   } else {
8470     Result.makeComplexInt();
8471     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8472     Result.IntReal = Zero;
8473     Result.IntImag = Zero;
8474   }
8475   return true;
8476 }
8477 
8478 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8479   const Expr* SubExpr = E->getSubExpr();
8480 
8481   if (SubExpr->getType()->isRealFloatingType()) {
8482     Result.makeComplexFloat();
8483     APFloat &Imag = Result.FloatImag;
8484     if (!EvaluateFloat(SubExpr, Imag, Info))
8485       return false;
8486 
8487     Result.FloatReal = APFloat(Imag.getSemantics());
8488     return true;
8489   } else {
8490     assert(SubExpr->getType()->isIntegerType() &&
8491            "Unexpected imaginary literal.");
8492 
8493     Result.makeComplexInt();
8494     APSInt &Imag = Result.IntImag;
8495     if (!EvaluateInteger(SubExpr, Imag, Info))
8496       return false;
8497 
8498     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8499     return true;
8500   }
8501 }
8502 
8503 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
8504 
8505   switch (E->getCastKind()) {
8506   case CK_BitCast:
8507   case CK_BaseToDerived:
8508   case CK_DerivedToBase:
8509   case CK_UncheckedDerivedToBase:
8510   case CK_Dynamic:
8511   case CK_ToUnion:
8512   case CK_ArrayToPointerDecay:
8513   case CK_FunctionToPointerDecay:
8514   case CK_NullToPointer:
8515   case CK_NullToMemberPointer:
8516   case CK_BaseToDerivedMemberPointer:
8517   case CK_DerivedToBaseMemberPointer:
8518   case CK_MemberPointerToBoolean:
8519   case CK_ReinterpretMemberPointer:
8520   case CK_ConstructorConversion:
8521   case CK_IntegralToPointer:
8522   case CK_PointerToIntegral:
8523   case CK_PointerToBoolean:
8524   case CK_ToVoid:
8525   case CK_VectorSplat:
8526   case CK_IntegralCast:
8527   case CK_BooleanToSignedIntegral:
8528   case CK_IntegralToBoolean:
8529   case CK_IntegralToFloating:
8530   case CK_FloatingToIntegral:
8531   case CK_FloatingToBoolean:
8532   case CK_FloatingCast:
8533   case CK_CPointerToObjCPointerCast:
8534   case CK_BlockPointerToObjCPointerCast:
8535   case CK_AnyPointerToBlockPointerCast:
8536   case CK_ObjCObjectLValueCast:
8537   case CK_FloatingComplexToReal:
8538   case CK_FloatingComplexToBoolean:
8539   case CK_IntegralComplexToReal:
8540   case CK_IntegralComplexToBoolean:
8541   case CK_ARCProduceObject:
8542   case CK_ARCConsumeObject:
8543   case CK_ARCReclaimReturnedObject:
8544   case CK_ARCExtendBlockObject:
8545   case CK_CopyAndAutoreleaseBlockObject:
8546   case CK_BuiltinFnToFnPtr:
8547   case CK_ZeroToOCLEvent:
8548   case CK_NonAtomicToAtomic:
8549   case CK_AddressSpaceConversion:
8550     llvm_unreachable("invalid cast kind for complex value");
8551 
8552   case CK_LValueToRValue:
8553   case CK_AtomicToNonAtomic:
8554   case CK_NoOp:
8555     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8556 
8557   case CK_Dependent:
8558   case CK_LValueBitCast:
8559   case CK_UserDefinedConversion:
8560     return Error(E);
8561 
8562   case CK_FloatingRealToComplex: {
8563     APFloat &Real = Result.FloatReal;
8564     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
8565       return false;
8566 
8567     Result.makeComplexFloat();
8568     Result.FloatImag = APFloat(Real.getSemantics());
8569     return true;
8570   }
8571 
8572   case CK_FloatingComplexCast: {
8573     if (!Visit(E->getSubExpr()))
8574       return false;
8575 
8576     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8577     QualType From
8578       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8579 
8580     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8581            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
8582   }
8583 
8584   case CK_FloatingComplexToIntegralComplex: {
8585     if (!Visit(E->getSubExpr()))
8586       return false;
8587 
8588     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8589     QualType From
8590       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8591     Result.makeComplexInt();
8592     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8593                                 To, Result.IntReal) &&
8594            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8595                                 To, Result.IntImag);
8596   }
8597 
8598   case CK_IntegralRealToComplex: {
8599     APSInt &Real = Result.IntReal;
8600     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8601       return false;
8602 
8603     Result.makeComplexInt();
8604     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8605     return true;
8606   }
8607 
8608   case CK_IntegralComplexCast: {
8609     if (!Visit(E->getSubExpr()))
8610       return false;
8611 
8612     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8613     QualType From
8614       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8615 
8616     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8617     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
8618     return true;
8619   }
8620 
8621   case CK_IntegralComplexToFloatingComplex: {
8622     if (!Visit(E->getSubExpr()))
8623       return false;
8624 
8625     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
8626     QualType From
8627       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
8628     Result.makeComplexFloat();
8629     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8630                                 To, Result.FloatReal) &&
8631            HandleIntToFloatCast(Info, E, From, Result.IntImag,
8632                                 To, Result.FloatImag);
8633   }
8634   }
8635 
8636   llvm_unreachable("unknown cast resulting in complex value");
8637 }
8638 
8639 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8640   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8641     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8642 
8643   // Track whether the LHS or RHS is real at the type system level. When this is
8644   // the case we can simplify our evaluation strategy.
8645   bool LHSReal = false, RHSReal = false;
8646 
8647   bool LHSOK;
8648   if (E->getLHS()->getType()->isRealFloatingType()) {
8649     LHSReal = true;
8650     APFloat &Real = Result.FloatReal;
8651     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8652     if (LHSOK) {
8653       Result.makeComplexFloat();
8654       Result.FloatImag = APFloat(Real.getSemantics());
8655     }
8656   } else {
8657     LHSOK = Visit(E->getLHS());
8658   }
8659   if (!LHSOK && !Info.noteFailure())
8660     return false;
8661 
8662   ComplexValue RHS;
8663   if (E->getRHS()->getType()->isRealFloatingType()) {
8664     RHSReal = true;
8665     APFloat &Real = RHS.FloatReal;
8666     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8667       return false;
8668     RHS.makeComplexFloat();
8669     RHS.FloatImag = APFloat(Real.getSemantics());
8670   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8671     return false;
8672 
8673   assert(!(LHSReal && RHSReal) &&
8674          "Cannot have both operands of a complex operation be real.");
8675   switch (E->getOpcode()) {
8676   default: return Error(E);
8677   case BO_Add:
8678     if (Result.isComplexFloat()) {
8679       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8680                                        APFloat::rmNearestTiesToEven);
8681       if (LHSReal)
8682         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8683       else if (!RHSReal)
8684         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8685                                          APFloat::rmNearestTiesToEven);
8686     } else {
8687       Result.getComplexIntReal() += RHS.getComplexIntReal();
8688       Result.getComplexIntImag() += RHS.getComplexIntImag();
8689     }
8690     break;
8691   case BO_Sub:
8692     if (Result.isComplexFloat()) {
8693       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8694                                             APFloat::rmNearestTiesToEven);
8695       if (LHSReal) {
8696         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8697         Result.getComplexFloatImag().changeSign();
8698       } else if (!RHSReal) {
8699         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8700                                               APFloat::rmNearestTiesToEven);
8701       }
8702     } else {
8703       Result.getComplexIntReal() -= RHS.getComplexIntReal();
8704       Result.getComplexIntImag() -= RHS.getComplexIntImag();
8705     }
8706     break;
8707   case BO_Mul:
8708     if (Result.isComplexFloat()) {
8709       // This is an implementation of complex multiplication according to the
8710       // constraints laid out in C11 Annex G. The implemantion uses the
8711       // following naming scheme:
8712       //   (a + ib) * (c + id)
8713       ComplexValue LHS = Result;
8714       APFloat &A = LHS.getComplexFloatReal();
8715       APFloat &B = LHS.getComplexFloatImag();
8716       APFloat &C = RHS.getComplexFloatReal();
8717       APFloat &D = RHS.getComplexFloatImag();
8718       APFloat &ResR = Result.getComplexFloatReal();
8719       APFloat &ResI = Result.getComplexFloatImag();
8720       if (LHSReal) {
8721         assert(!RHSReal && "Cannot have two real operands for a complex op!");
8722         ResR = A * C;
8723         ResI = A * D;
8724       } else if (RHSReal) {
8725         ResR = C * A;
8726         ResI = C * B;
8727       } else {
8728         // In the fully general case, we need to handle NaNs and infinities
8729         // robustly.
8730         APFloat AC = A * C;
8731         APFloat BD = B * D;
8732         APFloat AD = A * D;
8733         APFloat BC = B * C;
8734         ResR = AC - BD;
8735         ResI = AD + BC;
8736         if (ResR.isNaN() && ResI.isNaN()) {
8737           bool Recalc = false;
8738           if (A.isInfinity() || B.isInfinity()) {
8739             A = APFloat::copySign(
8740                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8741             B = APFloat::copySign(
8742                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8743             if (C.isNaN())
8744               C = APFloat::copySign(APFloat(C.getSemantics()), C);
8745             if (D.isNaN())
8746               D = APFloat::copySign(APFloat(D.getSemantics()), D);
8747             Recalc = true;
8748           }
8749           if (C.isInfinity() || D.isInfinity()) {
8750             C = APFloat::copySign(
8751                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8752             D = APFloat::copySign(
8753                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8754             if (A.isNaN())
8755               A = APFloat::copySign(APFloat(A.getSemantics()), A);
8756             if (B.isNaN())
8757               B = APFloat::copySign(APFloat(B.getSemantics()), B);
8758             Recalc = true;
8759           }
8760           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8761                           AD.isInfinity() || BC.isInfinity())) {
8762             if (A.isNaN())
8763               A = APFloat::copySign(APFloat(A.getSemantics()), A);
8764             if (B.isNaN())
8765               B = APFloat::copySign(APFloat(B.getSemantics()), B);
8766             if (C.isNaN())
8767               C = APFloat::copySign(APFloat(C.getSemantics()), C);
8768             if (D.isNaN())
8769               D = APFloat::copySign(APFloat(D.getSemantics()), D);
8770             Recalc = true;
8771           }
8772           if (Recalc) {
8773             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8774             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8775           }
8776         }
8777       }
8778     } else {
8779       ComplexValue LHS = Result;
8780       Result.getComplexIntReal() =
8781         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8782          LHS.getComplexIntImag() * RHS.getComplexIntImag());
8783       Result.getComplexIntImag() =
8784         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8785          LHS.getComplexIntImag() * RHS.getComplexIntReal());
8786     }
8787     break;
8788   case BO_Div:
8789     if (Result.isComplexFloat()) {
8790       // This is an implementation of complex division according to the
8791       // constraints laid out in C11 Annex G. The implemantion uses the
8792       // following naming scheme:
8793       //   (a + ib) / (c + id)
8794       ComplexValue LHS = Result;
8795       APFloat &A = LHS.getComplexFloatReal();
8796       APFloat &B = LHS.getComplexFloatImag();
8797       APFloat &C = RHS.getComplexFloatReal();
8798       APFloat &D = RHS.getComplexFloatImag();
8799       APFloat &ResR = Result.getComplexFloatReal();
8800       APFloat &ResI = Result.getComplexFloatImag();
8801       if (RHSReal) {
8802         ResR = A / C;
8803         ResI = B / C;
8804       } else {
8805         if (LHSReal) {
8806           // No real optimizations we can do here, stub out with zero.
8807           B = APFloat::getZero(A.getSemantics());
8808         }
8809         int DenomLogB = 0;
8810         APFloat MaxCD = maxnum(abs(C), abs(D));
8811         if (MaxCD.isFinite()) {
8812           DenomLogB = ilogb(MaxCD);
8813           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8814           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
8815         }
8816         APFloat Denom = C * C + D * D;
8817         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8818                       APFloat::rmNearestTiesToEven);
8819         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8820                       APFloat::rmNearestTiesToEven);
8821         if (ResR.isNaN() && ResI.isNaN()) {
8822           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8823             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8824             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8825           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8826                      D.isFinite()) {
8827             A = APFloat::copySign(
8828                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8829             B = APFloat::copySign(
8830                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8831             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8832             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8833           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8834             C = APFloat::copySign(
8835                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8836             D = APFloat::copySign(
8837                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8838             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8839             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8840           }
8841         }
8842       }
8843     } else {
8844       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8845         return Error(E, diag::note_expr_divide_by_zero);
8846 
8847       ComplexValue LHS = Result;
8848       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8849         RHS.getComplexIntImag() * RHS.getComplexIntImag();
8850       Result.getComplexIntReal() =
8851         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8852          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8853       Result.getComplexIntImag() =
8854         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8855          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8856     }
8857     break;
8858   }
8859 
8860   return true;
8861 }
8862 
8863 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8864   // Get the operand value into 'Result'.
8865   if (!Visit(E->getSubExpr()))
8866     return false;
8867 
8868   switch (E->getOpcode()) {
8869   default:
8870     return Error(E);
8871   case UO_Extension:
8872     return true;
8873   case UO_Plus:
8874     // The result is always just the subexpr.
8875     return true;
8876   case UO_Minus:
8877     if (Result.isComplexFloat()) {
8878       Result.getComplexFloatReal().changeSign();
8879       Result.getComplexFloatImag().changeSign();
8880     }
8881     else {
8882       Result.getComplexIntReal() = -Result.getComplexIntReal();
8883       Result.getComplexIntImag() = -Result.getComplexIntImag();
8884     }
8885     return true;
8886   case UO_Not:
8887     if (Result.isComplexFloat())
8888       Result.getComplexFloatImag().changeSign();
8889     else
8890       Result.getComplexIntImag() = -Result.getComplexIntImag();
8891     return true;
8892   }
8893 }
8894 
8895 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8896   if (E->getNumInits() == 2) {
8897     if (E->getType()->isComplexType()) {
8898       Result.makeComplexFloat();
8899       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8900         return false;
8901       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8902         return false;
8903     } else {
8904       Result.makeComplexInt();
8905       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8906         return false;
8907       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8908         return false;
8909     }
8910     return true;
8911   }
8912   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8913 }
8914 
8915 //===----------------------------------------------------------------------===//
8916 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8917 // implicit conversion.
8918 //===----------------------------------------------------------------------===//
8919 
8920 namespace {
8921 class AtomicExprEvaluator :
8922     public ExprEvaluatorBase<AtomicExprEvaluator> {
8923   APValue &Result;
8924 public:
8925   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8926       : ExprEvaluatorBaseTy(Info), Result(Result) {}
8927 
8928   bool Success(const APValue &V, const Expr *E) {
8929     Result = V;
8930     return true;
8931   }
8932 
8933   bool ZeroInitialization(const Expr *E) {
8934     ImplicitValueInitExpr VIE(
8935         E->getType()->castAs<AtomicType>()->getValueType());
8936     return Evaluate(Result, Info, &VIE);
8937   }
8938 
8939   bool VisitCastExpr(const CastExpr *E) {
8940     switch (E->getCastKind()) {
8941     default:
8942       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8943     case CK_NonAtomicToAtomic:
8944       return Evaluate(Result, Info, E->getSubExpr());
8945     }
8946   }
8947 };
8948 } // end anonymous namespace
8949 
8950 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8951   assert(E->isRValue() && E->getType()->isAtomicType());
8952   return AtomicExprEvaluator(Info, Result).Visit(E);
8953 }
8954 
8955 //===----------------------------------------------------------------------===//
8956 // Void expression evaluation, primarily for a cast to void on the LHS of a
8957 // comma operator
8958 //===----------------------------------------------------------------------===//
8959 
8960 namespace {
8961 class VoidExprEvaluator
8962   : public ExprEvaluatorBase<VoidExprEvaluator> {
8963 public:
8964   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8965 
8966   bool Success(const APValue &V, const Expr *e) { return true; }
8967 
8968   bool VisitCastExpr(const CastExpr *E) {
8969     switch (E->getCastKind()) {
8970     default:
8971       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8972     case CK_ToVoid:
8973       VisitIgnoredValue(E->getSubExpr());
8974       return true;
8975     }
8976   }
8977 
8978   bool VisitCallExpr(const CallExpr *E) {
8979     switch (E->getBuiltinCallee()) {
8980     default:
8981       return ExprEvaluatorBaseTy::VisitCallExpr(E);
8982     case Builtin::BI__assume:
8983     case Builtin::BI__builtin_assume:
8984       // The argument is not evaluated!
8985       return true;
8986     }
8987   }
8988 };
8989 } // end anonymous namespace
8990 
8991 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8992   assert(E->isRValue() && E->getType()->isVoidType());
8993   return VoidExprEvaluator(Info).Visit(E);
8994 }
8995 
8996 //===----------------------------------------------------------------------===//
8997 // Top level Expr::EvaluateAsRValue method.
8998 //===----------------------------------------------------------------------===//
8999 
9000 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9001   // In C, function designators are not lvalues, but we evaluate them as if they
9002   // are.
9003   QualType T = E->getType();
9004   if (E->isGLValue() || T->isFunctionType()) {
9005     LValue LV;
9006     if (!EvaluateLValue(E, LV, Info))
9007       return false;
9008     LV.moveInto(Result);
9009   } else if (T->isVectorType()) {
9010     if (!EvaluateVector(E, Result, Info))
9011       return false;
9012   } else if (T->isIntegralOrEnumerationType()) {
9013     if (!IntExprEvaluator(Info, Result).Visit(E))
9014       return false;
9015   } else if (T->hasPointerRepresentation()) {
9016     LValue LV;
9017     if (!EvaluatePointer(E, LV, Info))
9018       return false;
9019     LV.moveInto(Result);
9020   } else if (T->isRealFloatingType()) {
9021     llvm::APFloat F(0.0);
9022     if (!EvaluateFloat(E, F, Info))
9023       return false;
9024     Result = APValue(F);
9025   } else if (T->isAnyComplexType()) {
9026     ComplexValue C;
9027     if (!EvaluateComplex(E, C, Info))
9028       return false;
9029     C.moveInto(Result);
9030   } else if (T->isMemberPointerType()) {
9031     MemberPtr P;
9032     if (!EvaluateMemberPointer(E, P, Info))
9033       return false;
9034     P.moveInto(Result);
9035     return true;
9036   } else if (T->isArrayType()) {
9037     LValue LV;
9038     LV.set(E, Info.CurrentCall->Index);
9039     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9040     if (!EvaluateArray(E, LV, Value, Info))
9041       return false;
9042     Result = Value;
9043   } else if (T->isRecordType()) {
9044     LValue LV;
9045     LV.set(E, Info.CurrentCall->Index);
9046     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9047     if (!EvaluateRecord(E, LV, Value, Info))
9048       return false;
9049     Result = Value;
9050   } else if (T->isVoidType()) {
9051     if (!Info.getLangOpts().CPlusPlus11)
9052       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9053         << E->getType();
9054     if (!EvaluateVoid(E, Info))
9055       return false;
9056   } else if (T->isAtomicType()) {
9057     if (!EvaluateAtomic(E, Result, Info))
9058       return false;
9059   } else if (Info.getLangOpts().CPlusPlus11) {
9060     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9061     return false;
9062   } else {
9063     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9064     return false;
9065   }
9066 
9067   return true;
9068 }
9069 
9070 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9071 /// cases, the in-place evaluation is essential, since later initializers for
9072 /// an object can indirectly refer to subobjects which were initialized earlier.
9073 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9074                             const Expr *E, bool AllowNonLiteralTypes) {
9075   assert(!E->isValueDependent());
9076 
9077   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9078     return false;
9079 
9080   if (E->isRValue()) {
9081     // Evaluate arrays and record types in-place, so that later initializers can
9082     // refer to earlier-initialized members of the object.
9083     if (E->getType()->isArrayType())
9084       return EvaluateArray(E, This, Result, Info);
9085     else if (E->getType()->isRecordType())
9086       return EvaluateRecord(E, This, Result, Info);
9087   }
9088 
9089   // For any other type, in-place evaluation is unimportant.
9090   return Evaluate(Result, Info, E);
9091 }
9092 
9093 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9094 /// lvalue-to-rvalue cast if it is an lvalue.
9095 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9096   if (E->getType().isNull())
9097     return false;
9098 
9099   if (!CheckLiteralType(Info, E))
9100     return false;
9101 
9102   if (!::Evaluate(Result, Info, E))
9103     return false;
9104 
9105   if (E->isGLValue()) {
9106     LValue LV;
9107     LV.setFrom(Info.Ctx, Result);
9108     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9109       return false;
9110   }
9111 
9112   // Check this core constant expression is a constant expression.
9113   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9114 }
9115 
9116 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9117                                  const ASTContext &Ctx, bool &IsConst) {
9118   // Fast-path evaluations of integer literals, since we sometimes see files
9119   // containing vast quantities of these.
9120   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9121     Result.Val = APValue(APSInt(L->getValue(),
9122                                 L->getType()->isUnsignedIntegerType()));
9123     IsConst = true;
9124     return true;
9125   }
9126 
9127   // This case should be rare, but we need to check it before we check on
9128   // the type below.
9129   if (Exp->getType().isNull()) {
9130     IsConst = false;
9131     return true;
9132   }
9133 
9134   // FIXME: Evaluating values of large array and record types can cause
9135   // performance problems. Only do so in C++11 for now.
9136   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9137                           Exp->getType()->isRecordType()) &&
9138       !Ctx.getLangOpts().CPlusPlus11) {
9139     IsConst = false;
9140     return true;
9141   }
9142   return false;
9143 }
9144 
9145 
9146 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9147 /// any crazy technique (that has nothing to do with language standards) that
9148 /// we want to.  If this function returns true, it returns the folded constant
9149 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9150 /// will be applied to the result.
9151 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9152   bool IsConst;
9153   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9154     return IsConst;
9155 
9156   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9157   return ::EvaluateAsRValue(Info, this, Result.Val);
9158 }
9159 
9160 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9161                                       const ASTContext &Ctx) const {
9162   EvalResult Scratch;
9163   return EvaluateAsRValue(Scratch, Ctx) &&
9164          HandleConversionToBool(Scratch.Val, Result);
9165 }
9166 
9167 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9168                                       Expr::SideEffectsKind SEK) {
9169   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9170          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9171 }
9172 
9173 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9174                          SideEffectsKind AllowSideEffects) const {
9175   if (!getType()->isIntegralOrEnumerationType())
9176     return false;
9177 
9178   EvalResult ExprResult;
9179   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9180       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9181     return false;
9182 
9183   Result = ExprResult.Val.getInt();
9184   return true;
9185 }
9186 
9187 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9188                            SideEffectsKind AllowSideEffects) const {
9189   if (!getType()->isRealFloatingType())
9190     return false;
9191 
9192   EvalResult ExprResult;
9193   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9194       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9195     return false;
9196 
9197   Result = ExprResult.Val.getFloat();
9198   return true;
9199 }
9200 
9201 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9202   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9203 
9204   LValue LV;
9205   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9206       !CheckLValueConstantExpression(Info, getExprLoc(),
9207                                      Ctx.getLValueReferenceType(getType()), LV))
9208     return false;
9209 
9210   LV.moveInto(Result.Val);
9211   return true;
9212 }
9213 
9214 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9215                                  const VarDecl *VD,
9216                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9217   // FIXME: Evaluating initializers for large array and record types can cause
9218   // performance problems. Only do so in C++11 for now.
9219   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9220       !Ctx.getLangOpts().CPlusPlus11)
9221     return false;
9222 
9223   Expr::EvalStatus EStatus;
9224   EStatus.Diag = &Notes;
9225 
9226   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9227                                       ? EvalInfo::EM_ConstantExpression
9228                                       : EvalInfo::EM_ConstantFold);
9229   InitInfo.setEvaluatingDecl(VD, Value);
9230 
9231   LValue LVal;
9232   LVal.set(VD);
9233 
9234   // C++11 [basic.start.init]p2:
9235   //  Variables with static storage duration or thread storage duration shall be
9236   //  zero-initialized before any other initialization takes place.
9237   // This behavior is not present in C.
9238   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9239       !VD->getType()->isReferenceType()) {
9240     ImplicitValueInitExpr VIE(VD->getType());
9241     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9242                          /*AllowNonLiteralTypes=*/true))
9243       return false;
9244   }
9245 
9246   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9247                        /*AllowNonLiteralTypes=*/true) ||
9248       EStatus.HasSideEffects)
9249     return false;
9250 
9251   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9252                                  Value);
9253 }
9254 
9255 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9256 /// constant folded, but discard the result.
9257 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9258   EvalResult Result;
9259   return EvaluateAsRValue(Result, Ctx) &&
9260          !hasUnacceptableSideEffect(Result, SEK);
9261 }
9262 
9263 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9264                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9265   EvalResult EvalResult;
9266   EvalResult.Diag = Diag;
9267   bool Result = EvaluateAsRValue(EvalResult, Ctx);
9268   (void)Result;
9269   assert(Result && "Could not evaluate expression");
9270   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9271 
9272   return EvalResult.Val.getInt();
9273 }
9274 
9275 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9276   bool IsConst;
9277   EvalResult EvalResult;
9278   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9279     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9280     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9281   }
9282 }
9283 
9284 bool Expr::EvalResult::isGlobalLValue() const {
9285   assert(Val.isLValue());
9286   return IsGlobalLValue(Val.getLValueBase());
9287 }
9288 
9289 
9290 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9291 /// an integer constant expression.
9292 
9293 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9294 /// comma, etc
9295 
9296 // CheckICE - This function does the fundamental ICE checking: the returned
9297 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9298 // and a (possibly null) SourceLocation indicating the location of the problem.
9299 //
9300 // Note that to reduce code duplication, this helper does no evaluation
9301 // itself; the caller checks whether the expression is evaluatable, and
9302 // in the rare cases where CheckICE actually cares about the evaluated
9303 // value, it calls into Evalute.
9304 
9305 namespace {
9306 
9307 enum ICEKind {
9308   /// This expression is an ICE.
9309   IK_ICE,
9310   /// This expression is not an ICE, but if it isn't evaluated, it's
9311   /// a legal subexpression for an ICE. This return value is used to handle
9312   /// the comma operator in C99 mode, and non-constant subexpressions.
9313   IK_ICEIfUnevaluated,
9314   /// This expression is not an ICE, and is not a legal subexpression for one.
9315   IK_NotICE
9316 };
9317 
9318 struct ICEDiag {
9319   ICEKind Kind;
9320   SourceLocation Loc;
9321 
9322   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9323 };
9324 
9325 }
9326 
9327 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9328 
9329 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9330 
9331 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9332   Expr::EvalResult EVResult;
9333   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9334       !EVResult.Val.isInt())
9335     return ICEDiag(IK_NotICE, E->getLocStart());
9336 
9337   return NoDiag();
9338 }
9339 
9340 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9341   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9342   if (!E->getType()->isIntegralOrEnumerationType())
9343     return ICEDiag(IK_NotICE, E->getLocStart());
9344 
9345   switch (E->getStmtClass()) {
9346 #define ABSTRACT_STMT(Node)
9347 #define STMT(Node, Base) case Expr::Node##Class:
9348 #define EXPR(Node, Base)
9349 #include "clang/AST/StmtNodes.inc"
9350   case Expr::PredefinedExprClass:
9351   case Expr::FloatingLiteralClass:
9352   case Expr::ImaginaryLiteralClass:
9353   case Expr::StringLiteralClass:
9354   case Expr::ArraySubscriptExprClass:
9355   case Expr::OMPArraySectionExprClass:
9356   case Expr::MemberExprClass:
9357   case Expr::CompoundAssignOperatorClass:
9358   case Expr::CompoundLiteralExprClass:
9359   case Expr::ExtVectorElementExprClass:
9360   case Expr::DesignatedInitExprClass:
9361   case Expr::NoInitExprClass:
9362   case Expr::DesignatedInitUpdateExprClass:
9363   case Expr::ImplicitValueInitExprClass:
9364   case Expr::ParenListExprClass:
9365   case Expr::VAArgExprClass:
9366   case Expr::AddrLabelExprClass:
9367   case Expr::StmtExprClass:
9368   case Expr::CXXMemberCallExprClass:
9369   case Expr::CUDAKernelCallExprClass:
9370   case Expr::CXXDynamicCastExprClass:
9371   case Expr::CXXTypeidExprClass:
9372   case Expr::CXXUuidofExprClass:
9373   case Expr::MSPropertyRefExprClass:
9374   case Expr::MSPropertySubscriptExprClass:
9375   case Expr::CXXNullPtrLiteralExprClass:
9376   case Expr::UserDefinedLiteralClass:
9377   case Expr::CXXThisExprClass:
9378   case Expr::CXXThrowExprClass:
9379   case Expr::CXXNewExprClass:
9380   case Expr::CXXDeleteExprClass:
9381   case Expr::CXXPseudoDestructorExprClass:
9382   case Expr::UnresolvedLookupExprClass:
9383   case Expr::TypoExprClass:
9384   case Expr::DependentScopeDeclRefExprClass:
9385   case Expr::CXXConstructExprClass:
9386   case Expr::CXXInheritedCtorInitExprClass:
9387   case Expr::CXXStdInitializerListExprClass:
9388   case Expr::CXXBindTemporaryExprClass:
9389   case Expr::ExprWithCleanupsClass:
9390   case Expr::CXXTemporaryObjectExprClass:
9391   case Expr::CXXUnresolvedConstructExprClass:
9392   case Expr::CXXDependentScopeMemberExprClass:
9393   case Expr::UnresolvedMemberExprClass:
9394   case Expr::ObjCStringLiteralClass:
9395   case Expr::ObjCBoxedExprClass:
9396   case Expr::ObjCArrayLiteralClass:
9397   case Expr::ObjCDictionaryLiteralClass:
9398   case Expr::ObjCEncodeExprClass:
9399   case Expr::ObjCMessageExprClass:
9400   case Expr::ObjCSelectorExprClass:
9401   case Expr::ObjCProtocolExprClass:
9402   case Expr::ObjCIvarRefExprClass:
9403   case Expr::ObjCPropertyRefExprClass:
9404   case Expr::ObjCSubscriptRefExprClass:
9405   case Expr::ObjCIsaExprClass:
9406   case Expr::ObjCAvailabilityCheckExprClass:
9407   case Expr::ShuffleVectorExprClass:
9408   case Expr::ConvertVectorExprClass:
9409   case Expr::BlockExprClass:
9410   case Expr::NoStmtClass:
9411   case Expr::OpaqueValueExprClass:
9412   case Expr::PackExpansionExprClass:
9413   case Expr::SubstNonTypeTemplateParmPackExprClass:
9414   case Expr::FunctionParmPackExprClass:
9415   case Expr::AsTypeExprClass:
9416   case Expr::ObjCIndirectCopyRestoreExprClass:
9417   case Expr::MaterializeTemporaryExprClass:
9418   case Expr::PseudoObjectExprClass:
9419   case Expr::AtomicExprClass:
9420   case Expr::LambdaExprClass:
9421   case Expr::CXXFoldExprClass:
9422   case Expr::CoawaitExprClass:
9423   case Expr::CoyieldExprClass:
9424     return ICEDiag(IK_NotICE, E->getLocStart());
9425 
9426   case Expr::InitListExprClass: {
9427     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9428     // form "T x = { a };" is equivalent to "T x = a;".
9429     // Unless we're initializing a reference, T is a scalar as it is known to be
9430     // of integral or enumeration type.
9431     if (E->isRValue())
9432       if (cast<InitListExpr>(E)->getNumInits() == 1)
9433         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9434     return ICEDiag(IK_NotICE, E->getLocStart());
9435   }
9436 
9437   case Expr::SizeOfPackExprClass:
9438   case Expr::GNUNullExprClass:
9439     // GCC considers the GNU __null value to be an integral constant expression.
9440     return NoDiag();
9441 
9442   case Expr::SubstNonTypeTemplateParmExprClass:
9443     return
9444       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9445 
9446   case Expr::ParenExprClass:
9447     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
9448   case Expr::GenericSelectionExprClass:
9449     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
9450   case Expr::IntegerLiteralClass:
9451   case Expr::CharacterLiteralClass:
9452   case Expr::ObjCBoolLiteralExprClass:
9453   case Expr::CXXBoolLiteralExprClass:
9454   case Expr::CXXScalarValueInitExprClass:
9455   case Expr::TypeTraitExprClass:
9456   case Expr::ArrayTypeTraitExprClass:
9457   case Expr::ExpressionTraitExprClass:
9458   case Expr::CXXNoexceptExprClass:
9459     return NoDiag();
9460   case Expr::CallExprClass:
9461   case Expr::CXXOperatorCallExprClass: {
9462     // C99 6.6/3 allows function calls within unevaluated subexpressions of
9463     // constant expressions, but they can never be ICEs because an ICE cannot
9464     // contain an operand of (pointer to) function type.
9465     const CallExpr *CE = cast<CallExpr>(E);
9466     if (CE->getBuiltinCallee())
9467       return CheckEvalInICE(E, Ctx);
9468     return ICEDiag(IK_NotICE, E->getLocStart());
9469   }
9470   case Expr::DeclRefExprClass: {
9471     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9472       return NoDiag();
9473     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
9474     if (Ctx.getLangOpts().CPlusPlus &&
9475         D && IsConstNonVolatile(D->getType())) {
9476       // Parameter variables are never constants.  Without this check,
9477       // getAnyInitializer() can find a default argument, which leads
9478       // to chaos.
9479       if (isa<ParmVarDecl>(D))
9480         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9481 
9482       // C++ 7.1.5.1p2
9483       //   A variable of non-volatile const-qualified integral or enumeration
9484       //   type initialized by an ICE can be used in ICEs.
9485       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
9486         if (!Dcl->getType()->isIntegralOrEnumerationType())
9487           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9488 
9489         const VarDecl *VD;
9490         // Look for a declaration of this variable that has an initializer, and
9491         // check whether it is an ICE.
9492         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9493           return NoDiag();
9494         else
9495           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9496       }
9497     }
9498     return ICEDiag(IK_NotICE, E->getLocStart());
9499   }
9500   case Expr::UnaryOperatorClass: {
9501     const UnaryOperator *Exp = cast<UnaryOperator>(E);
9502     switch (Exp->getOpcode()) {
9503     case UO_PostInc:
9504     case UO_PostDec:
9505     case UO_PreInc:
9506     case UO_PreDec:
9507     case UO_AddrOf:
9508     case UO_Deref:
9509     case UO_Coawait:
9510       // C99 6.6/3 allows increment and decrement within unevaluated
9511       // subexpressions of constant expressions, but they can never be ICEs
9512       // because an ICE cannot contain an lvalue operand.
9513       return ICEDiag(IK_NotICE, E->getLocStart());
9514     case UO_Extension:
9515     case UO_LNot:
9516     case UO_Plus:
9517     case UO_Minus:
9518     case UO_Not:
9519     case UO_Real:
9520     case UO_Imag:
9521       return CheckICE(Exp->getSubExpr(), Ctx);
9522     }
9523 
9524     // OffsetOf falls through here.
9525   }
9526   case Expr::OffsetOfExprClass: {
9527     // Note that per C99, offsetof must be an ICE. And AFAIK, using
9528     // EvaluateAsRValue matches the proposed gcc behavior for cases like
9529     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
9530     // compliance: we should warn earlier for offsetof expressions with
9531     // array subscripts that aren't ICEs, and if the array subscripts
9532     // are ICEs, the value of the offsetof must be an integer constant.
9533     return CheckEvalInICE(E, Ctx);
9534   }
9535   case Expr::UnaryExprOrTypeTraitExprClass: {
9536     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9537     if ((Exp->getKind() ==  UETT_SizeOf) &&
9538         Exp->getTypeOfArgument()->isVariableArrayType())
9539       return ICEDiag(IK_NotICE, E->getLocStart());
9540     return NoDiag();
9541   }
9542   case Expr::BinaryOperatorClass: {
9543     const BinaryOperator *Exp = cast<BinaryOperator>(E);
9544     switch (Exp->getOpcode()) {
9545     case BO_PtrMemD:
9546     case BO_PtrMemI:
9547     case BO_Assign:
9548     case BO_MulAssign:
9549     case BO_DivAssign:
9550     case BO_RemAssign:
9551     case BO_AddAssign:
9552     case BO_SubAssign:
9553     case BO_ShlAssign:
9554     case BO_ShrAssign:
9555     case BO_AndAssign:
9556     case BO_XorAssign:
9557     case BO_OrAssign:
9558       // C99 6.6/3 allows assignments within unevaluated subexpressions of
9559       // constant expressions, but they can never be ICEs because an ICE cannot
9560       // contain an lvalue operand.
9561       return ICEDiag(IK_NotICE, E->getLocStart());
9562 
9563     case BO_Mul:
9564     case BO_Div:
9565     case BO_Rem:
9566     case BO_Add:
9567     case BO_Sub:
9568     case BO_Shl:
9569     case BO_Shr:
9570     case BO_LT:
9571     case BO_GT:
9572     case BO_LE:
9573     case BO_GE:
9574     case BO_EQ:
9575     case BO_NE:
9576     case BO_And:
9577     case BO_Xor:
9578     case BO_Or:
9579     case BO_Comma: {
9580       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9581       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9582       if (Exp->getOpcode() == BO_Div ||
9583           Exp->getOpcode() == BO_Rem) {
9584         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
9585         // we don't evaluate one.
9586         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
9587           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
9588           if (REval == 0)
9589             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9590           if (REval.isSigned() && REval.isAllOnesValue()) {
9591             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
9592             if (LEval.isMinSignedValue())
9593               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9594           }
9595         }
9596       }
9597       if (Exp->getOpcode() == BO_Comma) {
9598         if (Ctx.getLangOpts().C99) {
9599           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9600           // if it isn't evaluated.
9601           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9602             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9603         } else {
9604           // In both C89 and C++, commas in ICEs are illegal.
9605           return ICEDiag(IK_NotICE, E->getLocStart());
9606         }
9607       }
9608       return Worst(LHSResult, RHSResult);
9609     }
9610     case BO_LAnd:
9611     case BO_LOr: {
9612       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9613       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9614       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
9615         // Rare case where the RHS has a comma "side-effect"; we need
9616         // to actually check the condition to see whether the side
9617         // with the comma is evaluated.
9618         if ((Exp->getOpcode() == BO_LAnd) !=
9619             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
9620           return RHSResult;
9621         return NoDiag();
9622       }
9623 
9624       return Worst(LHSResult, RHSResult);
9625     }
9626     }
9627   }
9628   case Expr::ImplicitCastExprClass:
9629   case Expr::CStyleCastExprClass:
9630   case Expr::CXXFunctionalCastExprClass:
9631   case Expr::CXXStaticCastExprClass:
9632   case Expr::CXXReinterpretCastExprClass:
9633   case Expr::CXXConstCastExprClass:
9634   case Expr::ObjCBridgedCastExprClass: {
9635     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
9636     if (isa<ExplicitCastExpr>(E)) {
9637       if (const FloatingLiteral *FL
9638             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9639         unsigned DestWidth = Ctx.getIntWidth(E->getType());
9640         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9641         APSInt IgnoredVal(DestWidth, !DestSigned);
9642         bool Ignored;
9643         // If the value does not fit in the destination type, the behavior is
9644         // undefined, so we are not required to treat it as a constant
9645         // expression.
9646         if (FL->getValue().convertToInteger(IgnoredVal,
9647                                             llvm::APFloat::rmTowardZero,
9648                                             &Ignored) & APFloat::opInvalidOp)
9649           return ICEDiag(IK_NotICE, E->getLocStart());
9650         return NoDiag();
9651       }
9652     }
9653     switch (cast<CastExpr>(E)->getCastKind()) {
9654     case CK_LValueToRValue:
9655     case CK_AtomicToNonAtomic:
9656     case CK_NonAtomicToAtomic:
9657     case CK_NoOp:
9658     case CK_IntegralToBoolean:
9659     case CK_IntegralCast:
9660       return CheckICE(SubExpr, Ctx);
9661     default:
9662       return ICEDiag(IK_NotICE, E->getLocStart());
9663     }
9664   }
9665   case Expr::BinaryConditionalOperatorClass: {
9666     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9667     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
9668     if (CommonResult.Kind == IK_NotICE) return CommonResult;
9669     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9670     if (FalseResult.Kind == IK_NotICE) return FalseResult;
9671     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9672     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
9673         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
9674     return FalseResult;
9675   }
9676   case Expr::ConditionalOperatorClass: {
9677     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9678     // If the condition (ignoring parens) is a __builtin_constant_p call,
9679     // then only the true side is actually considered in an integer constant
9680     // expression, and it is fully evaluated.  This is an important GNU
9681     // extension.  See GCC PR38377 for discussion.
9682     if (const CallExpr *CallCE
9683         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
9684       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
9685         return CheckEvalInICE(E, Ctx);
9686     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
9687     if (CondResult.Kind == IK_NotICE)
9688       return CondResult;
9689 
9690     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9691     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9692 
9693     if (TrueResult.Kind == IK_NotICE)
9694       return TrueResult;
9695     if (FalseResult.Kind == IK_NotICE)
9696       return FalseResult;
9697     if (CondResult.Kind == IK_ICEIfUnevaluated)
9698       return CondResult;
9699     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9700       return NoDiag();
9701     // Rare case where the diagnostics depend on which side is evaluated
9702     // Note that if we get here, CondResult is 0, and at least one of
9703     // TrueResult and FalseResult is non-zero.
9704     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9705       return FalseResult;
9706     return TrueResult;
9707   }
9708   case Expr::CXXDefaultArgExprClass:
9709     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9710   case Expr::CXXDefaultInitExprClass:
9711     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9712   case Expr::ChooseExprClass: {
9713     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9714   }
9715   }
9716 
9717   llvm_unreachable("Invalid StmtClass!");
9718 }
9719 
9720 /// Evaluate an expression as a C++11 integral constant expression.
9721 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9722                                                     const Expr *E,
9723                                                     llvm::APSInt *Value,
9724                                                     SourceLocation *Loc) {
9725   if (!E->getType()->isIntegralOrEnumerationType()) {
9726     if (Loc) *Loc = E->getExprLoc();
9727     return false;
9728   }
9729 
9730   APValue Result;
9731   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9732     return false;
9733 
9734   if (!Result.isInt()) {
9735     if (Loc) *Loc = E->getExprLoc();
9736     return false;
9737   }
9738 
9739   if (Value) *Value = Result.getInt();
9740   return true;
9741 }
9742 
9743 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9744                                  SourceLocation *Loc) const {
9745   if (Ctx.getLangOpts().CPlusPlus11)
9746     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9747 
9748   ICEDiag D = CheckICE(this, Ctx);
9749   if (D.Kind != IK_ICE) {
9750     if (Loc) *Loc = D.Loc;
9751     return false;
9752   }
9753   return true;
9754 }
9755 
9756 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9757                                  SourceLocation *Loc, bool isEvaluated) const {
9758   if (Ctx.getLangOpts().CPlusPlus11)
9759     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9760 
9761   if (!isIntegerConstantExpr(Ctx, Loc))
9762     return false;
9763   // The only possible side-effects here are due to UB discovered in the
9764   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9765   // required to treat the expression as an ICE, so we produce the folded
9766   // value.
9767   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
9768     llvm_unreachable("ICE cannot be evaluated!");
9769   return true;
9770 }
9771 
9772 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9773   return CheckICE(this, Ctx).Kind == IK_ICE;
9774 }
9775 
9776 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9777                                SourceLocation *Loc) const {
9778   // We support this checking in C++98 mode in order to diagnose compatibility
9779   // issues.
9780   assert(Ctx.getLangOpts().CPlusPlus);
9781 
9782   // Build evaluation settings.
9783   Expr::EvalStatus Status;
9784   SmallVector<PartialDiagnosticAt, 8> Diags;
9785   Status.Diag = &Diags;
9786   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9787 
9788   APValue Scratch;
9789   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9790 
9791   if (!Diags.empty()) {
9792     IsConstExpr = false;
9793     if (Loc) *Loc = Diags[0].first;
9794   } else if (!IsConstExpr) {
9795     // FIXME: This shouldn't happen.
9796     if (Loc) *Loc = getExprLoc();
9797   }
9798 
9799   return IsConstExpr;
9800 }
9801 
9802 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9803                                     const FunctionDecl *Callee,
9804                                     ArrayRef<const Expr*> Args) const {
9805   Expr::EvalStatus Status;
9806   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9807 
9808   ArgVector ArgValues(Args.size());
9809   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9810        I != E; ++I) {
9811     if ((*I)->isValueDependent() ||
9812         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9813       // If evaluation fails, throw away the argument entirely.
9814       ArgValues[I - Args.begin()] = APValue();
9815     if (Info.EvalStatus.HasSideEffects)
9816       return false;
9817   }
9818 
9819   // Build fake call to Callee.
9820   CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9821                        ArgValues.data());
9822   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9823 }
9824 
9825 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9826                                    SmallVectorImpl<
9827                                      PartialDiagnosticAt> &Diags) {
9828   // FIXME: It would be useful to check constexpr function templates, but at the
9829   // moment the constant expression evaluator cannot cope with the non-rigorous
9830   // ASTs which we build for dependent expressions.
9831   if (FD->isDependentContext())
9832     return true;
9833 
9834   Expr::EvalStatus Status;
9835   Status.Diag = &Diags;
9836 
9837   EvalInfo Info(FD->getASTContext(), Status,
9838                 EvalInfo::EM_PotentialConstantExpression);
9839 
9840   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9841   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9842 
9843   // Fabricate an arbitrary expression on the stack and pretend that it
9844   // is a temporary being used as the 'this' pointer.
9845   LValue This;
9846   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9847   This.set(&VIE, Info.CurrentCall->Index);
9848 
9849   ArrayRef<const Expr*> Args;
9850 
9851   APValue Scratch;
9852   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9853     // Evaluate the call as a constant initializer, to allow the construction
9854     // of objects of non-literal types.
9855     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9856     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
9857   } else {
9858     SourceLocation Loc = FD->getLocation();
9859     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9860                        Args, FD->getBody(), Info, Scratch, nullptr);
9861   }
9862 
9863   return Diags.empty();
9864 }
9865 
9866 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9867                                               const FunctionDecl *FD,
9868                                               SmallVectorImpl<
9869                                                 PartialDiagnosticAt> &Diags) {
9870   Expr::EvalStatus Status;
9871   Status.Diag = &Diags;
9872 
9873   EvalInfo Info(FD->getASTContext(), Status,
9874                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9875 
9876   // Fabricate a call stack frame to give the arguments a plausible cover story.
9877   ArrayRef<const Expr*> Args;
9878   ArgVector ArgValues(0);
9879   bool Success = EvaluateArgs(Args, ArgValues, Info);
9880   (void)Success;
9881   assert(Success &&
9882          "Failed to set up arguments for potential constant evaluation");
9883   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9884 
9885   APValue ResultScratch;
9886   Evaluate(ResultScratch, Info, E);
9887   return Diags.empty();
9888 }
9889 
9890 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9891                                  unsigned Type) const {
9892   if (!getType()->isPointerType())
9893     return false;
9894 
9895   Expr::EvalStatus Status;
9896   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9897   return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9898 }
9899