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