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