]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp
MFV r316083,316094:
[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. In certain scenarios, if:
608       /// - we find a MemberExpr with a base that can't be evaluated, or
609       /// - we find a variable initialized with a call to a function that has
610       ///   the alloc_size attribute on it
611       /// then we may consider evaluation to have succeeded.
612       ///
613       /// In either case, the LValue returned shall have an invalid base; in the
614       /// former, the base will be the invalid MemberExpr, in the latter, the
615       /// base will be either the alloc_size CallExpr or a CastExpr wrapping
616       /// said CallExpr.
617       EM_OffsetFold,
618     } EvalMode;
619
620     /// Are we checking whether the expression is a potential constant
621     /// expression?
622     bool checkingPotentialConstantExpression() const {
623       return EvalMode == EM_PotentialConstantExpression ||
624              EvalMode == EM_PotentialConstantExpressionUnevaluated;
625     }
626
627     /// Are we checking an expression for overflow?
628     // FIXME: We should check for any kind of undefined or suspicious behavior
629     // in such constructs, not just overflow.
630     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
631
632     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
633       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
634         CallStackDepth(0), NextCallIndex(1),
635         StepsLeft(getLangOpts().ConstexprStepLimit),
636         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
637         EvaluatingDecl((const ValueDecl *)nullptr),
638         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
639         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
640         EvalMode(Mode) {}
641
642     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
643       EvaluatingDecl = Base;
644       EvaluatingDeclValue = &Value;
645     }
646
647     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
648
649     bool CheckCallLimit(SourceLocation Loc) {
650       // Don't perform any constexpr calls (other than the call we're checking)
651       // when checking a potential constant expression.
652       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
653         return false;
654       if (NextCallIndex == 0) {
655         // NextCallIndex has wrapped around.
656         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
657         return false;
658       }
659       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
660         return true;
661       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
662         << getLangOpts().ConstexprCallDepth;
663       return false;
664     }
665
666     CallStackFrame *getCallFrame(unsigned CallIndex) {
667       assert(CallIndex && "no call index in getCallFrame");
668       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
669       // be null in this loop.
670       CallStackFrame *Frame = CurrentCall;
671       while (Frame->Index > CallIndex)
672         Frame = Frame->Caller;
673       return (Frame->Index == CallIndex) ? Frame : nullptr;
674     }
675
676     bool nextStep(const Stmt *S) {
677       if (!StepsLeft) {
678         FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
679         return false;
680       }
681       --StepsLeft;
682       return true;
683     }
684
685   private:
686     /// Add a diagnostic to the diagnostics list.
687     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
688       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
689       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
690       return EvalStatus.Diag->back().second;
691     }
692
693     /// Add notes containing a call stack to the current point of evaluation.
694     void addCallStack(unsigned Limit);
695
696   private:
697     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
698                             unsigned ExtraNotes, bool IsCCEDiag) {
699     
700       if (EvalStatus.Diag) {
701         // If we have a prior diagnostic, it will be noting that the expression
702         // isn't a constant expression. This diagnostic is more important,
703         // unless we require this evaluation to produce a constant expression.
704         //
705         // FIXME: We might want to show both diagnostics to the user in
706         // EM_ConstantFold mode.
707         if (!EvalStatus.Diag->empty()) {
708           switch (EvalMode) {
709           case EM_ConstantFold:
710           case EM_IgnoreSideEffects:
711           case EM_EvaluateForOverflow:
712             if (!HasFoldFailureDiagnostic)
713               break;
714             // We've already failed to fold something. Keep that diagnostic.
715           case EM_ConstantExpression:
716           case EM_PotentialConstantExpression:
717           case EM_ConstantExpressionUnevaluated:
718           case EM_PotentialConstantExpressionUnevaluated:
719           case EM_OffsetFold:
720             HasActiveDiagnostic = false;
721             return OptionalDiagnostic();
722           }
723         }
724
725         unsigned CallStackNotes = CallStackDepth - 1;
726         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
727         if (Limit)
728           CallStackNotes = std::min(CallStackNotes, Limit + 1);
729         if (checkingPotentialConstantExpression())
730           CallStackNotes = 0;
731
732         HasActiveDiagnostic = true;
733         HasFoldFailureDiagnostic = !IsCCEDiag;
734         EvalStatus.Diag->clear();
735         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
736         addDiag(Loc, DiagId);
737         if (!checkingPotentialConstantExpression())
738           addCallStack(Limit);
739         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
740       }
741       HasActiveDiagnostic = false;
742       return OptionalDiagnostic();
743     }
744   public:
745     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
746     OptionalDiagnostic
747     FFDiag(SourceLocation Loc,
748           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
749           unsigned ExtraNotes = 0) {
750       return Diag(Loc, DiagId, ExtraNotes, false);
751     }
752     
753     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
754                               = diag::note_invalid_subexpr_in_const_expr,
755                             unsigned ExtraNotes = 0) {
756       if (EvalStatus.Diag)
757         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
758       HasActiveDiagnostic = false;
759       return OptionalDiagnostic();
760     }
761
762     /// Diagnose that the evaluation does not produce a C++11 core constant
763     /// expression.
764     ///
765     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
766     /// EM_PotentialConstantExpression mode and we produce one of these.
767     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
768                                  = diag::note_invalid_subexpr_in_const_expr,
769                                unsigned ExtraNotes = 0) {
770       // Don't override a previous diagnostic. Don't bother collecting
771       // diagnostics if we're evaluating for overflow.
772       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
773         HasActiveDiagnostic = false;
774         return OptionalDiagnostic();
775       }
776       return Diag(Loc, DiagId, ExtraNotes, true);
777     }
778     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
779                                  = diag::note_invalid_subexpr_in_const_expr,
780                                unsigned ExtraNotes = 0) {
781       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
782     }
783     /// Add a note to a prior diagnostic.
784     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
785       if (!HasActiveDiagnostic)
786         return OptionalDiagnostic();
787       return OptionalDiagnostic(&addDiag(Loc, DiagId));
788     }
789
790     /// Add a stack of notes to a prior diagnostic.
791     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
792       if (HasActiveDiagnostic) {
793         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
794                                 Diags.begin(), Diags.end());
795       }
796     }
797
798     /// Should we continue evaluation after encountering a side-effect that we
799     /// couldn't model?
800     bool keepEvaluatingAfterSideEffect() {
801       switch (EvalMode) {
802       case EM_PotentialConstantExpression:
803       case EM_PotentialConstantExpressionUnevaluated:
804       case EM_EvaluateForOverflow:
805       case EM_IgnoreSideEffects:
806         return true;
807
808       case EM_ConstantExpression:
809       case EM_ConstantExpressionUnevaluated:
810       case EM_ConstantFold:
811       case EM_OffsetFold:
812         return false;
813       }
814       llvm_unreachable("Missed EvalMode case");
815     }
816
817     /// Note that we have had a side-effect, and determine whether we should
818     /// keep evaluating.
819     bool noteSideEffect() {
820       EvalStatus.HasSideEffects = true;
821       return keepEvaluatingAfterSideEffect();
822     }
823
824     /// Should we continue evaluation after encountering undefined behavior?
825     bool keepEvaluatingAfterUndefinedBehavior() {
826       switch (EvalMode) {
827       case EM_EvaluateForOverflow:
828       case EM_IgnoreSideEffects:
829       case EM_ConstantFold:
830       case EM_OffsetFold:
831         return true;
832
833       case EM_PotentialConstantExpression:
834       case EM_PotentialConstantExpressionUnevaluated:
835       case EM_ConstantExpression:
836       case EM_ConstantExpressionUnevaluated:
837         return false;
838       }
839       llvm_unreachable("Missed EvalMode case");
840     }
841
842     /// Note that we hit something that was technically undefined behavior, but
843     /// that we can evaluate past it (such as signed overflow or floating-point
844     /// division by zero.)
845     bool noteUndefinedBehavior() {
846       EvalStatus.HasUndefinedBehavior = true;
847       return keepEvaluatingAfterUndefinedBehavior();
848     }
849
850     /// Should we continue evaluation as much as possible after encountering a
851     /// construct which can't be reduced to a value?
852     bool keepEvaluatingAfterFailure() {
853       if (!StepsLeft)
854         return false;
855
856       switch (EvalMode) {
857       case EM_PotentialConstantExpression:
858       case EM_PotentialConstantExpressionUnevaluated:
859       case EM_EvaluateForOverflow:
860         return true;
861
862       case EM_ConstantExpression:
863       case EM_ConstantExpressionUnevaluated:
864       case EM_ConstantFold:
865       case EM_IgnoreSideEffects:
866       case EM_OffsetFold:
867         return false;
868       }
869       llvm_unreachable("Missed EvalMode case");
870     }
871
872     /// Notes that we failed to evaluate an expression that other expressions
873     /// directly depend on, and determine if we should keep evaluating. This
874     /// should only be called if we actually intend to keep evaluating.
875     ///
876     /// Call noteSideEffect() instead if we may be able to ignore the value that
877     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
878     ///
879     /// (Foo(), 1)      // use noteSideEffect
880     /// (Foo() || true) // use noteSideEffect
881     /// Foo() + 1       // use noteFailure
882     LLVM_NODISCARD bool noteFailure() {
883       // Failure when evaluating some expression often means there is some
884       // subexpression whose evaluation was skipped. Therefore, (because we
885       // don't track whether we skipped an expression when unwinding after an
886       // evaluation failure) every evaluation failure that bubbles up from a
887       // subexpression implies that a side-effect has potentially happened. We
888       // skip setting the HasSideEffects flag to true until we decide to
889       // continue evaluating after that point, which happens here.
890       bool KeepGoing = keepEvaluatingAfterFailure();
891       EvalStatus.HasSideEffects |= KeepGoing;
892       return KeepGoing;
893     }
894
895     class ArrayInitLoopIndex {
896       EvalInfo &Info;
897       uint64_t OuterIndex;
898
899     public:
900       ArrayInitLoopIndex(EvalInfo &Info)
901           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
902         Info.ArrayInitIndex = 0;
903       }
904       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
905
906       operator uint64_t&() { return Info.ArrayInitIndex; }
907     };
908   };
909
910   /// Object used to treat all foldable expressions as constant expressions.
911   struct FoldConstant {
912     EvalInfo &Info;
913     bool Enabled;
914     bool HadNoPriorDiags;
915     EvalInfo::EvaluationMode OldMode;
916
917     explicit FoldConstant(EvalInfo &Info, bool Enabled)
918       : Info(Info),
919         Enabled(Enabled),
920         HadNoPriorDiags(Info.EvalStatus.Diag &&
921                         Info.EvalStatus.Diag->empty() &&
922                         !Info.EvalStatus.HasSideEffects),
923         OldMode(Info.EvalMode) {
924       if (Enabled &&
925           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
926            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
927         Info.EvalMode = EvalInfo::EM_ConstantFold;
928     }
929     void keepDiagnostics() { Enabled = false; }
930     ~FoldConstant() {
931       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
932           !Info.EvalStatus.HasSideEffects)
933         Info.EvalStatus.Diag->clear();
934       Info.EvalMode = OldMode;
935     }
936   };
937
938   /// RAII object used to treat the current evaluation as the correct pointer
939   /// offset fold for the current EvalMode
940   struct FoldOffsetRAII {
941     EvalInfo &Info;
942     EvalInfo::EvaluationMode OldMode;
943     explicit FoldOffsetRAII(EvalInfo &Info)
944         : Info(Info), OldMode(Info.EvalMode) {
945       if (!Info.checkingPotentialConstantExpression())
946         Info.EvalMode = EvalInfo::EM_OffsetFold;
947     }
948
949     ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
950   };
951
952   /// RAII object used to optionally suppress diagnostics and side-effects from
953   /// a speculative evaluation.
954   class SpeculativeEvaluationRAII {
955     /// Pair of EvalInfo, and a bit that stores whether or not we were
956     /// speculatively evaluating when we created this RAII.
957     llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
958     Expr::EvalStatus Old;
959
960     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
961       InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
962       Old = Other.Old;
963       Other.InfoAndOldSpecEval.setPointer(nullptr);
964     }
965
966     void maybeRestoreState() {
967       EvalInfo *Info = InfoAndOldSpecEval.getPointer();
968       if (!Info)
969         return;
970
971       Info->EvalStatus = Old;
972       Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
973     }
974
975   public:
976     SpeculativeEvaluationRAII() = default;
977
978     SpeculativeEvaluationRAII(
979         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
980         : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
981           Old(Info.EvalStatus) {
982       Info.EvalStatus.Diag = NewDiag;
983       Info.IsSpeculativelyEvaluating = true;
984     }
985
986     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
987     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
988       moveFromAndCancel(std::move(Other));
989     }
990
991     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
992       maybeRestoreState();
993       moveFromAndCancel(std::move(Other));
994       return *this;
995     }
996
997     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
998   };
999
1000   /// RAII object wrapping a full-expression or block scope, and handling
1001   /// the ending of the lifetime of temporaries created within it.
1002   template<bool IsFullExpression>
1003   class ScopeRAII {
1004     EvalInfo &Info;
1005     unsigned OldStackSize;
1006   public:
1007     ScopeRAII(EvalInfo &Info)
1008         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1009     ~ScopeRAII() {
1010       // Body moved to a static method to encourage the compiler to inline away
1011       // instances of this class.
1012       cleanup(Info, OldStackSize);
1013     }
1014   private:
1015     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1016       unsigned NewEnd = OldStackSize;
1017       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1018            I != N; ++I) {
1019         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1020           // Full-expression cleanup of a lifetime-extended temporary: nothing
1021           // to do, just move this cleanup to the right place in the stack.
1022           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1023           ++NewEnd;
1024         } else {
1025           // End the lifetime of the object.
1026           Info.CleanupStack[I].endLifetime();
1027         }
1028       }
1029       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1030                               Info.CleanupStack.end());
1031     }
1032   };
1033   typedef ScopeRAII<false> BlockScopeRAII;
1034   typedef ScopeRAII<true> FullExpressionRAII;
1035 }
1036
1037 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1038                                          CheckSubobjectKind CSK) {
1039   if (Invalid)
1040     return false;
1041   if (isOnePastTheEnd()) {
1042     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1043       << CSK;
1044     setInvalid();
1045     return false;
1046   }
1047   return true;
1048 }
1049
1050 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1051                                                     const Expr *E, uint64_t N) {
1052   // If we're complaining, we must be able to statically determine the size of
1053   // the most derived array.
1054   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1055     Info.CCEDiag(E, diag::note_constexpr_array_index)
1056       << static_cast<int>(N) << /*array*/ 0
1057       << static_cast<unsigned>(getMostDerivedArraySize());
1058   else
1059     Info.CCEDiag(E, diag::note_constexpr_array_index)
1060       << static_cast<int>(N) << /*non-array*/ 1;
1061   setInvalid();
1062 }
1063
1064 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1065                                const FunctionDecl *Callee, const LValue *This,
1066                                APValue *Arguments)
1067     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1068       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1069   Info.CurrentCall = this;
1070   ++Info.CallStackDepth;
1071 }
1072
1073 CallStackFrame::~CallStackFrame() {
1074   assert(Info.CurrentCall == this && "calls retired out of order");
1075   --Info.CallStackDepth;
1076   Info.CurrentCall = Caller;
1077 }
1078
1079 APValue &CallStackFrame::createTemporary(const void *Key,
1080                                          bool IsLifetimeExtended) {
1081   APValue &Result = Temporaries[Key];
1082   assert(Result.isUninit() && "temporary created multiple times");
1083   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1084   return Result;
1085 }
1086
1087 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1088
1089 void EvalInfo::addCallStack(unsigned Limit) {
1090   // Determine which calls to skip, if any.
1091   unsigned ActiveCalls = CallStackDepth - 1;
1092   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1093   if (Limit && Limit < ActiveCalls) {
1094     SkipStart = Limit / 2 + Limit % 2;
1095     SkipEnd = ActiveCalls - Limit / 2;
1096   }
1097
1098   // Walk the call stack and add the diagnostics.
1099   unsigned CallIdx = 0;
1100   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1101        Frame = Frame->Caller, ++CallIdx) {
1102     // Skip this call?
1103     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1104       if (CallIdx == SkipStart) {
1105         // Note that we're skipping calls.
1106         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1107           << unsigned(ActiveCalls - Limit);
1108       }
1109       continue;
1110     }
1111
1112     // Use a different note for an inheriting constructor, because from the
1113     // user's perspective it's not really a function at all.
1114     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1115       if (CD->isInheritingConstructor()) {
1116         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1117           << CD->getParent();
1118         continue;
1119       }
1120     }
1121
1122     SmallVector<char, 128> Buffer;
1123     llvm::raw_svector_ostream Out(Buffer);
1124     describeCall(Frame, Out);
1125     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1126   }
1127 }
1128
1129 namespace {
1130   struct ComplexValue {
1131   private:
1132     bool IsInt;
1133
1134   public:
1135     APSInt IntReal, IntImag;
1136     APFloat FloatReal, FloatImag;
1137
1138     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1139
1140     void makeComplexFloat() { IsInt = false; }
1141     bool isComplexFloat() const { return !IsInt; }
1142     APFloat &getComplexFloatReal() { return FloatReal; }
1143     APFloat &getComplexFloatImag() { return FloatImag; }
1144
1145     void makeComplexInt() { IsInt = true; }
1146     bool isComplexInt() const { return IsInt; }
1147     APSInt &getComplexIntReal() { return IntReal; }
1148     APSInt &getComplexIntImag() { return IntImag; }
1149
1150     void moveInto(APValue &v) const {
1151       if (isComplexFloat())
1152         v = APValue(FloatReal, FloatImag);
1153       else
1154         v = APValue(IntReal, IntImag);
1155     }
1156     void setFrom(const APValue &v) {
1157       assert(v.isComplexFloat() || v.isComplexInt());
1158       if (v.isComplexFloat()) {
1159         makeComplexFloat();
1160         FloatReal = v.getComplexFloatReal();
1161         FloatImag = v.getComplexFloatImag();
1162       } else {
1163         makeComplexInt();
1164         IntReal = v.getComplexIntReal();
1165         IntImag = v.getComplexIntImag();
1166       }
1167     }
1168   };
1169
1170   struct LValue {
1171     APValue::LValueBase Base;
1172     CharUnits Offset;
1173     unsigned InvalidBase : 1;
1174     unsigned CallIndex : 31;
1175     SubobjectDesignator Designator;
1176     bool IsNullPtr;
1177
1178     const APValue::LValueBase getLValueBase() const { return Base; }
1179     CharUnits &getLValueOffset() { return Offset; }
1180     const CharUnits &getLValueOffset() const { return Offset; }
1181     unsigned getLValueCallIndex() const { return CallIndex; }
1182     SubobjectDesignator &getLValueDesignator() { return Designator; }
1183     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1184     bool isNullPointer() const { return IsNullPtr;}
1185
1186     void moveInto(APValue &V) const {
1187       if (Designator.Invalid)
1188         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1189                     IsNullPtr);
1190       else {
1191         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1192         assert(!Designator.FirstEntryIsAnUnsizedArray &&
1193                "Unsized array with a valid base?");
1194         V = APValue(Base, Offset, Designator.Entries,
1195                     Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1196       }
1197     }
1198     void setFrom(ASTContext &Ctx, const APValue &V) {
1199       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1200       Base = V.getLValueBase();
1201       Offset = V.getLValueOffset();
1202       InvalidBase = false;
1203       CallIndex = V.getLValueCallIndex();
1204       Designator = SubobjectDesignator(Ctx, V);
1205       IsNullPtr = V.isNullPointer();
1206     }
1207
1208     void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1209              bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1210 #ifndef NDEBUG
1211       // We only allow a few types of invalid bases. Enforce that here.
1212       if (BInvalid) {
1213         const auto *E = B.get<const Expr *>();
1214         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1215                "Unexpected type of invalid base");
1216       }
1217 #endif
1218
1219       Base = B;
1220       Offset = CharUnits::fromQuantity(Offset_);
1221       InvalidBase = BInvalid;
1222       CallIndex = I;
1223       Designator = SubobjectDesignator(getType(B));
1224       IsNullPtr = IsNullPtr_;
1225     }
1226
1227     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1228       set(B, I, true);
1229     }
1230
1231     // Check that this LValue is not based on a null pointer. If it is, produce
1232     // a diagnostic and mark the designator as invalid.
1233     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1234                           CheckSubobjectKind CSK) {
1235       if (Designator.Invalid)
1236         return false;
1237       if (IsNullPtr) {
1238         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1239           << CSK;
1240         Designator.setInvalid();
1241         return false;
1242       }
1243       return true;
1244     }
1245
1246     // Check this LValue refers to an object. If not, set the designator to be
1247     // invalid and emit a diagnostic.
1248     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1249       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1250              Designator.checkSubobject(Info, E, CSK);
1251     }
1252
1253     void addDecl(EvalInfo &Info, const Expr *E,
1254                  const Decl *D, bool Virtual = false) {
1255       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1256         Designator.addDeclUnchecked(D, Virtual);
1257     }
1258     void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1259       assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1260       assert(isBaseAnAllocSizeCall(Base) &&
1261              "Only alloc_size bases can have unsized arrays");
1262       Designator.FirstEntryIsAnUnsizedArray = true;
1263       Designator.addUnsizedArrayUnchecked(ElemTy);
1264     }
1265     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1266       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1267         Designator.addArrayUnchecked(CAT);
1268     }
1269     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1270       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1271         Designator.addComplexUnchecked(EltTy, Imag);
1272     }
1273     void clearIsNullPointer() {
1274       IsNullPtr = false;
1275     }
1276     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1277                               CharUnits ElementSize) {
1278       // Compute the new offset in the appropriate width.
1279       Offset += Index * ElementSize;
1280       if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1281         Designator.adjustIndex(Info, E, Index);
1282       if (Index)
1283         clearIsNullPointer();
1284     }
1285     void adjustOffset(CharUnits N) {
1286       Offset += N;
1287       if (N.getQuantity())
1288         clearIsNullPointer();
1289     }
1290   };
1291
1292   struct MemberPtr {
1293     MemberPtr() {}
1294     explicit MemberPtr(const ValueDecl *Decl) :
1295       DeclAndIsDerivedMember(Decl, false), Path() {}
1296
1297     /// The member or (direct or indirect) field referred to by this member
1298     /// pointer, or 0 if this is a null member pointer.
1299     const ValueDecl *getDecl() const {
1300       return DeclAndIsDerivedMember.getPointer();
1301     }
1302     /// Is this actually a member of some type derived from the relevant class?
1303     bool isDerivedMember() const {
1304       return DeclAndIsDerivedMember.getInt();
1305     }
1306     /// Get the class which the declaration actually lives in.
1307     const CXXRecordDecl *getContainingRecord() const {
1308       return cast<CXXRecordDecl>(
1309           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1310     }
1311
1312     void moveInto(APValue &V) const {
1313       V = APValue(getDecl(), isDerivedMember(), Path);
1314     }
1315     void setFrom(const APValue &V) {
1316       assert(V.isMemberPointer());
1317       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1318       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1319       Path.clear();
1320       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1321       Path.insert(Path.end(), P.begin(), P.end());
1322     }
1323
1324     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1325     /// whether the member is a member of some class derived from the class type
1326     /// of the member pointer.
1327     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1328     /// Path - The path of base/derived classes from the member declaration's
1329     /// class (exclusive) to the class type of the member pointer (inclusive).
1330     SmallVector<const CXXRecordDecl*, 4> Path;
1331
1332     /// Perform a cast towards the class of the Decl (either up or down the
1333     /// hierarchy).
1334     bool castBack(const CXXRecordDecl *Class) {
1335       assert(!Path.empty());
1336       const CXXRecordDecl *Expected;
1337       if (Path.size() >= 2)
1338         Expected = Path[Path.size() - 2];
1339       else
1340         Expected = getContainingRecord();
1341       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1342         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1343         // if B does not contain the original member and is not a base or
1344         // derived class of the class containing the original member, the result
1345         // of the cast is undefined.
1346         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1347         // (D::*). We consider that to be a language defect.
1348         return false;
1349       }
1350       Path.pop_back();
1351       return true;
1352     }
1353     /// Perform a base-to-derived member pointer cast.
1354     bool castToDerived(const CXXRecordDecl *Derived) {
1355       if (!getDecl())
1356         return true;
1357       if (!isDerivedMember()) {
1358         Path.push_back(Derived);
1359         return true;
1360       }
1361       if (!castBack(Derived))
1362         return false;
1363       if (Path.empty())
1364         DeclAndIsDerivedMember.setInt(false);
1365       return true;
1366     }
1367     /// Perform a derived-to-base member pointer cast.
1368     bool castToBase(const CXXRecordDecl *Base) {
1369       if (!getDecl())
1370         return true;
1371       if (Path.empty())
1372         DeclAndIsDerivedMember.setInt(true);
1373       if (isDerivedMember()) {
1374         Path.push_back(Base);
1375         return true;
1376       }
1377       return castBack(Base);
1378     }
1379   };
1380
1381   /// Compare two member pointers, which are assumed to be of the same type.
1382   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1383     if (!LHS.getDecl() || !RHS.getDecl())
1384       return !LHS.getDecl() && !RHS.getDecl();
1385     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1386       return false;
1387     return LHS.Path == RHS.Path;
1388   }
1389 }
1390
1391 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1392 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1393                             const LValue &This, const Expr *E,
1394                             bool AllowNonLiteralTypes = false);
1395 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1396                            bool InvalidBaseOK = false);
1397 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1398                             bool InvalidBaseOK = false);
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   bool InvalidBaseOK;
4807   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4808   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4809
4810   bool Success(APValue::LValueBase B) {
4811     Result.set(B);
4812     return true;
4813   }
4814
4815   bool evaluatePointer(const Expr *E, LValue &Result) {
4816     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4817   }
4818
4819 public:
4820   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4821       : ExprEvaluatorBaseTy(Info), Result(Result),
4822         InvalidBaseOK(InvalidBaseOK) {}
4823
4824   bool Success(const APValue &V, const Expr *E) {
4825     Result.setFrom(this->Info.Ctx, V);
4826     return true;
4827   }
4828
4829   bool VisitMemberExpr(const MemberExpr *E) {
4830     // Handle non-static data members.
4831     QualType BaseTy;
4832     bool EvalOK;
4833     if (E->isArrow()) {
4834       EvalOK = evaluatePointer(E->getBase(), Result);
4835       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4836     } else if (E->getBase()->isRValue()) {
4837       assert(E->getBase()->getType()->isRecordType());
4838       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4839       BaseTy = E->getBase()->getType();
4840     } else {
4841       EvalOK = this->Visit(E->getBase());
4842       BaseTy = E->getBase()->getType();
4843     }
4844     if (!EvalOK) {
4845       if (!InvalidBaseOK)
4846         return false;
4847       Result.setInvalid(E);
4848       return true;
4849     }
4850
4851     const ValueDecl *MD = E->getMemberDecl();
4852     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4853       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4854              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4855       (void)BaseTy;
4856       if (!HandleLValueMember(this->Info, E, Result, FD))
4857         return false;
4858     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4859       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4860         return false;
4861     } else
4862       return this->Error(E);
4863
4864     if (MD->getType()->isReferenceType()) {
4865       APValue RefValue;
4866       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4867                                           RefValue))
4868         return false;
4869       return Success(RefValue, E);
4870     }
4871     return true;
4872   }
4873
4874   bool VisitBinaryOperator(const BinaryOperator *E) {
4875     switch (E->getOpcode()) {
4876     default:
4877       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4878
4879     case BO_PtrMemD:
4880     case BO_PtrMemI:
4881       return HandleMemberPointerAccess(this->Info, E, Result);
4882     }
4883   }
4884
4885   bool VisitCastExpr(const CastExpr *E) {
4886     switch (E->getCastKind()) {
4887     default:
4888       return ExprEvaluatorBaseTy::VisitCastExpr(E);
4889
4890     case CK_DerivedToBase:
4891     case CK_UncheckedDerivedToBase:
4892       if (!this->Visit(E->getSubExpr()))
4893         return false;
4894
4895       // Now figure out the necessary offset to add to the base LV to get from
4896       // the derived class to the base class.
4897       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4898                                   Result);
4899     }
4900   }
4901 };
4902 }
4903
4904 //===----------------------------------------------------------------------===//
4905 // LValue Evaluation
4906 //
4907 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4908 // function designators (in C), decl references to void objects (in C), and
4909 // temporaries (if building with -Wno-address-of-temporary).
4910 //
4911 // LValue evaluation produces values comprising a base expression of one of the
4912 // following types:
4913 // - Declarations
4914 //  * VarDecl
4915 //  * FunctionDecl
4916 // - Literals
4917 //  * CompoundLiteralExpr in C (and in global scope in C++)
4918 //  * StringLiteral
4919 //  * CXXTypeidExpr
4920 //  * PredefinedExpr
4921 //  * ObjCStringLiteralExpr
4922 //  * ObjCEncodeExpr
4923 //  * AddrLabelExpr
4924 //  * BlockExpr
4925 //  * CallExpr for a MakeStringConstant builtin
4926 // - Locals and temporaries
4927 //  * MaterializeTemporaryExpr
4928 //  * Any Expr, with a CallIndex indicating the function in which the temporary
4929 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
4930 //    from the AST (FIXME).
4931 //  * A MaterializeTemporaryExpr that has static storage duration, with no
4932 //    CallIndex, for a lifetime-extended temporary.
4933 // plus an offset in bytes.
4934 //===----------------------------------------------------------------------===//
4935 namespace {
4936 class LValueExprEvaluator
4937   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4938 public:
4939   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4940     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
4941
4942   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4943   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4944
4945   bool VisitDeclRefExpr(const DeclRefExpr *E);
4946   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4947   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4948   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4949   bool VisitMemberExpr(const MemberExpr *E);
4950   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4951   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4952   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4953   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4954   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4955   bool VisitUnaryDeref(const UnaryOperator *E);
4956   bool VisitUnaryReal(const UnaryOperator *E);
4957   bool VisitUnaryImag(const UnaryOperator *E);
4958   bool VisitUnaryPreInc(const UnaryOperator *UO) {
4959     return VisitUnaryPreIncDec(UO);
4960   }
4961   bool VisitUnaryPreDec(const UnaryOperator *UO) {
4962     return VisitUnaryPreIncDec(UO);
4963   }
4964   bool VisitBinAssign(const BinaryOperator *BO);
4965   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4966
4967   bool VisitCastExpr(const CastExpr *E) {
4968     switch (E->getCastKind()) {
4969     default:
4970       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4971
4972     case CK_LValueBitCast:
4973       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4974       if (!Visit(E->getSubExpr()))
4975         return false;
4976       Result.Designator.setInvalid();
4977       return true;
4978
4979     case CK_BaseToDerived:
4980       if (!Visit(E->getSubExpr()))
4981         return false;
4982       return HandleBaseToDerivedCast(Info, E, Result);
4983     }
4984   }
4985 };
4986 } // end anonymous namespace
4987
4988 /// Evaluate an expression as an lvalue. This can be legitimately called on
4989 /// expressions which are not glvalues, in three cases:
4990 ///  * function designators in C, and
4991 ///  * "extern void" objects
4992 ///  * @selector() expressions in Objective-C
4993 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
4994                            bool InvalidBaseOK) {
4995   assert(E->isGLValue() || E->getType()->isFunctionType() ||
4996          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4997   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
4998 }
4999
5000 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5001   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5002     return Success(FD);
5003   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5004     return VisitVarDecl(E, VD);
5005   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5006     return Visit(BD->getBinding());
5007   return Error(E);
5008 }
5009
5010
5011 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5012   CallStackFrame *Frame = nullptr;
5013   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5014     // Only if a local variable was declared in the function currently being
5015     // evaluated, do we expect to be able to find its value in the current
5016     // frame. (Otherwise it was likely declared in an enclosing context and
5017     // could either have a valid evaluatable value (for e.g. a constexpr
5018     // variable) or be ill-formed (and trigger an appropriate evaluation
5019     // diagnostic)).
5020     if (Info.CurrentCall->Callee &&
5021         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5022       Frame = Info.CurrentCall;
5023     }
5024   }
5025
5026   if (!VD->getType()->isReferenceType()) {
5027     if (Frame) {
5028       Result.set(VD, Frame->Index);
5029       return true;
5030     }
5031     return Success(VD);
5032   }
5033
5034   APValue *V;
5035   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5036     return false;
5037   if (V->isUninit()) {
5038     if (!Info.checkingPotentialConstantExpression())
5039       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5040     return false;
5041   }
5042   return Success(*V, E);
5043 }
5044
5045 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5046     const MaterializeTemporaryExpr *E) {
5047   // Walk through the expression to find the materialized temporary itself.
5048   SmallVector<const Expr *, 2> CommaLHSs;
5049   SmallVector<SubobjectAdjustment, 2> Adjustments;
5050   const Expr *Inner = E->GetTemporaryExpr()->
5051       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5052
5053   // If we passed any comma operators, evaluate their LHSs.
5054   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5055     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5056       return false;
5057
5058   // A materialized temporary with static storage duration can appear within the
5059   // result of a constant expression evaluation, so we need to preserve its
5060   // value for use outside this evaluation.
5061   APValue *Value;
5062   if (E->getStorageDuration() == SD_Static) {
5063     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5064     *Value = APValue();
5065     Result.set(E);
5066   } else {
5067     Value = &Info.CurrentCall->
5068         createTemporary(E, E->getStorageDuration() == SD_Automatic);
5069     Result.set(E, Info.CurrentCall->Index);
5070   }
5071
5072   QualType Type = Inner->getType();
5073
5074   // Materialize the temporary itself.
5075   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5076       (E->getStorageDuration() == SD_Static &&
5077        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5078     *Value = APValue();
5079     return false;
5080   }
5081
5082   // Adjust our lvalue to refer to the desired subobject.
5083   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5084     --I;
5085     switch (Adjustments[I].Kind) {
5086     case SubobjectAdjustment::DerivedToBaseAdjustment:
5087       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5088                                 Type, Result))
5089         return false;
5090       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5091       break;
5092
5093     case SubobjectAdjustment::FieldAdjustment:
5094       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5095         return false;
5096       Type = Adjustments[I].Field->getType();
5097       break;
5098
5099     case SubobjectAdjustment::MemberPointerAdjustment:
5100       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5101                                      Adjustments[I].Ptr.RHS))
5102         return false;
5103       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5104       break;
5105     }
5106   }
5107
5108   return true;
5109 }
5110
5111 bool
5112 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5113   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5114          "lvalue compound literal in c++?");
5115   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5116   // only see this when folding in C, so there's no standard to follow here.
5117   return Success(E);
5118 }
5119
5120 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5121   if (!E->isPotentiallyEvaluated())
5122     return Success(E);
5123
5124   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5125     << E->getExprOperand()->getType()
5126     << E->getExprOperand()->getSourceRange();
5127   return false;
5128 }
5129
5130 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5131   return Success(E);
5132 }
5133
5134 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5135   // Handle static data members.
5136   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5137     VisitIgnoredBaseExpression(E->getBase());
5138     return VisitVarDecl(E, VD);
5139   }
5140
5141   // Handle static member functions.
5142   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5143     if (MD->isStatic()) {
5144       VisitIgnoredBaseExpression(E->getBase());
5145       return Success(MD);
5146     }
5147   }
5148
5149   // Handle non-static data members.
5150   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5151 }
5152
5153 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5154   // FIXME: Deal with vectors as array subscript bases.
5155   if (E->getBase()->getType()->isVectorType())
5156     return Error(E);
5157
5158   if (!evaluatePointer(E->getBase(), Result))
5159     return false;
5160
5161   APSInt Index;
5162   if (!EvaluateInteger(E->getIdx(), Index, Info))
5163     return false;
5164
5165   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5166                                      getExtValue(Index));
5167 }
5168
5169 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5170   return evaluatePointer(E->getSubExpr(), Result);
5171 }
5172
5173 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5174   if (!Visit(E->getSubExpr()))
5175     return false;
5176   // __real is a no-op on scalar lvalues.
5177   if (E->getSubExpr()->getType()->isAnyComplexType())
5178     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5179   return true;
5180 }
5181
5182 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5183   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5184          "lvalue __imag__ on scalar?");
5185   if (!Visit(E->getSubExpr()))
5186     return false;
5187   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5188   return true;
5189 }
5190
5191 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5192   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5193     return Error(UO);
5194
5195   if (!this->Visit(UO->getSubExpr()))
5196     return false;
5197
5198   return handleIncDec(
5199       this->Info, UO, Result, UO->getSubExpr()->getType(),
5200       UO->isIncrementOp(), nullptr);
5201 }
5202
5203 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5204     const CompoundAssignOperator *CAO) {
5205   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5206     return Error(CAO);
5207
5208   APValue RHS;
5209
5210   // The overall lvalue result is the result of evaluating the LHS.
5211   if (!this->Visit(CAO->getLHS())) {
5212     if (Info.noteFailure())
5213       Evaluate(RHS, this->Info, CAO->getRHS());
5214     return false;
5215   }
5216
5217   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5218     return false;
5219
5220   return handleCompoundAssignment(
5221       this->Info, CAO,
5222       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5223       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5224 }
5225
5226 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5227   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5228     return Error(E);
5229
5230   APValue NewVal;
5231
5232   if (!this->Visit(E->getLHS())) {
5233     if (Info.noteFailure())
5234       Evaluate(NewVal, this->Info, E->getRHS());
5235     return false;
5236   }
5237
5238   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5239     return false;
5240
5241   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5242                           NewVal);
5243 }
5244
5245 //===----------------------------------------------------------------------===//
5246 // Pointer Evaluation
5247 //===----------------------------------------------------------------------===//
5248
5249 /// \brief Attempts to compute the number of bytes available at the pointer
5250 /// returned by a function with the alloc_size attribute. Returns true if we
5251 /// were successful. Places an unsigned number into `Result`.
5252 ///
5253 /// This expects the given CallExpr to be a call to a function with an
5254 /// alloc_size attribute.
5255 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5256                                             const CallExpr *Call,
5257                                             llvm::APInt &Result) {
5258   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5259
5260   // alloc_size args are 1-indexed, 0 means not present.
5261   assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5262   unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5263   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5264   if (Call->getNumArgs() <= SizeArgNo)
5265     return false;
5266
5267   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5268     if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5269       return false;
5270     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5271       return false;
5272     Into = Into.zextOrSelf(BitsInSizeT);
5273     return true;
5274   };
5275
5276   APSInt SizeOfElem;
5277   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5278     return false;
5279
5280   if (!AllocSize->getNumElemsParam()) {
5281     Result = std::move(SizeOfElem);
5282     return true;
5283   }
5284
5285   APSInt NumberOfElems;
5286   // Argument numbers start at 1
5287   unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5288   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5289     return false;
5290
5291   bool Overflow;
5292   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5293   if (Overflow)
5294     return false;
5295
5296   Result = std::move(BytesAvailable);
5297   return true;
5298 }
5299
5300 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5301 /// function.
5302 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5303                                             const LValue &LVal,
5304                                             llvm::APInt &Result) {
5305   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5306          "Can't get the size of a non alloc_size function");
5307   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5308   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5309   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5310 }
5311
5312 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5313 /// a function with the alloc_size attribute. If it was possible to do so, this
5314 /// function will return true, make Result's Base point to said function call,
5315 /// and mark Result's Base as invalid.
5316 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5317                                       LValue &Result) {
5318   if (Base.isNull())
5319     return false;
5320
5321   // Because we do no form of static analysis, we only support const variables.
5322   //
5323   // Additionally, we can't support parameters, nor can we support static
5324   // variables (in the latter case, use-before-assign isn't UB; in the former,
5325   // we have no clue what they'll be assigned to).
5326   const auto *VD =
5327       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5328   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5329     return false;
5330
5331   const Expr *Init = VD->getAnyInitializer();
5332   if (!Init)
5333     return false;
5334
5335   const Expr *E = Init->IgnoreParens();
5336   if (!tryUnwrapAllocSizeCall(E))
5337     return false;
5338
5339   // Store E instead of E unwrapped so that the type of the LValue's base is
5340   // what the user wanted.
5341   Result.setInvalid(E);
5342
5343   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5344   Result.addUnsizedArray(Info, Pointee);
5345   return true;
5346 }
5347
5348 namespace {
5349 class PointerExprEvaluator
5350   : public ExprEvaluatorBase<PointerExprEvaluator> {
5351   LValue &Result;
5352   bool InvalidBaseOK;
5353
5354   bool Success(const Expr *E) {
5355     Result.set(E);
5356     return true;
5357   }
5358
5359   bool evaluateLValue(const Expr *E, LValue &Result) {
5360     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5361   }
5362
5363   bool evaluatePointer(const Expr *E, LValue &Result) {
5364     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5365   }
5366
5367   bool visitNonBuiltinCallExpr(const CallExpr *E);
5368 public:
5369
5370   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5371       : ExprEvaluatorBaseTy(info), Result(Result),
5372         InvalidBaseOK(InvalidBaseOK) {}
5373
5374   bool Success(const APValue &V, const Expr *E) {
5375     Result.setFrom(Info.Ctx, V);
5376     return true;
5377   }
5378   bool ZeroInitialization(const Expr *E) {
5379     auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5380     Result.set((Expr*)nullptr, 0, false, true, Offset);
5381     return true;
5382   }
5383
5384   bool VisitBinaryOperator(const BinaryOperator *E);
5385   bool VisitCastExpr(const CastExpr* E);
5386   bool VisitUnaryAddrOf(const UnaryOperator *E);
5387   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5388       { return Success(E); }
5389   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5390       { return Success(E); }
5391   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5392       { return Success(E); }
5393   bool VisitCallExpr(const CallExpr *E);
5394   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5395   bool VisitBlockExpr(const BlockExpr *E) {
5396     if (!E->getBlockDecl()->hasCaptures())
5397       return Success(E);
5398     return Error(E);
5399   }
5400   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5401     // Can't look at 'this' when checking a potential constant expression.
5402     if (Info.checkingPotentialConstantExpression())
5403       return false;
5404     if (!Info.CurrentCall->This) {
5405       if (Info.getLangOpts().CPlusPlus11)
5406         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5407       else
5408         Info.FFDiag(E);
5409       return false;
5410     }
5411     Result = *Info.CurrentCall->This;
5412     return true;
5413   }
5414
5415   // FIXME: Missing: @protocol, @selector
5416 };
5417 } // end anonymous namespace
5418
5419 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5420                             bool InvalidBaseOK) {
5421   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5422   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5423 }
5424
5425 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5426   if (E->getOpcode() != BO_Add &&
5427       E->getOpcode() != BO_Sub)
5428     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5429
5430   const Expr *PExp = E->getLHS();
5431   const Expr *IExp = E->getRHS();
5432   if (IExp->getType()->isPointerType())
5433     std::swap(PExp, IExp);
5434
5435   bool EvalPtrOK = evaluatePointer(PExp, Result);
5436   if (!EvalPtrOK && !Info.noteFailure())
5437     return false;
5438
5439   llvm::APSInt Offset;
5440   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5441     return false;
5442
5443   int64_t AdditionalOffset = getExtValue(Offset);
5444   if (E->getOpcode() == BO_Sub)
5445     AdditionalOffset = -AdditionalOffset;
5446
5447   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5448   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5449                                      AdditionalOffset);
5450 }
5451
5452 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5453   return evaluateLValue(E->getSubExpr(), Result);
5454 }
5455
5456 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5457   const Expr* SubExpr = E->getSubExpr();
5458
5459   switch (E->getCastKind()) {
5460   default:
5461     break;
5462
5463   case CK_BitCast:
5464   case CK_CPointerToObjCPointerCast:
5465   case CK_BlockPointerToObjCPointerCast:
5466   case CK_AnyPointerToBlockPointerCast:
5467   case CK_AddressSpaceConversion:
5468     if (!Visit(SubExpr))
5469       return false;
5470     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5471     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5472     // also static_casts, but we disallow them as a resolution to DR1312.
5473     if (!E->getType()->isVoidPointerType()) {
5474       Result.Designator.setInvalid();
5475       if (SubExpr->getType()->isVoidPointerType())
5476         CCEDiag(E, diag::note_constexpr_invalid_cast)
5477           << 3 << SubExpr->getType();
5478       else
5479         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5480     }
5481     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5482       ZeroInitialization(E);
5483     return true;
5484
5485   case CK_DerivedToBase:
5486   case CK_UncheckedDerivedToBase:
5487     if (!evaluatePointer(E->getSubExpr(), Result))
5488       return false;
5489     if (!Result.Base && Result.Offset.isZero())
5490       return true;
5491
5492     // Now figure out the necessary offset to add to the base LV to get from
5493     // the derived class to the base class.
5494     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5495                                   castAs<PointerType>()->getPointeeType(),
5496                                 Result);
5497
5498   case CK_BaseToDerived:
5499     if (!Visit(E->getSubExpr()))
5500       return false;
5501     if (!Result.Base && Result.Offset.isZero())
5502       return true;
5503     return HandleBaseToDerivedCast(Info, E, Result);
5504
5505   case CK_NullToPointer:
5506     VisitIgnoredValue(E->getSubExpr());
5507     return ZeroInitialization(E);
5508
5509   case CK_IntegralToPointer: {
5510     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5511
5512     APValue Value;
5513     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5514       break;
5515
5516     if (Value.isInt()) {
5517       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5518       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5519       Result.Base = (Expr*)nullptr;
5520       Result.InvalidBase = false;
5521       Result.Offset = CharUnits::fromQuantity(N);
5522       Result.CallIndex = 0;
5523       Result.Designator.setInvalid();
5524       Result.IsNullPtr = false;
5525       return true;
5526     } else {
5527       // Cast is of an lvalue, no need to change value.
5528       Result.setFrom(Info.Ctx, Value);
5529       return true;
5530     }
5531   }
5532   case CK_ArrayToPointerDecay:
5533     if (SubExpr->isGLValue()) {
5534       if (!evaluateLValue(SubExpr, Result))
5535         return false;
5536     } else {
5537       Result.set(SubExpr, Info.CurrentCall->Index);
5538       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5539                            Info, Result, SubExpr))
5540         return false;
5541     }
5542     // The result is a pointer to the first element of the array.
5543     if (const ConstantArrayType *CAT
5544           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5545       Result.addArray(Info, E, CAT);
5546     else
5547       Result.Designator.setInvalid();
5548     return true;
5549
5550   case CK_FunctionToPointerDecay:
5551     return evaluateLValue(SubExpr, Result);
5552
5553   case CK_LValueToRValue: {
5554     LValue LVal;
5555     if (!evaluateLValue(E->getSubExpr(), LVal))
5556       return false;
5557
5558     APValue RVal;
5559     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5560     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5561                                         LVal, RVal))
5562       return InvalidBaseOK &&
5563              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5564     return Success(RVal, E);
5565   }
5566   }
5567
5568   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5569 }
5570
5571 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5572   // C++ [expr.alignof]p3:
5573   //     When alignof is applied to a reference type, the result is the
5574   //     alignment of the referenced type.
5575   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5576     T = Ref->getPointeeType();
5577
5578   // __alignof is defined to return the preferred alignment.
5579   return Info.Ctx.toCharUnitsFromBits(
5580     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5581 }
5582
5583 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5584   E = E->IgnoreParens();
5585
5586   // The kinds of expressions that we have special-case logic here for
5587   // should be kept up to date with the special checks for those
5588   // expressions in Sema.
5589
5590   // alignof decl is always accepted, even if it doesn't make sense: we default
5591   // to 1 in those cases.
5592   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5593     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5594                                  /*RefAsPointee*/true);
5595
5596   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5597     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5598                                  /*RefAsPointee*/true);
5599
5600   return GetAlignOfType(Info, E->getType());
5601 }
5602
5603 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5604 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5605   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5606     return true;
5607
5608   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5609     return false;
5610
5611   Result.setInvalid(E);
5612   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5613   Result.addUnsizedArray(Info, PointeeTy);
5614   return true;
5615 }
5616
5617 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5618   if (IsStringLiteralCall(E))
5619     return Success(E);
5620
5621   if (unsigned BuiltinOp = E->getBuiltinCallee())
5622     return VisitBuiltinCallExpr(E, BuiltinOp);
5623
5624   return visitNonBuiltinCallExpr(E);
5625 }
5626
5627 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5628                                                 unsigned BuiltinOp) {
5629   switch (BuiltinOp) {
5630   case Builtin::BI__builtin_addressof:
5631     return evaluateLValue(E->getArg(0), Result);
5632   case Builtin::BI__builtin_assume_aligned: {
5633     // We need to be very careful here because: if the pointer does not have the
5634     // asserted alignment, then the behavior is undefined, and undefined
5635     // behavior is non-constant.
5636     if (!evaluatePointer(E->getArg(0), Result))
5637       return false;
5638
5639     LValue OffsetResult(Result);
5640     APSInt Alignment;
5641     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5642       return false;
5643     CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5644
5645     if (E->getNumArgs() > 2) {
5646       APSInt Offset;
5647       if (!EvaluateInteger(E->getArg(2), Offset, Info))
5648         return false;
5649
5650       int64_t AdditionalOffset = -getExtValue(Offset);
5651       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5652     }
5653
5654     // If there is a base object, then it must have the correct alignment.
5655     if (OffsetResult.Base) {
5656       CharUnits BaseAlignment;
5657       if (const ValueDecl *VD =
5658           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5659         BaseAlignment = Info.Ctx.getDeclAlign(VD);
5660       } else {
5661         BaseAlignment =
5662           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5663       }
5664
5665       if (BaseAlignment < Align) {
5666         Result.Designator.setInvalid();
5667         // FIXME: Quantities here cast to integers because the plural modifier
5668         // does not work on APSInts yet.
5669         CCEDiag(E->getArg(0),
5670                 diag::note_constexpr_baa_insufficient_alignment) << 0
5671           << (int) BaseAlignment.getQuantity()
5672           << (unsigned) getExtValue(Alignment);
5673         return false;
5674       }
5675     }
5676
5677     // The offset must also have the correct alignment.
5678     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5679       Result.Designator.setInvalid();
5680       APSInt Offset(64, false);
5681       Offset = OffsetResult.Offset.getQuantity();
5682
5683       if (OffsetResult.Base)
5684         CCEDiag(E->getArg(0),
5685                 diag::note_constexpr_baa_insufficient_alignment) << 1
5686           << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5687       else
5688         CCEDiag(E->getArg(0),
5689                 diag::note_constexpr_baa_value_insufficient_alignment)
5690           << Offset << (unsigned) getExtValue(Alignment);
5691
5692       return false;
5693     }
5694
5695     return true;
5696   }
5697
5698   case Builtin::BIstrchr:
5699   case Builtin::BIwcschr:
5700   case Builtin::BImemchr:
5701   case Builtin::BIwmemchr:
5702     if (Info.getLangOpts().CPlusPlus11)
5703       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5704         << /*isConstexpr*/0 << /*isConstructor*/0
5705         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5706     else
5707       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5708     // Fall through.
5709   case Builtin::BI__builtin_strchr:
5710   case Builtin::BI__builtin_wcschr:
5711   case Builtin::BI__builtin_memchr:
5712   case Builtin::BI__builtin_char_memchr:
5713   case Builtin::BI__builtin_wmemchr: {
5714     if (!Visit(E->getArg(0)))
5715       return false;
5716     APSInt Desired;
5717     if (!EvaluateInteger(E->getArg(1), Desired, Info))
5718       return false;
5719     uint64_t MaxLength = uint64_t(-1);
5720     if (BuiltinOp != Builtin::BIstrchr &&
5721         BuiltinOp != Builtin::BIwcschr &&
5722         BuiltinOp != Builtin::BI__builtin_strchr &&
5723         BuiltinOp != Builtin::BI__builtin_wcschr) {
5724       APSInt N;
5725       if (!EvaluateInteger(E->getArg(2), N, Info))
5726         return false;
5727       MaxLength = N.getExtValue();
5728     }
5729
5730     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5731
5732     // Figure out what value we're actually looking for (after converting to
5733     // the corresponding unsigned type if necessary).
5734     uint64_t DesiredVal;
5735     bool StopAtNull = false;
5736     switch (BuiltinOp) {
5737     case Builtin::BIstrchr:
5738     case Builtin::BI__builtin_strchr:
5739       // strchr compares directly to the passed integer, and therefore
5740       // always fails if given an int that is not a char.
5741       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5742                                                   E->getArg(1)->getType(),
5743                                                   Desired),
5744                                Desired))
5745         return ZeroInitialization(E);
5746       StopAtNull = true;
5747       // Fall through.
5748     case Builtin::BImemchr:
5749     case Builtin::BI__builtin_memchr:
5750     case Builtin::BI__builtin_char_memchr:
5751       // memchr compares by converting both sides to unsigned char. That's also
5752       // correct for strchr if we get this far (to cope with plain char being
5753       // unsigned in the strchr case).
5754       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5755       break;
5756
5757     case Builtin::BIwcschr:
5758     case Builtin::BI__builtin_wcschr:
5759       StopAtNull = true;
5760       // Fall through.
5761     case Builtin::BIwmemchr:
5762     case Builtin::BI__builtin_wmemchr:
5763       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5764       DesiredVal = Desired.getZExtValue();
5765       break;
5766     }
5767
5768     for (; MaxLength; --MaxLength) {
5769       APValue Char;
5770       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5771           !Char.isInt())
5772         return false;
5773       if (Char.getInt().getZExtValue() == DesiredVal)
5774         return true;
5775       if (StopAtNull && !Char.getInt())
5776         break;
5777       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5778         return false;
5779     }
5780     // Not found: return nullptr.
5781     return ZeroInitialization(E);
5782   }
5783
5784   default:
5785     return visitNonBuiltinCallExpr(E);
5786   }
5787 }
5788
5789 //===----------------------------------------------------------------------===//
5790 // Member Pointer Evaluation
5791 //===----------------------------------------------------------------------===//
5792
5793 namespace {
5794 class MemberPointerExprEvaluator
5795   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5796   MemberPtr &Result;
5797
5798   bool Success(const ValueDecl *D) {
5799     Result = MemberPtr(D);
5800     return true;
5801   }
5802 public:
5803
5804   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5805     : ExprEvaluatorBaseTy(Info), Result(Result) {}
5806
5807   bool Success(const APValue &V, const Expr *E) {
5808     Result.setFrom(V);
5809     return true;
5810   }
5811   bool ZeroInitialization(const Expr *E) {
5812     return Success((const ValueDecl*)nullptr);
5813   }
5814
5815   bool VisitCastExpr(const CastExpr *E);
5816   bool VisitUnaryAddrOf(const UnaryOperator *E);
5817 };
5818 } // end anonymous namespace
5819
5820 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5821                                   EvalInfo &Info) {
5822   assert(E->isRValue() && E->getType()->isMemberPointerType());
5823   return MemberPointerExprEvaluator(Info, Result).Visit(E);
5824 }
5825
5826 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5827   switch (E->getCastKind()) {
5828   default:
5829     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5830
5831   case CK_NullToMemberPointer:
5832     VisitIgnoredValue(E->getSubExpr());
5833     return ZeroInitialization(E);
5834
5835   case CK_BaseToDerivedMemberPointer: {
5836     if (!Visit(E->getSubExpr()))
5837       return false;
5838     if (E->path_empty())
5839       return true;
5840     // Base-to-derived member pointer casts store the path in derived-to-base
5841     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5842     // the wrong end of the derived->base arc, so stagger the path by one class.
5843     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5844     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5845          PathI != PathE; ++PathI) {
5846       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5847       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5848       if (!Result.castToDerived(Derived))
5849         return Error(E);
5850     }
5851     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5852     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5853       return Error(E);
5854     return true;
5855   }
5856
5857   case CK_DerivedToBaseMemberPointer:
5858     if (!Visit(E->getSubExpr()))
5859       return false;
5860     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5861          PathE = E->path_end(); PathI != PathE; ++PathI) {
5862       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5863       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5864       if (!Result.castToBase(Base))
5865         return Error(E);
5866     }
5867     return true;
5868   }
5869 }
5870
5871 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5872   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5873   // member can be formed.
5874   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5875 }
5876
5877 //===----------------------------------------------------------------------===//
5878 // Record Evaluation
5879 //===----------------------------------------------------------------------===//
5880
5881 namespace {
5882   class RecordExprEvaluator
5883   : public ExprEvaluatorBase<RecordExprEvaluator> {
5884     const LValue &This;
5885     APValue &Result;
5886   public:
5887
5888     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5889       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5890
5891     bool Success(const APValue &V, const Expr *E) {
5892       Result = V;
5893       return true;
5894     }
5895     bool ZeroInitialization(const Expr *E) {
5896       return ZeroInitialization(E, E->getType());
5897     }
5898     bool ZeroInitialization(const Expr *E, QualType T);
5899
5900     bool VisitCallExpr(const CallExpr *E) {
5901       return handleCallExpr(E, Result, &This);
5902     }
5903     bool VisitCastExpr(const CastExpr *E);
5904     bool VisitInitListExpr(const InitListExpr *E);
5905     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5906       return VisitCXXConstructExpr(E, E->getType());
5907     }
5908     bool VisitLambdaExpr(const LambdaExpr *E);
5909     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5910     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5911     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5912   };
5913 }
5914
5915 /// Perform zero-initialization on an object of non-union class type.
5916 /// C++11 [dcl.init]p5:
5917 ///  To zero-initialize an object or reference of type T means:
5918 ///    [...]
5919 ///    -- if T is a (possibly cv-qualified) non-union class type,
5920 ///       each non-static data member and each base-class subobject is
5921 ///       zero-initialized
5922 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5923                                           const RecordDecl *RD,
5924                                           const LValue &This, APValue &Result) {
5925   assert(!RD->isUnion() && "Expected non-union class type");
5926   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5927   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5928                    std::distance(RD->field_begin(), RD->field_end()));
5929
5930   if (RD->isInvalidDecl()) return false;
5931   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5932
5933   if (CD) {
5934     unsigned Index = 0;
5935     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5936            End = CD->bases_end(); I != End; ++I, ++Index) {
5937       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5938       LValue Subobject = This;
5939       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5940         return false;
5941       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5942                                          Result.getStructBase(Index)))
5943         return false;
5944     }
5945   }
5946
5947   for (const auto *I : RD->fields()) {
5948     // -- if T is a reference type, no initialization is performed.
5949     if (I->getType()->isReferenceType())
5950       continue;
5951
5952     LValue Subobject = This;
5953     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5954       return false;
5955
5956     ImplicitValueInitExpr VIE(I->getType());
5957     if (!EvaluateInPlace(
5958           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5959       return false;
5960   }
5961
5962   return true;
5963 }
5964
5965 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5966   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5967   if (RD->isInvalidDecl()) return false;
5968   if (RD->isUnion()) {
5969     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5970     // object's first non-static named data member is zero-initialized
5971     RecordDecl::field_iterator I = RD->field_begin();
5972     if (I == RD->field_end()) {
5973       Result = APValue((const FieldDecl*)nullptr);
5974       return true;
5975     }
5976
5977     LValue Subobject = This;
5978     if (!HandleLValueMember(Info, E, Subobject, *I))
5979       return false;
5980     Result = APValue(*I);
5981     ImplicitValueInitExpr VIE(I->getType());
5982     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5983   }
5984
5985   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5986     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5987     return false;
5988   }
5989
5990   return HandleClassZeroInitialization(Info, E, RD, This, Result);
5991 }
5992
5993 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5994   switch (E->getCastKind()) {
5995   default:
5996     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5997
5998   case CK_ConstructorConversion:
5999     return Visit(E->getSubExpr());
6000
6001   case CK_DerivedToBase:
6002   case CK_UncheckedDerivedToBase: {
6003     APValue DerivedObject;
6004     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6005       return false;
6006     if (!DerivedObject.isStruct())
6007       return Error(E->getSubExpr());
6008
6009     // Derived-to-base rvalue conversion: just slice off the derived part.
6010     APValue *Value = &DerivedObject;
6011     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6012     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6013          PathE = E->path_end(); PathI != PathE; ++PathI) {
6014       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6015       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6016       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6017       RD = Base;
6018     }
6019     Result = *Value;
6020     return true;
6021   }
6022   }
6023 }
6024
6025 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6026   if (E->isTransparent())
6027     return Visit(E->getInit(0));
6028
6029   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6030   if (RD->isInvalidDecl()) return false;
6031   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6032
6033   if (RD->isUnion()) {
6034     const FieldDecl *Field = E->getInitializedFieldInUnion();
6035     Result = APValue(Field);
6036     if (!Field)
6037       return true;
6038
6039     // If the initializer list for a union does not contain any elements, the
6040     // first element of the union is value-initialized.
6041     // FIXME: The element should be initialized from an initializer list.
6042     //        Is this difference ever observable for initializer lists which
6043     //        we don't build?
6044     ImplicitValueInitExpr VIE(Field->getType());
6045     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6046
6047     LValue Subobject = This;
6048     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6049       return false;
6050
6051     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6052     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6053                                   isa<CXXDefaultInitExpr>(InitExpr));
6054
6055     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6056   }
6057
6058   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6059   if (Result.isUninit())
6060     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6061                      std::distance(RD->field_begin(), RD->field_end()));
6062   unsigned ElementNo = 0;
6063   bool Success = true;
6064
6065   // Initialize base classes.
6066   if (CXXRD) {
6067     for (const auto &Base : CXXRD->bases()) {
6068       assert(ElementNo < E->getNumInits() && "missing init for base class");
6069       const Expr *Init = E->getInit(ElementNo);
6070
6071       LValue Subobject = This;
6072       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6073         return false;
6074
6075       APValue &FieldVal = Result.getStructBase(ElementNo);
6076       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6077         if (!Info.noteFailure())
6078           return false;
6079         Success = false;
6080       }
6081       ++ElementNo;
6082     }
6083   }
6084
6085   // Initialize members.
6086   for (const auto *Field : RD->fields()) {
6087     // Anonymous bit-fields are not considered members of the class for
6088     // purposes of aggregate initialization.
6089     if (Field->isUnnamedBitfield())
6090       continue;
6091
6092     LValue Subobject = This;
6093
6094     bool HaveInit = ElementNo < E->getNumInits();
6095
6096     // FIXME: Diagnostics here should point to the end of the initializer
6097     // list, not the start.
6098     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6099                             Subobject, Field, &Layout))
6100       return false;
6101
6102     // Perform an implicit value-initialization for members beyond the end of
6103     // the initializer list.
6104     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6105     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6106
6107     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6108     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6109                                   isa<CXXDefaultInitExpr>(Init));
6110
6111     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6112     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6113         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6114                                                        FieldVal, Field))) {
6115       if (!Info.noteFailure())
6116         return false;
6117       Success = false;
6118     }
6119   }
6120
6121   return Success;
6122 }
6123
6124 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6125                                                 QualType T) {
6126   // Note that E's type is not necessarily the type of our class here; we might
6127   // be initializing an array element instead.
6128   const CXXConstructorDecl *FD = E->getConstructor();
6129   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6130
6131   bool ZeroInit = E->requiresZeroInitialization();
6132   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6133     // If we've already performed zero-initialization, we're already done.
6134     if (!Result.isUninit())
6135       return true;
6136
6137     // We can get here in two different ways:
6138     //  1) We're performing value-initialization, and should zero-initialize
6139     //     the object, or
6140     //  2) We're performing default-initialization of an object with a trivial
6141     //     constexpr default constructor, in which case we should start the
6142     //     lifetimes of all the base subobjects (there can be no data member
6143     //     subobjects in this case) per [basic.life]p1.
6144     // Either way, ZeroInitialization is appropriate.
6145     return ZeroInitialization(E, T);
6146   }
6147
6148   const FunctionDecl *Definition = nullptr;
6149   auto Body = FD->getBody(Definition);
6150
6151   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6152     return false;
6153
6154   // Avoid materializing a temporary for an elidable copy/move constructor.
6155   if (E->isElidable() && !ZeroInit)
6156     if (const MaterializeTemporaryExpr *ME
6157           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6158       return Visit(ME->GetTemporaryExpr());
6159
6160   if (ZeroInit && !ZeroInitialization(E, T))
6161     return false;
6162
6163   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6164   return HandleConstructorCall(E, This, Args,
6165                                cast<CXXConstructorDecl>(Definition), Info,
6166                                Result);
6167 }
6168
6169 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6170     const CXXInheritedCtorInitExpr *E) {
6171   if (!Info.CurrentCall) {
6172     assert(Info.checkingPotentialConstantExpression());
6173     return false;
6174   }
6175
6176   const CXXConstructorDecl *FD = E->getConstructor();
6177   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6178     return false;
6179
6180   const FunctionDecl *Definition = nullptr;
6181   auto Body = FD->getBody(Definition);
6182
6183   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6184     return false;
6185
6186   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6187                                cast<CXXConstructorDecl>(Definition), Info,
6188                                Result);
6189 }
6190
6191 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6192     const CXXStdInitializerListExpr *E) {
6193   const ConstantArrayType *ArrayType =
6194       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6195
6196   LValue Array;
6197   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6198     return false;
6199
6200   // Get a pointer to the first element of the array.
6201   Array.addArray(Info, E, ArrayType);
6202
6203   // FIXME: Perform the checks on the field types in SemaInit.
6204   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6205   RecordDecl::field_iterator Field = Record->field_begin();
6206   if (Field == Record->field_end())
6207     return Error(E);
6208
6209   // Start pointer.
6210   if (!Field->getType()->isPointerType() ||
6211       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6212                             ArrayType->getElementType()))
6213     return Error(E);
6214
6215   // FIXME: What if the initializer_list type has base classes, etc?
6216   Result = APValue(APValue::UninitStruct(), 0, 2);
6217   Array.moveInto(Result.getStructField(0));
6218
6219   if (++Field == Record->field_end())
6220     return Error(E);
6221
6222   if (Field->getType()->isPointerType() &&
6223       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6224                            ArrayType->getElementType())) {
6225     // End pointer.
6226     if (!HandleLValueArrayAdjustment(Info, E, Array,
6227                                      ArrayType->getElementType(),
6228                                      ArrayType->getSize().getZExtValue()))
6229       return false;
6230     Array.moveInto(Result.getStructField(1));
6231   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6232     // Length.
6233     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6234   else
6235     return Error(E);
6236
6237   if (++Field != Record->field_end())
6238     return Error(E);
6239
6240   return true;
6241 }
6242
6243 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6244   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6245   if (ClosureClass->isInvalidDecl()) return false;
6246
6247   if (Info.checkingPotentialConstantExpression()) return true;
6248   if (E->capture_size()) {
6249     Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6250         << "can not evaluate lambda expressions with captures";
6251     return false;
6252   }
6253   // FIXME: Implement captures.
6254   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6255   return true;
6256 }
6257
6258 static bool EvaluateRecord(const Expr *E, const LValue &This,
6259                            APValue &Result, EvalInfo &Info) {
6260   assert(E->isRValue() && E->getType()->isRecordType() &&
6261          "can't evaluate expression as a record rvalue");
6262   return RecordExprEvaluator(Info, This, Result).Visit(E);
6263 }
6264
6265 //===----------------------------------------------------------------------===//
6266 // Temporary Evaluation
6267 //
6268 // Temporaries are represented in the AST as rvalues, but generally behave like
6269 // lvalues. The full-object of which the temporary is a subobject is implicitly
6270 // materialized so that a reference can bind to it.
6271 //===----------------------------------------------------------------------===//
6272 namespace {
6273 class TemporaryExprEvaluator
6274   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6275 public:
6276   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6277     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6278
6279   /// Visit an expression which constructs the value of this temporary.
6280   bool VisitConstructExpr(const Expr *E) {
6281     Result.set(E, Info.CurrentCall->Index);
6282     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6283                            Info, Result, E);
6284   }
6285
6286   bool VisitCastExpr(const CastExpr *E) {
6287     switch (E->getCastKind()) {
6288     default:
6289       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6290
6291     case CK_ConstructorConversion:
6292       return VisitConstructExpr(E->getSubExpr());
6293     }
6294   }
6295   bool VisitInitListExpr(const InitListExpr *E) {
6296     return VisitConstructExpr(E);
6297   }
6298   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6299     return VisitConstructExpr(E);
6300   }
6301   bool VisitCallExpr(const CallExpr *E) {
6302     return VisitConstructExpr(E);
6303   }
6304   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6305     return VisitConstructExpr(E);
6306   }
6307   bool VisitLambdaExpr(const LambdaExpr *E) {
6308     return VisitConstructExpr(E);
6309   }
6310 };
6311 } // end anonymous namespace
6312
6313 /// Evaluate an expression of record type as a temporary.
6314 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6315   assert(E->isRValue() && E->getType()->isRecordType());
6316   return TemporaryExprEvaluator(Info, Result).Visit(E);
6317 }
6318
6319 //===----------------------------------------------------------------------===//
6320 // Vector Evaluation
6321 //===----------------------------------------------------------------------===//
6322
6323 namespace {
6324   class VectorExprEvaluator
6325   : public ExprEvaluatorBase<VectorExprEvaluator> {
6326     APValue &Result;
6327   public:
6328
6329     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6330       : ExprEvaluatorBaseTy(info), Result(Result) {}
6331
6332     bool Success(ArrayRef<APValue> V, const Expr *E) {
6333       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6334       // FIXME: remove this APValue copy.
6335       Result = APValue(V.data(), V.size());
6336       return true;
6337     }
6338     bool Success(const APValue &V, const Expr *E) {
6339       assert(V.isVector());
6340       Result = V;
6341       return true;
6342     }
6343     bool ZeroInitialization(const Expr *E);
6344
6345     bool VisitUnaryReal(const UnaryOperator *E)
6346       { return Visit(E->getSubExpr()); }
6347     bool VisitCastExpr(const CastExpr* E);
6348     bool VisitInitListExpr(const InitListExpr *E);
6349     bool VisitUnaryImag(const UnaryOperator *E);
6350     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6351     //                 binary comparisons, binary and/or/xor,
6352     //                 shufflevector, ExtVectorElementExpr
6353   };
6354 } // end anonymous namespace
6355
6356 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6357   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6358   return VectorExprEvaluator(Info, Result).Visit(E);
6359 }
6360
6361 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6362   const VectorType *VTy = E->getType()->castAs<VectorType>();
6363   unsigned NElts = VTy->getNumElements();
6364
6365   const Expr *SE = E->getSubExpr();
6366   QualType SETy = SE->getType();
6367
6368   switch (E->getCastKind()) {
6369   case CK_VectorSplat: {
6370     APValue Val = APValue();
6371     if (SETy->isIntegerType()) {
6372       APSInt IntResult;
6373       if (!EvaluateInteger(SE, IntResult, Info))
6374         return false;
6375       Val = APValue(std::move(IntResult));
6376     } else if (SETy->isRealFloatingType()) {
6377       APFloat FloatResult(0.0);
6378       if (!EvaluateFloat(SE, FloatResult, Info))
6379         return false;
6380       Val = APValue(std::move(FloatResult));
6381     } else {
6382       return Error(E);
6383     }
6384
6385     // Splat and create vector APValue.
6386     SmallVector<APValue, 4> Elts(NElts, Val);
6387     return Success(Elts, E);
6388   }
6389   case CK_BitCast: {
6390     // Evaluate the operand into an APInt we can extract from.
6391     llvm::APInt SValInt;
6392     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6393       return false;
6394     // Extract the elements
6395     QualType EltTy = VTy->getElementType();
6396     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6397     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6398     SmallVector<APValue, 4> Elts;
6399     if (EltTy->isRealFloatingType()) {
6400       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6401       unsigned FloatEltSize = EltSize;
6402       if (&Sem == &APFloat::x87DoubleExtended())
6403         FloatEltSize = 80;
6404       for (unsigned i = 0; i < NElts; i++) {
6405         llvm::APInt Elt;
6406         if (BigEndian)
6407           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6408         else
6409           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6410         Elts.push_back(APValue(APFloat(Sem, Elt)));
6411       }
6412     } else if (EltTy->isIntegerType()) {
6413       for (unsigned i = 0; i < NElts; i++) {
6414         llvm::APInt Elt;
6415         if (BigEndian)
6416           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6417         else
6418           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6419         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6420       }
6421     } else {
6422       return Error(E);
6423     }
6424     return Success(Elts, E);
6425   }
6426   default:
6427     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6428   }
6429 }
6430
6431 bool
6432 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6433   const VectorType *VT = E->getType()->castAs<VectorType>();
6434   unsigned NumInits = E->getNumInits();
6435   unsigned NumElements = VT->getNumElements();
6436
6437   QualType EltTy = VT->getElementType();
6438   SmallVector<APValue, 4> Elements;
6439
6440   // The number of initializers can be less than the number of
6441   // vector elements. For OpenCL, this can be due to nested vector
6442   // initialization. For GCC compatibility, missing trailing elements 
6443   // should be initialized with zeroes.
6444   unsigned CountInits = 0, CountElts = 0;
6445   while (CountElts < NumElements) {
6446     // Handle nested vector initialization.
6447     if (CountInits < NumInits 
6448         && E->getInit(CountInits)->getType()->isVectorType()) {
6449       APValue v;
6450       if (!EvaluateVector(E->getInit(CountInits), v, Info))
6451         return Error(E);
6452       unsigned vlen = v.getVectorLength();
6453       for (unsigned j = 0; j < vlen; j++) 
6454         Elements.push_back(v.getVectorElt(j));
6455       CountElts += vlen;
6456     } else if (EltTy->isIntegerType()) {
6457       llvm::APSInt sInt(32);
6458       if (CountInits < NumInits) {
6459         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6460           return false;
6461       } else // trailing integer zero.
6462         sInt = Info.Ctx.MakeIntValue(0, EltTy);
6463       Elements.push_back(APValue(sInt));
6464       CountElts++;
6465     } else {
6466       llvm::APFloat f(0.0);
6467       if (CountInits < NumInits) {
6468         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6469           return false;
6470       } else // trailing float zero.
6471         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6472       Elements.push_back(APValue(f));
6473       CountElts++;
6474     }
6475     CountInits++;
6476   }
6477   return Success(Elements, E);
6478 }
6479
6480 bool
6481 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6482   const VectorType *VT = E->getType()->getAs<VectorType>();
6483   QualType EltTy = VT->getElementType();
6484   APValue ZeroElement;
6485   if (EltTy->isIntegerType())
6486     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6487   else
6488     ZeroElement =
6489         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6490
6491   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6492   return Success(Elements, E);
6493 }
6494
6495 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6496   VisitIgnoredValue(E->getSubExpr());
6497   return ZeroInitialization(E);
6498 }
6499
6500 //===----------------------------------------------------------------------===//
6501 // Array Evaluation
6502 //===----------------------------------------------------------------------===//
6503
6504 namespace {
6505   class ArrayExprEvaluator
6506   : public ExprEvaluatorBase<ArrayExprEvaluator> {
6507     const LValue &This;
6508     APValue &Result;
6509   public:
6510
6511     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6512       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6513
6514     bool Success(const APValue &V, const Expr *E) {
6515       assert((V.isArray() || V.isLValue()) &&
6516              "expected array or string literal");
6517       Result = V;
6518       return true;
6519     }
6520
6521     bool ZeroInitialization(const Expr *E) {
6522       const ConstantArrayType *CAT =
6523           Info.Ctx.getAsConstantArrayType(E->getType());
6524       if (!CAT)
6525         return Error(E);
6526
6527       Result = APValue(APValue::UninitArray(), 0,
6528                        CAT->getSize().getZExtValue());
6529       if (!Result.hasArrayFiller()) return true;
6530
6531       // Zero-initialize all elements.
6532       LValue Subobject = This;
6533       Subobject.addArray(Info, E, CAT);
6534       ImplicitValueInitExpr VIE(CAT->getElementType());
6535       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6536     }
6537
6538     bool VisitCallExpr(const CallExpr *E) {
6539       return handleCallExpr(E, Result, &This);
6540     }
6541     bool VisitInitListExpr(const InitListExpr *E);
6542     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6543     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6544     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6545                                const LValue &Subobject,
6546                                APValue *Value, QualType Type);
6547   };
6548 } // end anonymous namespace
6549
6550 static bool EvaluateArray(const Expr *E, const LValue &This,
6551                           APValue &Result, EvalInfo &Info) {
6552   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6553   return ArrayExprEvaluator(Info, This, Result).Visit(E);
6554 }
6555
6556 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6557   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6558   if (!CAT)
6559     return Error(E);
6560
6561   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6562   // an appropriately-typed string literal enclosed in braces.
6563   if (E->isStringLiteralInit()) {
6564     LValue LV;
6565     if (!EvaluateLValue(E->getInit(0), LV, Info))
6566       return false;
6567     APValue Val;
6568     LV.moveInto(Val);
6569     return Success(Val, E);
6570   }
6571
6572   bool Success = true;
6573
6574   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6575          "zero-initialized array shouldn't have any initialized elts");
6576   APValue Filler;
6577   if (Result.isArray() && Result.hasArrayFiller())
6578     Filler = Result.getArrayFiller();
6579
6580   unsigned NumEltsToInit = E->getNumInits();
6581   unsigned NumElts = CAT->getSize().getZExtValue();
6582   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6583
6584   // If the initializer might depend on the array index, run it for each
6585   // array element. For now, just whitelist non-class value-initialization.
6586   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6587     NumEltsToInit = NumElts;
6588
6589   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6590
6591   // If the array was previously zero-initialized, preserve the
6592   // zero-initialized values.
6593   if (!Filler.isUninit()) {
6594     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6595       Result.getArrayInitializedElt(I) = Filler;
6596     if (Result.hasArrayFiller())
6597       Result.getArrayFiller() = Filler;
6598   }
6599
6600   LValue Subobject = This;
6601   Subobject.addArray(Info, E, CAT);
6602   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6603     const Expr *Init =
6604         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6605     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6606                          Info, Subobject, Init) ||
6607         !HandleLValueArrayAdjustment(Info, Init, Subobject,
6608                                      CAT->getElementType(), 1)) {
6609       if (!Info.noteFailure())
6610         return false;
6611       Success = false;
6612     }
6613   }
6614
6615   if (!Result.hasArrayFiller())
6616     return Success;
6617
6618   // If we get here, we have a trivial filler, which we can just evaluate
6619   // once and splat over the rest of the array elements.
6620   assert(FillerExpr && "no array filler for incomplete init list");
6621   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6622                          FillerExpr) && Success;
6623 }
6624
6625 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6626   if (E->getCommonExpr() &&
6627       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6628                 Info, E->getCommonExpr()->getSourceExpr()))
6629     return false;
6630
6631   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6632
6633   uint64_t Elements = CAT->getSize().getZExtValue();
6634   Result = APValue(APValue::UninitArray(), Elements, Elements);
6635
6636   LValue Subobject = This;
6637   Subobject.addArray(Info, E, CAT);
6638
6639   bool Success = true;
6640   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6641     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6642                          Info, Subobject, E->getSubExpr()) ||
6643         !HandleLValueArrayAdjustment(Info, E, Subobject,
6644                                      CAT->getElementType(), 1)) {
6645       if (!Info.noteFailure())
6646         return false;
6647       Success = false;
6648     }
6649   }
6650
6651   return Success;
6652 }
6653
6654 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6655   return VisitCXXConstructExpr(E, This, &Result, E->getType());
6656 }
6657
6658 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6659                                                const LValue &Subobject,
6660                                                APValue *Value,
6661                                                QualType Type) {
6662   bool HadZeroInit = !Value->isUninit();
6663
6664   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6665     unsigned N = CAT->getSize().getZExtValue();
6666
6667     // Preserve the array filler if we had prior zero-initialization.
6668     APValue Filler =
6669       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6670                                              : APValue();
6671
6672     *Value = APValue(APValue::UninitArray(), N, N);
6673
6674     if (HadZeroInit)
6675       for (unsigned I = 0; I != N; ++I)
6676         Value->getArrayInitializedElt(I) = Filler;
6677
6678     // Initialize the elements.
6679     LValue ArrayElt = Subobject;
6680     ArrayElt.addArray(Info, E, CAT);
6681     for (unsigned I = 0; I != N; ++I)
6682       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6683                                  CAT->getElementType()) ||
6684           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6685                                        CAT->getElementType(), 1))
6686         return false;
6687
6688     return true;
6689   }
6690
6691   if (!Type->isRecordType())
6692     return Error(E);
6693
6694   return RecordExprEvaluator(Info, Subobject, *Value)
6695              .VisitCXXConstructExpr(E, Type);
6696 }
6697
6698 //===----------------------------------------------------------------------===//
6699 // Integer Evaluation
6700 //
6701 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6702 // types and back in constant folding. Integer values are thus represented
6703 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6704 //===----------------------------------------------------------------------===//
6705
6706 namespace {
6707 class IntExprEvaluator
6708   : public ExprEvaluatorBase<IntExprEvaluator> {
6709   APValue &Result;
6710 public:
6711   IntExprEvaluator(EvalInfo &info, APValue &result)
6712     : ExprEvaluatorBaseTy(info), Result(result) {}
6713
6714   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6715     assert(E->getType()->isIntegralOrEnumerationType() &&
6716            "Invalid evaluation result.");
6717     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6718            "Invalid evaluation result.");
6719     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6720            "Invalid evaluation result.");
6721     Result = APValue(SI);
6722     return true;
6723   }
6724   bool Success(const llvm::APSInt &SI, const Expr *E) {
6725     return Success(SI, E, Result);
6726   }
6727
6728   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6729     assert(E->getType()->isIntegralOrEnumerationType() && 
6730            "Invalid evaluation result.");
6731     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6732            "Invalid evaluation result.");
6733     Result = APValue(APSInt(I));
6734     Result.getInt().setIsUnsigned(
6735                             E->getType()->isUnsignedIntegerOrEnumerationType());
6736     return true;
6737   }
6738   bool Success(const llvm::APInt &I, const Expr *E) {
6739     return Success(I, E, Result);
6740   }
6741
6742   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6743     assert(E->getType()->isIntegralOrEnumerationType() && 
6744            "Invalid evaluation result.");
6745     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6746     return true;
6747   }
6748   bool Success(uint64_t Value, const Expr *E) {
6749     return Success(Value, E, Result);
6750   }
6751
6752   bool Success(CharUnits Size, const Expr *E) {
6753     return Success(Size.getQuantity(), E);
6754   }
6755
6756   bool Success(const APValue &V, const Expr *E) {
6757     if (V.isLValue() || V.isAddrLabelDiff()) {
6758       Result = V;
6759       return true;
6760     }
6761     return Success(V.getInt(), E);
6762   }
6763
6764   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6765
6766   //===--------------------------------------------------------------------===//
6767   //                            Visitor Methods
6768   //===--------------------------------------------------------------------===//
6769
6770   bool VisitIntegerLiteral(const IntegerLiteral *E) {
6771     return Success(E->getValue(), E);
6772   }
6773   bool VisitCharacterLiteral(const CharacterLiteral *E) {
6774     return Success(E->getValue(), E);
6775   }
6776
6777   bool CheckReferencedDecl(const Expr *E, const Decl *D);
6778   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6779     if (CheckReferencedDecl(E, E->getDecl()))
6780       return true;
6781
6782     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6783   }
6784   bool VisitMemberExpr(const MemberExpr *E) {
6785     if (CheckReferencedDecl(E, E->getMemberDecl())) {
6786       VisitIgnoredBaseExpression(E->getBase());
6787       return true;
6788     }
6789
6790     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6791   }
6792
6793   bool VisitCallExpr(const CallExpr *E);
6794   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6795   bool VisitBinaryOperator(const BinaryOperator *E);
6796   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6797   bool VisitUnaryOperator(const UnaryOperator *E);
6798
6799   bool VisitCastExpr(const CastExpr* E);
6800   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6801
6802   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6803     return Success(E->getValue(), E);
6804   }
6805
6806   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6807     return Success(E->getValue(), E);
6808   }
6809
6810   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6811     if (Info.ArrayInitIndex == uint64_t(-1)) {
6812       // We were asked to evaluate this subexpression independent of the
6813       // enclosing ArrayInitLoopExpr. We can't do that.
6814       Info.FFDiag(E);
6815       return false;
6816     }
6817     return Success(Info.ArrayInitIndex, E);
6818   }
6819     
6820   // Note, GNU defines __null as an integer, not a pointer.
6821   bool VisitGNUNullExpr(const GNUNullExpr *E) {
6822     return ZeroInitialization(E);
6823   }
6824
6825   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6826     return Success(E->getValue(), E);
6827   }
6828
6829   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6830     return Success(E->getValue(), E);
6831   }
6832
6833   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6834     return Success(E->getValue(), E);
6835   }
6836
6837   bool VisitUnaryReal(const UnaryOperator *E);
6838   bool VisitUnaryImag(const UnaryOperator *E);
6839
6840   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6841   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6842
6843   // FIXME: Missing: array subscript of vector, member of vector
6844 };
6845 } // end anonymous namespace
6846
6847 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6848 /// produce either the integer value or a pointer.
6849 ///
6850 /// GCC has a heinous extension which folds casts between pointer types and
6851 /// pointer-sized integral types. We support this by allowing the evaluation of
6852 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6853 /// Some simple arithmetic on such values is supported (they are treated much
6854 /// like char*).
6855 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6856                                     EvalInfo &Info) {
6857   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6858   return IntExprEvaluator(Info, Result).Visit(E);
6859 }
6860
6861 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6862   APValue Val;
6863   if (!EvaluateIntegerOrLValue(E, Val, Info))
6864     return false;
6865   if (!Val.isInt()) {
6866     // FIXME: It would be better to produce the diagnostic for casting
6867     //        a pointer to an integer.
6868     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6869     return false;
6870   }
6871   Result = Val.getInt();
6872   return true;
6873 }
6874
6875 /// Check whether the given declaration can be directly converted to an integral
6876 /// rvalue. If not, no diagnostic is produced; there are other things we can
6877 /// try.
6878 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6879   // Enums are integer constant exprs.
6880   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6881     // Check for signedness/width mismatches between E type and ECD value.
6882     bool SameSign = (ECD->getInitVal().isSigned()
6883                      == E->getType()->isSignedIntegerOrEnumerationType());
6884     bool SameWidth = (ECD->getInitVal().getBitWidth()
6885                       == Info.Ctx.getIntWidth(E->getType()));
6886     if (SameSign && SameWidth)
6887       return Success(ECD->getInitVal(), E);
6888     else {
6889       // Get rid of mismatch (otherwise Success assertions will fail)
6890       // by computing a new value matching the type of E.
6891       llvm::APSInt Val = ECD->getInitVal();
6892       if (!SameSign)
6893         Val.setIsSigned(!ECD->getInitVal().isSigned());
6894       if (!SameWidth)
6895         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6896       return Success(Val, E);
6897     }
6898   }
6899   return false;
6900 }
6901
6902 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6903 /// as GCC.
6904 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6905                                        const LangOptions &LangOpts) {
6906   // The following enum mimics the values returned by GCC.
6907   // FIXME: Does GCC differ between lvalue and rvalue references here?
6908   enum gcc_type_class {
6909     no_type_class = -1,
6910     void_type_class, integer_type_class, char_type_class,
6911     enumeral_type_class, boolean_type_class,
6912     pointer_type_class, reference_type_class, offset_type_class,
6913     real_type_class, complex_type_class,
6914     function_type_class, method_type_class,
6915     record_type_class, union_type_class,
6916     array_type_class, string_type_class,
6917     lang_type_class
6918   };
6919
6920   // If no argument was supplied, default to "no_type_class". This isn't
6921   // ideal, however it is what gcc does.
6922   if (E->getNumArgs() == 0)
6923     return no_type_class;
6924
6925   QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6926   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6927
6928   switch (CanTy->getTypeClass()) {
6929 #define TYPE(ID, BASE)
6930 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6931 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6932 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6933 #include "clang/AST/TypeNodes.def"
6934       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6935
6936   case Type::Builtin:
6937     switch (BT->getKind()) {
6938 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6939 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6940 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6941 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6942 #include "clang/AST/BuiltinTypes.def"
6943     case BuiltinType::Void:
6944       return void_type_class;
6945
6946     case BuiltinType::Bool:
6947       return boolean_type_class;
6948
6949     case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6950     case BuiltinType::UChar:
6951     case BuiltinType::UShort:
6952     case BuiltinType::UInt:
6953     case BuiltinType::ULong:
6954     case BuiltinType::ULongLong:
6955     case BuiltinType::UInt128:
6956       return integer_type_class;
6957
6958     case BuiltinType::NullPtr:
6959       return pointer_type_class;
6960
6961     case BuiltinType::WChar_U:
6962     case BuiltinType::Char16:
6963     case BuiltinType::Char32:
6964     case BuiltinType::ObjCId:
6965     case BuiltinType::ObjCClass:
6966     case BuiltinType::ObjCSel:
6967 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6968     case BuiltinType::Id:
6969 #include "clang/Basic/OpenCLImageTypes.def"
6970     case BuiltinType::OCLSampler:
6971     case BuiltinType::OCLEvent:
6972     case BuiltinType::OCLClkEvent:
6973     case BuiltinType::OCLQueue:
6974     case BuiltinType::OCLNDRange:
6975     case BuiltinType::OCLReserveID:
6976     case BuiltinType::Dependent:
6977       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6978     };
6979
6980   case Type::Enum:
6981     return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6982     break;
6983
6984   case Type::Pointer:
6985     return pointer_type_class;
6986     break;
6987
6988   case Type::MemberPointer:
6989     if (CanTy->isMemberDataPointerType())
6990       return offset_type_class;
6991     else {
6992       // We expect member pointers to be either data or function pointers,
6993       // nothing else.
6994       assert(CanTy->isMemberFunctionPointerType());
6995       return method_type_class;
6996     }
6997
6998   case Type::Complex:
6999     return complex_type_class;
7000
7001   case Type::FunctionNoProto:
7002   case Type::FunctionProto:
7003     return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7004
7005   case Type::Record:
7006     if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7007       switch (RT->getDecl()->getTagKind()) {
7008       case TagTypeKind::TTK_Struct:
7009       case TagTypeKind::TTK_Class:
7010       case TagTypeKind::TTK_Interface:
7011         return record_type_class;
7012
7013       case TagTypeKind::TTK_Enum:
7014         return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7015
7016       case TagTypeKind::TTK_Union:
7017         return union_type_class;
7018       }
7019     }
7020     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7021
7022   case Type::ConstantArray:
7023   case Type::VariableArray:
7024   case Type::IncompleteArray:
7025     return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7026
7027   case Type::BlockPointer:
7028   case Type::LValueReference:
7029   case Type::RValueReference:
7030   case Type::Vector:
7031   case Type::ExtVector:
7032   case Type::Auto:
7033   case Type::ObjCObject:
7034   case Type::ObjCInterface:
7035   case Type::ObjCObjectPointer:
7036   case Type::Pipe:
7037   case Type::Atomic:
7038     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7039   }
7040
7041   llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7042 }
7043
7044 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7045 /// __builtin_constant_p when applied to the given lvalue.
7046 ///
7047 /// An lvalue is only "constant" if it is a pointer or reference to the first
7048 /// character of a string literal.
7049 template<typename LValue>
7050 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7051   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7052   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7053 }
7054
7055 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7056 /// GCC as we can manage.
7057 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7058   QualType ArgType = Arg->getType();
7059
7060   // __builtin_constant_p always has one operand. The rules which gcc follows
7061   // are not precisely documented, but are as follows:
7062   //
7063   //  - If the operand is of integral, floating, complex or enumeration type,
7064   //    and can be folded to a known value of that type, it returns 1.
7065   //  - If the operand and can be folded to a pointer to the first character
7066   //    of a string literal (or such a pointer cast to an integral type), it
7067   //    returns 1.
7068   //
7069   // Otherwise, it returns 0.
7070   //
7071   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7072   // its support for this does not currently work.
7073   if (ArgType->isIntegralOrEnumerationType()) {
7074     Expr::EvalResult Result;
7075     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7076       return false;
7077
7078     APValue &V = Result.Val;
7079     if (V.getKind() == APValue::Int)
7080       return true;
7081     if (V.getKind() == APValue::LValue)
7082       return EvaluateBuiltinConstantPForLValue(V);
7083   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7084     return Arg->isEvaluatable(Ctx);
7085   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7086     LValue LV;
7087     Expr::EvalStatus Status;
7088     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7089     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7090                           : EvaluatePointer(Arg, LV, Info)) &&
7091         !Status.HasSideEffects)
7092       return EvaluateBuiltinConstantPForLValue(LV);
7093   }
7094
7095   // Anything else isn't considered to be sufficiently constant.
7096   return false;
7097 }
7098
7099 /// Retrieves the "underlying object type" of the given expression,
7100 /// as used by __builtin_object_size.
7101 static QualType getObjectType(APValue::LValueBase B) {
7102   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7103     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7104       return VD->getType();
7105   } else if (const Expr *E = B.get<const Expr*>()) {
7106     if (isa<CompoundLiteralExpr>(E))
7107       return E->getType();
7108   }
7109
7110   return QualType();
7111 }
7112
7113 /// A more selective version of E->IgnoreParenCasts for
7114 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7115 /// to change the type of E.
7116 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7117 ///
7118 /// Always returns an RValue with a pointer representation.
7119 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7120   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7121
7122   auto *NoParens = E->IgnoreParens();
7123   auto *Cast = dyn_cast<CastExpr>(NoParens);
7124   if (Cast == nullptr)
7125     return NoParens;
7126
7127   // We only conservatively allow a few kinds of casts, because this code is
7128   // inherently a simple solution that seeks to support the common case.
7129   auto CastKind = Cast->getCastKind();
7130   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7131       CastKind != CK_AddressSpaceConversion)
7132     return NoParens;
7133
7134   auto *SubExpr = Cast->getSubExpr();
7135   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7136     return NoParens;
7137   return ignorePointerCastsAndParens(SubExpr);
7138 }
7139
7140 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7141 /// record layout. e.g.
7142 ///   struct { struct { int a, b; } fst, snd; } obj;
7143 ///   obj.fst   // no
7144 ///   obj.snd   // yes
7145 ///   obj.fst.a // no
7146 ///   obj.fst.b // no
7147 ///   obj.snd.a // no
7148 ///   obj.snd.b // yes
7149 ///
7150 /// Please note: this function is specialized for how __builtin_object_size
7151 /// views "objects".
7152 ///
7153 /// If this encounters an invalid RecordDecl, it will always return true.
7154 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7155   assert(!LVal.Designator.Invalid);
7156
7157   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7158     const RecordDecl *Parent = FD->getParent();
7159     Invalid = Parent->isInvalidDecl();
7160     if (Invalid || Parent->isUnion())
7161       return true;
7162     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7163     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7164   };
7165
7166   auto &Base = LVal.getLValueBase();
7167   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7168     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7169       bool Invalid;
7170       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7171         return Invalid;
7172     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7173       for (auto *FD : IFD->chain()) {
7174         bool Invalid;
7175         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7176           return Invalid;
7177       }
7178     }
7179   }
7180
7181   unsigned I = 0;
7182   QualType BaseType = getType(Base);
7183   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7184     assert(isBaseAnAllocSizeCall(Base) &&
7185            "Unsized array in non-alloc_size call?");
7186     // If this is an alloc_size base, we should ignore the initial array index
7187     ++I;
7188     BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7189   }
7190
7191   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7192     const auto &Entry = LVal.Designator.Entries[I];
7193     if (BaseType->isArrayType()) {
7194       // Because __builtin_object_size treats arrays as objects, we can ignore
7195       // the index iff this is the last array in the Designator.
7196       if (I + 1 == E)
7197         return true;
7198       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7199       uint64_t Index = Entry.ArrayIndex;
7200       if (Index + 1 != CAT->getSize())
7201         return false;
7202       BaseType = CAT->getElementType();
7203     } else if (BaseType->isAnyComplexType()) {
7204       const auto *CT = BaseType->castAs<ComplexType>();
7205       uint64_t Index = Entry.ArrayIndex;
7206       if (Index != 1)
7207         return false;
7208       BaseType = CT->getElementType();
7209     } else if (auto *FD = getAsField(Entry)) {
7210       bool Invalid;
7211       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7212         return Invalid;
7213       BaseType = FD->getType();
7214     } else {
7215       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7216       return false;
7217     }
7218   }
7219   return true;
7220 }
7221
7222 /// Tests to see if the LValue has a user-specified designator (that isn't
7223 /// necessarily valid). Note that this always returns 'true' if the LValue has
7224 /// an unsized array as its first designator entry, because there's currently no
7225 /// way to tell if the user typed *foo or foo[0].
7226 static bool refersToCompleteObject(const LValue &LVal) {
7227   if (LVal.Designator.Invalid)
7228     return false;
7229
7230   if (!LVal.Designator.Entries.empty())
7231     return LVal.Designator.isMostDerivedAnUnsizedArray();
7232
7233   if (!LVal.InvalidBase)
7234     return true;
7235
7236   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7237   // the LValueBase.
7238   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7239   return !E || !isa<MemberExpr>(E);
7240 }
7241
7242 /// Attempts to detect a user writing into a piece of memory that's impossible
7243 /// to figure out the size of by just using types.
7244 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7245   const SubobjectDesignator &Designator = LVal.Designator;
7246   // Notes:
7247   // - Users can only write off of the end when we have an invalid base. Invalid
7248   //   bases imply we don't know where the memory came from.
7249   // - We used to be a bit more aggressive here; we'd only be conservative if
7250   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7251   //   broke some common standard library extensions (PR30346), but was
7252   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7253   //   with some sort of whitelist. OTOH, it seems that GCC is always
7254   //   conservative with the last element in structs (if it's an array), so our
7255   //   current behavior is more compatible than a whitelisting approach would
7256   //   be.
7257   return LVal.InvalidBase &&
7258          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7259          Designator.MostDerivedIsArrayElement &&
7260          isDesignatorAtObjectEnd(Ctx, LVal);
7261 }
7262
7263 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7264 /// Fails if the conversion would cause loss of precision.
7265 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7266                                             CharUnits &Result) {
7267   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7268   if (Int.ugt(CharUnitsMax))
7269     return false;
7270   Result = CharUnits::fromQuantity(Int.getZExtValue());
7271   return true;
7272 }
7273
7274 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7275 /// determine how many bytes exist from the beginning of the object to either
7276 /// the end of the current subobject, or the end of the object itself, depending
7277 /// on what the LValue looks like + the value of Type.
7278 ///
7279 /// If this returns false, the value of Result is undefined.
7280 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7281                                unsigned Type, const LValue &LVal,
7282                                CharUnits &EndOffset) {
7283   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7284
7285   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7286     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7287       return false;
7288     return HandleSizeof(Info, ExprLoc, Ty, Result);
7289   };
7290
7291   // We want to evaluate the size of the entire object. This is a valid fallback
7292   // for when Type=1 and the designator is invalid, because we're asked for an
7293   // upper-bound.
7294   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7295     // Type=3 wants a lower bound, so we can't fall back to this.
7296     if (Type == 3 && !DetermineForCompleteObject)
7297       return false;
7298
7299     llvm::APInt APEndOffset;
7300     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7301         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7302       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7303
7304     if (LVal.InvalidBase)
7305       return false;
7306
7307     QualType BaseTy = getObjectType(LVal.getLValueBase());
7308     return CheckedHandleSizeof(BaseTy, EndOffset);
7309   }
7310
7311   // We want to evaluate the size of a subobject.
7312   const SubobjectDesignator &Designator = LVal.Designator;
7313
7314   // The following is a moderately common idiom in C:
7315   //
7316   // struct Foo { int a; char c[1]; };
7317   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7318   // strcpy(&F->c[0], Bar);
7319   //
7320   // In order to not break too much legacy code, we need to support it.
7321   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7322     // If we can resolve this to an alloc_size call, we can hand that back,
7323     // because we know for certain how many bytes there are to write to.
7324     llvm::APInt APEndOffset;
7325     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7326         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7327       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7328
7329     // If we cannot determine the size of the initial allocation, then we can't
7330     // given an accurate upper-bound. However, we are still able to give
7331     // conservative lower-bounds for Type=3.
7332     if (Type == 1)
7333       return false;
7334   }
7335
7336   CharUnits BytesPerElem;
7337   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7338     return false;
7339
7340   // According to the GCC documentation, we want the size of the subobject
7341   // denoted by the pointer. But that's not quite right -- what we actually
7342   // want is the size of the immediately-enclosing array, if there is one.
7343   int64_t ElemsRemaining;
7344   if (Designator.MostDerivedIsArrayElement &&
7345       Designator.Entries.size() == Designator.MostDerivedPathLength) {
7346     uint64_t ArraySize = Designator.getMostDerivedArraySize();
7347     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7348     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7349   } else {
7350     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7351   }
7352
7353   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7354   return true;
7355 }
7356
7357 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7358 /// returns true and stores the result in @p Size.
7359 ///
7360 /// If @p WasError is non-null, this will report whether the failure to evaluate
7361 /// is to be treated as an Error in IntExprEvaluator.
7362 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7363                                          EvalInfo &Info, uint64_t &Size) {
7364   // Determine the denoted object.
7365   LValue LVal;
7366   {
7367     // The operand of __builtin_object_size is never evaluated for side-effects.
7368     // If there are any, but we can determine the pointed-to object anyway, then
7369     // ignore the side-effects.
7370     SpeculativeEvaluationRAII SpeculativeEval(Info);
7371     FoldOffsetRAII Fold(Info);
7372
7373     if (E->isGLValue()) {
7374       // It's possible for us to be given GLValues if we're called via
7375       // Expr::tryEvaluateObjectSize.
7376       APValue RVal;
7377       if (!EvaluateAsRValue(Info, E, RVal))
7378         return false;
7379       LVal.setFrom(Info.Ctx, RVal);
7380     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7381                                 /*InvalidBaseOK=*/true))
7382       return false;
7383   }
7384
7385   // If we point to before the start of the object, there are no accessible
7386   // bytes.
7387   if (LVal.getLValueOffset().isNegative()) {
7388     Size = 0;
7389     return true;
7390   }
7391
7392   CharUnits EndOffset;
7393   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7394     return false;
7395
7396   // If we've fallen outside of the end offset, just pretend there's nothing to
7397   // write to/read from.
7398   if (EndOffset <= LVal.getLValueOffset())
7399     Size = 0;
7400   else
7401     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7402   return true;
7403 }
7404
7405 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7406   if (unsigned BuiltinOp = E->getBuiltinCallee())
7407     return VisitBuiltinCallExpr(E, BuiltinOp);
7408
7409   return ExprEvaluatorBaseTy::VisitCallExpr(E);
7410 }
7411
7412 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7413                                             unsigned BuiltinOp) {
7414   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7415   default:
7416     return ExprEvaluatorBaseTy::VisitCallExpr(E);
7417
7418   case Builtin::BI__builtin_object_size: {
7419     // The type was checked when we built the expression.
7420     unsigned Type =
7421         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7422     assert(Type <= 3 && "unexpected type");
7423
7424     uint64_t Size;
7425     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7426       return Success(Size, E);
7427
7428     if (E->getArg(0)->HasSideEffects(Info.Ctx))
7429       return Success((Type & 2) ? 0 : -1, E);
7430
7431     // Expression had no side effects, but we couldn't statically determine the
7432     // size of the referenced object.
7433     switch (Info.EvalMode) {
7434     case EvalInfo::EM_ConstantExpression:
7435     case EvalInfo::EM_PotentialConstantExpression:
7436     case EvalInfo::EM_ConstantFold:
7437     case EvalInfo::EM_EvaluateForOverflow:
7438     case EvalInfo::EM_IgnoreSideEffects:
7439     case EvalInfo::EM_OffsetFold:
7440       // Leave it to IR generation.
7441       return Error(E);
7442     case EvalInfo::EM_ConstantExpressionUnevaluated:
7443     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7444       // Reduce it to a constant now.
7445       return Success((Type & 2) ? 0 : -1, E);
7446     }
7447
7448     llvm_unreachable("unexpected EvalMode");
7449   }
7450
7451   case Builtin::BI__builtin_bswap16:
7452   case Builtin::BI__builtin_bswap32:
7453   case Builtin::BI__builtin_bswap64: {
7454     APSInt Val;
7455     if (!EvaluateInteger(E->getArg(0), Val, Info))
7456       return false;
7457
7458     return Success(Val.byteSwap(), E);
7459   }
7460
7461   case Builtin::BI__builtin_classify_type:
7462     return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7463
7464   // FIXME: BI__builtin_clrsb
7465   // FIXME: BI__builtin_clrsbl
7466   // FIXME: BI__builtin_clrsbll
7467
7468   case Builtin::BI__builtin_clz:
7469   case Builtin::BI__builtin_clzl:
7470   case Builtin::BI__builtin_clzll:
7471   case Builtin::BI__builtin_clzs: {
7472     APSInt Val;
7473     if (!EvaluateInteger(E->getArg(0), Val, Info))
7474       return false;
7475     if (!Val)
7476       return Error(E);
7477
7478     return Success(Val.countLeadingZeros(), E);
7479   }
7480
7481   case Builtin::BI__builtin_constant_p:
7482     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7483
7484   case Builtin::BI__builtin_ctz:
7485   case Builtin::BI__builtin_ctzl:
7486   case Builtin::BI__builtin_ctzll:
7487   case Builtin::BI__builtin_ctzs: {
7488     APSInt Val;
7489     if (!EvaluateInteger(E->getArg(0), Val, Info))
7490       return false;
7491     if (!Val)
7492       return Error(E);
7493
7494     return Success(Val.countTrailingZeros(), E);
7495   }
7496
7497   case Builtin::BI__builtin_eh_return_data_regno: {
7498     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7499     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7500     return Success(Operand, E);
7501   }
7502
7503   case Builtin::BI__builtin_expect:
7504     return Visit(E->getArg(0));
7505
7506   case Builtin::BI__builtin_ffs:
7507   case Builtin::BI__builtin_ffsl:
7508   case Builtin::BI__builtin_ffsll: {
7509     APSInt Val;
7510     if (!EvaluateInteger(E->getArg(0), Val, Info))
7511       return false;
7512
7513     unsigned N = Val.countTrailingZeros();
7514     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7515   }
7516
7517   case Builtin::BI__builtin_fpclassify: {
7518     APFloat Val(0.0);
7519     if (!EvaluateFloat(E->getArg(5), Val, Info))
7520       return false;
7521     unsigned Arg;
7522     switch (Val.getCategory()) {
7523     case APFloat::fcNaN: Arg = 0; break;
7524     case APFloat::fcInfinity: Arg = 1; break;
7525     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7526     case APFloat::fcZero: Arg = 4; break;
7527     }
7528     return Visit(E->getArg(Arg));
7529   }
7530
7531   case Builtin::BI__builtin_isinf_sign: {
7532     APFloat Val(0.0);
7533     return EvaluateFloat(E->getArg(0), Val, Info) &&
7534            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7535   }
7536
7537   case Builtin::BI__builtin_isinf: {
7538     APFloat Val(0.0);
7539     return EvaluateFloat(E->getArg(0), Val, Info) &&
7540            Success(Val.isInfinity() ? 1 : 0, E);
7541   }
7542
7543   case Builtin::BI__builtin_isfinite: {
7544     APFloat Val(0.0);
7545     return EvaluateFloat(E->getArg(0), Val, Info) &&
7546            Success(Val.isFinite() ? 1 : 0, E);
7547   }
7548
7549   case Builtin::BI__builtin_isnan: {
7550     APFloat Val(0.0);
7551     return EvaluateFloat(E->getArg(0), Val, Info) &&
7552            Success(Val.isNaN() ? 1 : 0, E);
7553   }
7554
7555   case Builtin::BI__builtin_isnormal: {
7556     APFloat Val(0.0);
7557     return EvaluateFloat(E->getArg(0), Val, Info) &&
7558            Success(Val.isNormal() ? 1 : 0, E);
7559   }
7560
7561   case Builtin::BI__builtin_parity:
7562   case Builtin::BI__builtin_parityl:
7563   case Builtin::BI__builtin_parityll: {
7564     APSInt Val;
7565     if (!EvaluateInteger(E->getArg(0), Val, Info))
7566       return false;
7567
7568     return Success(Val.countPopulation() % 2, E);
7569   }
7570
7571   case Builtin::BI__builtin_popcount:
7572   case Builtin::BI__builtin_popcountl:
7573   case Builtin::BI__builtin_popcountll: {
7574     APSInt Val;
7575     if (!EvaluateInteger(E->getArg(0), Val, Info))
7576       return false;
7577
7578     return Success(Val.countPopulation(), E);
7579   }
7580
7581   case Builtin::BIstrlen:
7582   case Builtin::BIwcslen:
7583     // A call to strlen is not a constant expression.
7584     if (Info.getLangOpts().CPlusPlus11)
7585       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7586         << /*isConstexpr*/0 << /*isConstructor*/0
7587         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7588     else
7589       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7590     // Fall through.
7591   case Builtin::BI__builtin_strlen:
7592   case Builtin::BI__builtin_wcslen: {
7593     // As an extension, we support __builtin_strlen() as a constant expression,
7594     // and support folding strlen() to a constant.
7595     LValue String;
7596     if (!EvaluatePointer(E->getArg(0), String, Info))
7597       return false;
7598
7599     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7600
7601     // Fast path: if it's a string literal, search the string value.
7602     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7603             String.getLValueBase().dyn_cast<const Expr *>())) {
7604       // The string literal may have embedded null characters. Find the first
7605       // one and truncate there.
7606       StringRef Str = S->getBytes();
7607       int64_t Off = String.Offset.getQuantity();
7608       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7609           S->getCharByteWidth() == 1 &&
7610           // FIXME: Add fast-path for wchar_t too.
7611           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7612         Str = Str.substr(Off);
7613
7614         StringRef::size_type Pos = Str.find(0);
7615         if (Pos != StringRef::npos)
7616           Str = Str.substr(0, Pos);
7617
7618         return Success(Str.size(), E);
7619       }
7620
7621       // Fall through to slow path to issue appropriate diagnostic.
7622     }
7623
7624     // Slow path: scan the bytes of the string looking for the terminating 0.
7625     for (uint64_t Strlen = 0; /**/; ++Strlen) {
7626       APValue Char;
7627       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7628           !Char.isInt())
7629         return false;
7630       if (!Char.getInt())
7631         return Success(Strlen, E);
7632       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7633         return false;
7634     }
7635   }
7636
7637   case Builtin::BIstrcmp:
7638   case Builtin::BIwcscmp:
7639   case Builtin::BIstrncmp:
7640   case Builtin::BIwcsncmp:
7641   case Builtin::BImemcmp:
7642   case Builtin::BIwmemcmp:
7643     // A call to strlen is not a constant expression.
7644     if (Info.getLangOpts().CPlusPlus11)
7645       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7646         << /*isConstexpr*/0 << /*isConstructor*/0
7647         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7648     else
7649       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7650     // Fall through.
7651   case Builtin::BI__builtin_strcmp:
7652   case Builtin::BI__builtin_wcscmp:
7653   case Builtin::BI__builtin_strncmp:
7654   case Builtin::BI__builtin_wcsncmp:
7655   case Builtin::BI__builtin_memcmp:
7656   case Builtin::BI__builtin_wmemcmp: {
7657     LValue String1, String2;
7658     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7659         !EvaluatePointer(E->getArg(1), String2, Info))
7660       return false;
7661
7662     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7663
7664     uint64_t MaxLength = uint64_t(-1);
7665     if (BuiltinOp != Builtin::BIstrcmp &&
7666         BuiltinOp != Builtin::BIwcscmp &&
7667         BuiltinOp != Builtin::BI__builtin_strcmp &&
7668         BuiltinOp != Builtin::BI__builtin_wcscmp) {
7669       APSInt N;
7670       if (!EvaluateInteger(E->getArg(2), N, Info))
7671         return false;
7672       MaxLength = N.getExtValue();
7673     }
7674     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7675                        BuiltinOp != Builtin::BIwmemcmp &&
7676                        BuiltinOp != Builtin::BI__builtin_memcmp &&
7677                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
7678     for (; MaxLength; --MaxLength) {
7679       APValue Char1, Char2;
7680       if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7681           !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7682           !Char1.isInt() || !Char2.isInt())
7683         return false;
7684       if (Char1.getInt() != Char2.getInt())
7685         return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7686       if (StopAtNull && !Char1.getInt())
7687         return Success(0, E);
7688       assert(!(StopAtNull && !Char2.getInt()));
7689       if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7690           !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7691         return false;
7692     }
7693     // We hit the strncmp / memcmp limit.
7694     return Success(0, E);
7695   }
7696
7697   case Builtin::BI__atomic_always_lock_free:
7698   case Builtin::BI__atomic_is_lock_free:
7699   case Builtin::BI__c11_atomic_is_lock_free: {
7700     APSInt SizeVal;
7701     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7702       return false;
7703
7704     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7705     // of two less than the maximum inline atomic width, we know it is
7706     // lock-free.  If the size isn't a power of two, or greater than the
7707     // maximum alignment where we promote atomics, we know it is not lock-free
7708     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
7709     // the answer can only be determined at runtime; for example, 16-byte
7710     // atomics have lock-free implementations on some, but not all,
7711     // x86-64 processors.
7712
7713     // Check power-of-two.
7714     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7715     if (Size.isPowerOfTwo()) {
7716       // Check against inlining width.
7717       unsigned InlineWidthBits =
7718           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7719       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7720         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7721             Size == CharUnits::One() ||
7722             E->getArg(1)->isNullPointerConstant(Info.Ctx,
7723                                                 Expr::NPC_NeverValueDependent))
7724           // OK, we will inline appropriately-aligned operations of this size,
7725           // and _Atomic(T) is appropriately-aligned.
7726           return Success(1, E);
7727
7728         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7729           castAs<PointerType>()->getPointeeType();
7730         if (!PointeeType->isIncompleteType() &&
7731             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7732           // OK, we will inline operations on this object.
7733           return Success(1, E);
7734         }
7735       }
7736     }
7737
7738     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7739         Success(0, E) : Error(E);
7740   }
7741   }
7742 }
7743
7744 static bool HasSameBase(const LValue &A, const LValue &B) {
7745   if (!A.getLValueBase())
7746     return !B.getLValueBase();
7747   if (!B.getLValueBase())
7748     return false;
7749
7750   if (A.getLValueBase().getOpaqueValue() !=
7751       B.getLValueBase().getOpaqueValue()) {
7752     const Decl *ADecl = GetLValueBaseDecl(A);
7753     if (!ADecl)
7754       return false;
7755     const Decl *BDecl = GetLValueBaseDecl(B);
7756     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7757       return false;
7758   }
7759
7760   return IsGlobalLValue(A.getLValueBase()) ||
7761          A.getLValueCallIndex() == B.getLValueCallIndex();
7762 }
7763
7764 /// \brief Determine whether this is a pointer past the end of the complete
7765 /// object referred to by the lvalue.
7766 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7767                                             const LValue &LV) {
7768   // A null pointer can be viewed as being "past the end" but we don't
7769   // choose to look at it that way here.
7770   if (!LV.getLValueBase())
7771     return false;
7772
7773   // If the designator is valid and refers to a subobject, we're not pointing
7774   // past the end.
7775   if (!LV.getLValueDesignator().Invalid &&
7776       !LV.getLValueDesignator().isOnePastTheEnd())
7777     return false;
7778
7779   // A pointer to an incomplete type might be past-the-end if the type's size is
7780   // zero.  We cannot tell because the type is incomplete.
7781   QualType Ty = getType(LV.getLValueBase());
7782   if (Ty->isIncompleteType())
7783     return true;
7784
7785   // We're a past-the-end pointer if we point to the byte after the object,
7786   // no matter what our type or path is.
7787   auto Size = Ctx.getTypeSizeInChars(Ty);
7788   return LV.getLValueOffset() == Size;
7789 }
7790
7791 namespace {
7792
7793 /// \brief Data recursive integer evaluator of certain binary operators.
7794 ///
7795 /// We use a data recursive algorithm for binary operators so that we are able
7796 /// to handle extreme cases of chained binary operators without causing stack
7797 /// overflow.
7798 class DataRecursiveIntBinOpEvaluator {
7799   struct EvalResult {
7800     APValue Val;
7801     bool Failed;
7802
7803     EvalResult() : Failed(false) { }
7804
7805     void swap(EvalResult &RHS) {
7806       Val.swap(RHS.Val);
7807       Failed = RHS.Failed;
7808       RHS.Failed = false;
7809     }
7810   };
7811
7812   struct Job {
7813     const Expr *E;
7814     EvalResult LHSResult; // meaningful only for binary operator expression.
7815     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7816
7817     Job() = default;
7818     Job(Job &&) = default;
7819
7820     void startSpeculativeEval(EvalInfo &Info) {
7821       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7822     }
7823
7824   private:
7825     SpeculativeEvaluationRAII SpecEvalRAII;
7826   };
7827
7828   SmallVector<Job, 16> Queue;
7829
7830   IntExprEvaluator &IntEval;
7831   EvalInfo &Info;
7832   APValue &FinalResult;
7833
7834 public:
7835   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7836     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7837
7838   /// \brief True if \param E is a binary operator that we are going to handle
7839   /// data recursively.
7840   /// We handle binary operators that are comma, logical, or that have operands
7841   /// with integral or enumeration type.
7842   static bool shouldEnqueue(const BinaryOperator *E) {
7843     return E->getOpcode() == BO_Comma ||
7844            E->isLogicalOp() ||
7845            (E->isRValue() &&
7846             E->getType()->isIntegralOrEnumerationType() &&
7847             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7848             E->getRHS()->getType()->isIntegralOrEnumerationType());
7849   }
7850
7851   bool Traverse(const BinaryOperator *E) {
7852     enqueue(E);
7853     EvalResult PrevResult;
7854     while (!Queue.empty())
7855       process(PrevResult);
7856
7857     if (PrevResult.Failed) return false;
7858
7859     FinalResult.swap(PrevResult.Val);
7860     return true;
7861   }
7862
7863 private:
7864   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7865     return IntEval.Success(Value, E, Result);
7866   }
7867   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7868     return IntEval.Success(Value, E, Result);
7869   }
7870   bool Error(const Expr *E) {
7871     return IntEval.Error(E);
7872   }
7873   bool Error(const Expr *E, diag::kind D) {
7874     return IntEval.Error(E, D);
7875   }
7876
7877   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7878     return Info.CCEDiag(E, D);
7879   }
7880
7881   // \brief Returns true if visiting the RHS is necessary, false otherwise.
7882   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7883                          bool &SuppressRHSDiags);
7884
7885   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7886                   const BinaryOperator *E, APValue &Result);
7887
7888   void EvaluateExpr(const Expr *E, EvalResult &Result) {
7889     Result.Failed = !Evaluate(Result.Val, Info, E);
7890     if (Result.Failed)
7891       Result.Val = APValue();
7892   }
7893
7894   void process(EvalResult &Result);
7895
7896   void enqueue(const Expr *E) {
7897     E = E->IgnoreParens();
7898     Queue.resize(Queue.size()+1);
7899     Queue.back().E = E;
7900     Queue.back().Kind = Job::AnyExprKind;
7901   }
7902 };
7903
7904 }
7905
7906 bool DataRecursiveIntBinOpEvaluator::
7907        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7908                          bool &SuppressRHSDiags) {
7909   if (E->getOpcode() == BO_Comma) {
7910     // Ignore LHS but note if we could not evaluate it.
7911     if (LHSResult.Failed)
7912       return Info.noteSideEffect();
7913     return true;
7914   }
7915
7916   if (E->isLogicalOp()) {
7917     bool LHSAsBool;
7918     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7919       // We were able to evaluate the LHS, see if we can get away with not
7920       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7921       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7922         Success(LHSAsBool, E, LHSResult.Val);
7923         return false; // Ignore RHS
7924       }
7925     } else {
7926       LHSResult.Failed = true;
7927
7928       // Since we weren't able to evaluate the left hand side, it
7929       // might have had side effects.
7930       if (!Info.noteSideEffect())
7931         return false;
7932
7933       // We can't evaluate the LHS; however, sometimes the result
7934       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7935       // Don't ignore RHS and suppress diagnostics from this arm.
7936       SuppressRHSDiags = true;
7937     }
7938
7939     return true;
7940   }
7941
7942   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7943          E->getRHS()->getType()->isIntegralOrEnumerationType());
7944
7945   if (LHSResult.Failed && !Info.noteFailure())
7946     return false; // Ignore RHS;
7947
7948   return true;
7949 }
7950
7951 bool DataRecursiveIntBinOpEvaluator::
7952        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7953                   const BinaryOperator *E, APValue &Result) {
7954   if (E->getOpcode() == BO_Comma) {
7955     if (RHSResult.Failed)
7956       return false;
7957     Result = RHSResult.Val;
7958     return true;
7959   }
7960   
7961   if (E->isLogicalOp()) {
7962     bool lhsResult, rhsResult;
7963     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7964     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7965     
7966     if (LHSIsOK) {
7967       if (RHSIsOK) {
7968         if (E->getOpcode() == BO_LOr)
7969           return Success(lhsResult || rhsResult, E, Result);
7970         else
7971           return Success(lhsResult && rhsResult, E, Result);
7972       }
7973     } else {
7974       if (RHSIsOK) {
7975         // We can't evaluate the LHS; however, sometimes the result
7976         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7977         if (rhsResult == (E->getOpcode() == BO_LOr))
7978           return Success(rhsResult, E, Result);
7979       }
7980     }
7981     
7982     return false;
7983   }
7984   
7985   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7986          E->getRHS()->getType()->isIntegralOrEnumerationType());
7987   
7988   if (LHSResult.Failed || RHSResult.Failed)
7989     return false;
7990   
7991   const APValue &LHSVal = LHSResult.Val;
7992   const APValue &RHSVal = RHSResult.Val;
7993   
7994   // Handle cases like (unsigned long)&a + 4.
7995   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7996     Result = LHSVal;
7997     CharUnits AdditionalOffset =
7998         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7999     if (E->getOpcode() == BO_Add)
8000       Result.getLValueOffset() += AdditionalOffset;
8001     else
8002       Result.getLValueOffset() -= AdditionalOffset;
8003     return true;
8004   }
8005   
8006   // Handle cases like 4 + (unsigned long)&a
8007   if (E->getOpcode() == BO_Add &&
8008       RHSVal.isLValue() && LHSVal.isInt()) {
8009     Result = RHSVal;
8010     Result.getLValueOffset() +=
8011         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
8012     return true;
8013   }
8014   
8015   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8016     // Handle (intptr_t)&&A - (intptr_t)&&B.
8017     if (!LHSVal.getLValueOffset().isZero() ||
8018         !RHSVal.getLValueOffset().isZero())
8019       return false;
8020     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8021     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8022     if (!LHSExpr || !RHSExpr)
8023       return false;
8024     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8025     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8026     if (!LHSAddrExpr || !RHSAddrExpr)
8027       return false;
8028     // Make sure both labels come from the same function.
8029     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8030         RHSAddrExpr->getLabel()->getDeclContext())
8031       return false;
8032     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8033     return true;
8034   }
8035
8036   // All the remaining cases expect both operands to be an integer
8037   if (!LHSVal.isInt() || !RHSVal.isInt())
8038     return Error(E);
8039
8040   // Set up the width and signedness manually, in case it can't be deduced
8041   // from the operation we're performing.
8042   // FIXME: Don't do this in the cases where we can deduce it.
8043   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8044                E->getType()->isUnsignedIntegerOrEnumerationType());
8045   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8046                          RHSVal.getInt(), Value))
8047     return false;
8048   return Success(Value, E, Result);
8049 }
8050
8051 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8052   Job &job = Queue.back();
8053   
8054   switch (job.Kind) {
8055     case Job::AnyExprKind: {
8056       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8057         if (shouldEnqueue(Bop)) {
8058           job.Kind = Job::BinOpKind;
8059           enqueue(Bop->getLHS());
8060           return;
8061         }
8062       }
8063       
8064       EvaluateExpr(job.E, Result);
8065       Queue.pop_back();
8066       return;
8067     }
8068       
8069     case Job::BinOpKind: {
8070       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8071       bool SuppressRHSDiags = false;
8072       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8073         Queue.pop_back();
8074         return;
8075       }
8076       if (SuppressRHSDiags)
8077         job.startSpeculativeEval(Info);
8078       job.LHSResult.swap(Result);
8079       job.Kind = Job::BinOpVisitedLHSKind;
8080       enqueue(Bop->getRHS());
8081       return;
8082     }
8083       
8084     case Job::BinOpVisitedLHSKind: {
8085       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8086       EvalResult RHS;
8087       RHS.swap(Result);
8088       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8089       Queue.pop_back();
8090       return;
8091     }
8092   }
8093   
8094   llvm_unreachable("Invalid Job::Kind!");
8095 }
8096
8097 namespace {
8098 /// Used when we determine that we should fail, but can keep evaluating prior to
8099 /// noting that we had a failure.
8100 class DelayedNoteFailureRAII {
8101   EvalInfo &Info;
8102   bool NoteFailure;
8103
8104 public:
8105   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8106       : Info(Info), NoteFailure(NoteFailure) {}
8107   ~DelayedNoteFailureRAII() {
8108     if (NoteFailure) {
8109       bool ContinueAfterFailure = Info.noteFailure();
8110       (void)ContinueAfterFailure;
8111       assert(ContinueAfterFailure &&
8112              "Shouldn't have kept evaluating on failure.");
8113     }
8114   }
8115 };
8116 }
8117
8118 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8119   // We don't call noteFailure immediately because the assignment happens after
8120   // we evaluate LHS and RHS.
8121   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8122     return Error(E);
8123
8124   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8125   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8126     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8127
8128   QualType LHSTy = E->getLHS()->getType();
8129   QualType RHSTy = E->getRHS()->getType();
8130
8131   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8132     ComplexValue LHS, RHS;
8133     bool LHSOK;
8134     if (E->isAssignmentOp()) {
8135       LValue LV;
8136       EvaluateLValue(E->getLHS(), LV, Info);
8137       LHSOK = false;
8138     } else if (LHSTy->isRealFloatingType()) {
8139       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8140       if (LHSOK) {
8141         LHS.makeComplexFloat();
8142         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8143       }
8144     } else {
8145       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8146     }
8147     if (!LHSOK && !Info.noteFailure())
8148       return false;
8149
8150     if (E->getRHS()->getType()->isRealFloatingType()) {
8151       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8152         return false;
8153       RHS.makeComplexFloat();
8154       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8155     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8156       return false;
8157
8158     if (LHS.isComplexFloat()) {
8159       APFloat::cmpResult CR_r =
8160         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8161       APFloat::cmpResult CR_i =
8162         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8163
8164       if (E->getOpcode() == BO_EQ)
8165         return Success((CR_r == APFloat::cmpEqual &&
8166                         CR_i == APFloat::cmpEqual), E);
8167       else {
8168         assert(E->getOpcode() == BO_NE &&
8169                "Invalid complex comparison.");
8170         return Success(((CR_r == APFloat::cmpGreaterThan ||
8171                          CR_r == APFloat::cmpLessThan ||
8172                          CR_r == APFloat::cmpUnordered) ||
8173                         (CR_i == APFloat::cmpGreaterThan ||
8174                          CR_i == APFloat::cmpLessThan ||
8175                          CR_i == APFloat::cmpUnordered)), E);
8176       }
8177     } else {
8178       if (E->getOpcode() == BO_EQ)
8179         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8180                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8181       else {
8182         assert(E->getOpcode() == BO_NE &&
8183                "Invalid compex comparison.");
8184         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8185                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8186       }
8187     }
8188   }
8189
8190   if (LHSTy->isRealFloatingType() &&
8191       RHSTy->isRealFloatingType()) {
8192     APFloat RHS(0.0), LHS(0.0);
8193
8194     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8195     if (!LHSOK && !Info.noteFailure())
8196       return false;
8197
8198     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8199       return false;
8200
8201     APFloat::cmpResult CR = LHS.compare(RHS);
8202
8203     switch (E->getOpcode()) {
8204     default:
8205       llvm_unreachable("Invalid binary operator!");
8206     case BO_LT:
8207       return Success(CR == APFloat::cmpLessThan, E);
8208     case BO_GT:
8209       return Success(CR == APFloat::cmpGreaterThan, E);
8210     case BO_LE:
8211       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8212     case BO_GE:
8213       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8214                      E);
8215     case BO_EQ:
8216       return Success(CR == APFloat::cmpEqual, E);
8217     case BO_NE:
8218       return Success(CR == APFloat::cmpGreaterThan
8219                      || CR == APFloat::cmpLessThan
8220                      || CR == APFloat::cmpUnordered, E);
8221     }
8222   }
8223
8224   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8225     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8226       LValue LHSValue, RHSValue;
8227
8228       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8229       if (!LHSOK && !Info.noteFailure())
8230         return false;
8231
8232       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8233         return false;
8234
8235       // Reject differing bases from the normal codepath; we special-case
8236       // comparisons to null.
8237       if (!HasSameBase(LHSValue, RHSValue)) {
8238         if (E->getOpcode() == BO_Sub) {
8239           // Handle &&A - &&B.
8240           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8241             return Error(E);
8242           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8243           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8244           if (!LHSExpr || !RHSExpr)
8245             return Error(E);
8246           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8247           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8248           if (!LHSAddrExpr || !RHSAddrExpr)
8249             return Error(E);
8250           // Make sure both labels come from the same function.
8251           if (LHSAddrExpr->getLabel()->getDeclContext() !=
8252               RHSAddrExpr->getLabel()->getDeclContext())
8253             return Error(E);
8254           return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8255         }
8256         // Inequalities and subtractions between unrelated pointers have
8257         // unspecified or undefined behavior.
8258         if (!E->isEqualityOp())
8259           return Error(E);
8260         // A constant address may compare equal to the address of a symbol.
8261         // The one exception is that address of an object cannot compare equal
8262         // to a null pointer constant.
8263         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8264             (!RHSValue.Base && !RHSValue.Offset.isZero()))
8265           return Error(E);
8266         // It's implementation-defined whether distinct literals will have
8267         // distinct addresses. In clang, the result of such a comparison is
8268         // unspecified, so it is not a constant expression. However, we do know
8269         // that the address of a literal will be non-null.
8270         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8271             LHSValue.Base && RHSValue.Base)
8272           return Error(E);
8273         // We can't tell whether weak symbols will end up pointing to the same
8274         // object.
8275         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8276           return Error(E);
8277         // We can't compare the address of the start of one object with the
8278         // past-the-end address of another object, per C++ DR1652.
8279         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8280              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8281             (RHSValue.Base && RHSValue.Offset.isZero() &&
8282              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8283           return Error(E);
8284         // We can't tell whether an object is at the same address as another
8285         // zero sized object.
8286         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8287             (LHSValue.Base && isZeroSized(RHSValue)))
8288           return Error(E);
8289         // Pointers with different bases cannot represent the same object.
8290         // (Note that clang defaults to -fmerge-all-constants, which can
8291         // lead to inconsistent results for comparisons involving the address
8292         // of a constant; this generally doesn't matter in practice.)
8293         return Success(E->getOpcode() == BO_NE, E);
8294       }
8295
8296       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8297       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8298
8299       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8300       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8301
8302       if (E->getOpcode() == BO_Sub) {
8303         // C++11 [expr.add]p6:
8304         //   Unless both pointers point to elements of the same array object, or
8305         //   one past the last element of the array object, the behavior is
8306         //   undefined.
8307         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8308             !AreElementsOfSameArray(getType(LHSValue.Base),
8309                                     LHSDesignator, RHSDesignator))
8310           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8311
8312         QualType Type = E->getLHS()->getType();
8313         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8314
8315         CharUnits ElementSize;
8316         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8317           return false;
8318
8319         // As an extension, a type may have zero size (empty struct or union in
8320         // C, array of zero length). Pointer subtraction in such cases has
8321         // undefined behavior, so is not constant.
8322         if (ElementSize.isZero()) {
8323           Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8324             << ElementType;
8325           return false;
8326         }
8327
8328         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8329         // and produce incorrect results when it overflows. Such behavior
8330         // appears to be non-conforming, but is common, so perhaps we should
8331         // assume the standard intended for such cases to be undefined behavior
8332         // and check for them.
8333
8334         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8335         // overflow in the final conversion to ptrdiff_t.
8336         APSInt LHS(
8337           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8338         APSInt RHS(
8339           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8340         APSInt ElemSize(
8341           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8342         APSInt TrueResult = (LHS - RHS) / ElemSize;
8343         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8344
8345         if (Result.extend(65) != TrueResult &&
8346             !HandleOverflow(Info, E, TrueResult, E->getType()))
8347           return false;
8348         return Success(Result, E);
8349       }
8350
8351       // C++11 [expr.rel]p3:
8352       //   Pointers to void (after pointer conversions) can be compared, with a
8353       //   result defined as follows: If both pointers represent the same
8354       //   address or are both the null pointer value, the result is true if the
8355       //   operator is <= or >= and false otherwise; otherwise the result is
8356       //   unspecified.
8357       // We interpret this as applying to pointers to *cv* void.
8358       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8359           E->isRelationalOp())
8360         CCEDiag(E, diag::note_constexpr_void_comparison);
8361
8362       // C++11 [expr.rel]p2:
8363       // - If two pointers point to non-static data members of the same object,
8364       //   or to subobjects or array elements fo such members, recursively, the
8365       //   pointer to the later declared member compares greater provided the
8366       //   two members have the same access control and provided their class is
8367       //   not a union.
8368       //   [...]
8369       // - Otherwise pointer comparisons are unspecified.
8370       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8371           E->isRelationalOp()) {
8372         bool WasArrayIndex;
8373         unsigned Mismatch =
8374           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8375                                  RHSDesignator, WasArrayIndex);
8376         // At the point where the designators diverge, the comparison has a
8377         // specified value if:
8378         //  - we are comparing array indices
8379         //  - we are comparing fields of a union, or fields with the same access
8380         // Otherwise, the result is unspecified and thus the comparison is not a
8381         // constant expression.
8382         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8383             Mismatch < RHSDesignator.Entries.size()) {
8384           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8385           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8386           if (!LF && !RF)
8387             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8388           else if (!LF)
8389             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8390               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8391               << RF->getParent() << RF;
8392           else if (!RF)
8393             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8394               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8395               << LF->getParent() << LF;
8396           else if (!LF->getParent()->isUnion() &&
8397                    LF->getAccess() != RF->getAccess())
8398             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8399               << LF << LF->getAccess() << RF << RF->getAccess()
8400               << LF->getParent();
8401         }
8402       }
8403
8404       // The comparison here must be unsigned, and performed with the same
8405       // width as the pointer.
8406       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8407       uint64_t CompareLHS = LHSOffset.getQuantity();
8408       uint64_t CompareRHS = RHSOffset.getQuantity();
8409       assert(PtrSize <= 64 && "Unexpected pointer width");
8410       uint64_t Mask = ~0ULL >> (64 - PtrSize);
8411       CompareLHS &= Mask;
8412       CompareRHS &= Mask;
8413
8414       // If there is a base and this is a relational operator, we can only
8415       // compare pointers within the object in question; otherwise, the result
8416       // depends on where the object is located in memory.
8417       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8418         QualType BaseTy = getType(LHSValue.Base);
8419         if (BaseTy->isIncompleteType())
8420           return Error(E);
8421         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8422         uint64_t OffsetLimit = Size.getQuantity();
8423         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8424           return Error(E);
8425       }
8426
8427       switch (E->getOpcode()) {
8428       default: llvm_unreachable("missing comparison operator");
8429       case BO_LT: return Success(CompareLHS < CompareRHS, E);
8430       case BO_GT: return Success(CompareLHS > CompareRHS, E);
8431       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8432       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8433       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8434       case BO_NE: return Success(CompareLHS != CompareRHS, E);
8435       }
8436     }
8437   }
8438
8439   if (LHSTy->isMemberPointerType()) {
8440     assert(E->isEqualityOp() && "unexpected member pointer operation");
8441     assert(RHSTy->isMemberPointerType() && "invalid comparison");
8442
8443     MemberPtr LHSValue, RHSValue;
8444
8445     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8446     if (!LHSOK && !Info.noteFailure())
8447       return false;
8448
8449     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8450       return false;
8451
8452     // C++11 [expr.eq]p2:
8453     //   If both operands are null, they compare equal. Otherwise if only one is
8454     //   null, they compare unequal.
8455     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8456       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8457       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8458     }
8459
8460     //   Otherwise if either is a pointer to a virtual member function, the
8461     //   result is unspecified.
8462     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8463       if (MD->isVirtual())
8464         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8465     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8466       if (MD->isVirtual())
8467         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8468
8469     //   Otherwise they compare equal if and only if they would refer to the
8470     //   same member of the same most derived object or the same subobject if
8471     //   they were dereferenced with a hypothetical object of the associated
8472     //   class type.
8473     bool Equal = LHSValue == RHSValue;
8474     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8475   }
8476
8477   if (LHSTy->isNullPtrType()) {
8478     assert(E->isComparisonOp() && "unexpected nullptr operation");
8479     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8480     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8481     // are compared, the result is true of the operator is <=, >= or ==, and
8482     // false otherwise.
8483     BinaryOperator::Opcode Opcode = E->getOpcode();
8484     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8485   }
8486
8487   assert((!LHSTy->isIntegralOrEnumerationType() ||
8488           !RHSTy->isIntegralOrEnumerationType()) &&
8489          "DataRecursiveIntBinOpEvaluator should have handled integral types");
8490   // We can't continue from here for non-integral types.
8491   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8492 }
8493
8494 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8495 /// a result as the expression's type.
8496 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8497                                     const UnaryExprOrTypeTraitExpr *E) {
8498   switch(E->getKind()) {
8499   case UETT_AlignOf: {
8500     if (E->isArgumentType())
8501       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8502     else
8503       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8504   }
8505
8506   case UETT_VecStep: {
8507     QualType Ty = E->getTypeOfArgument();
8508
8509     if (Ty->isVectorType()) {
8510       unsigned n = Ty->castAs<VectorType>()->getNumElements();
8511
8512       // The vec_step built-in functions that take a 3-component
8513       // vector return 4. (OpenCL 1.1 spec 6.11.12)
8514       if (n == 3)
8515         n = 4;
8516
8517       return Success(n, E);
8518     } else
8519       return Success(1, E);
8520   }
8521
8522   case UETT_SizeOf: {
8523     QualType SrcTy = E->getTypeOfArgument();
8524     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8525     //   the result is the size of the referenced type."
8526     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8527       SrcTy = Ref->getPointeeType();
8528
8529     CharUnits Sizeof;
8530     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8531       return false;
8532     return Success(Sizeof, E);
8533   }
8534   case UETT_OpenMPRequiredSimdAlign:
8535     assert(E->isArgumentType());
8536     return Success(
8537         Info.Ctx.toCharUnitsFromBits(
8538                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8539             .getQuantity(),
8540         E);
8541   }
8542
8543   llvm_unreachable("unknown expr/type trait");
8544 }
8545
8546 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8547   CharUnits Result;
8548   unsigned n = OOE->getNumComponents();
8549   if (n == 0)
8550     return Error(OOE);
8551   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8552   for (unsigned i = 0; i != n; ++i) {
8553     OffsetOfNode ON = OOE->getComponent(i);
8554     switch (ON.getKind()) {
8555     case OffsetOfNode::Array: {
8556       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8557       APSInt IdxResult;
8558       if (!EvaluateInteger(Idx, IdxResult, Info))
8559         return false;
8560       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8561       if (!AT)
8562         return Error(OOE);
8563       CurrentType = AT->getElementType();
8564       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8565       Result += IdxResult.getSExtValue() * ElementSize;
8566       break;
8567     }
8568
8569     case OffsetOfNode::Field: {
8570       FieldDecl *MemberDecl = ON.getField();
8571       const RecordType *RT = CurrentType->getAs<RecordType>();
8572       if (!RT)
8573         return Error(OOE);
8574       RecordDecl *RD = RT->getDecl();
8575       if (RD->isInvalidDecl()) return false;
8576       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8577       unsigned i = MemberDecl->getFieldIndex();
8578       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8579       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8580       CurrentType = MemberDecl->getType().getNonReferenceType();
8581       break;
8582     }
8583
8584     case OffsetOfNode::Identifier:
8585       llvm_unreachable("dependent __builtin_offsetof");
8586
8587     case OffsetOfNode::Base: {
8588       CXXBaseSpecifier *BaseSpec = ON.getBase();
8589       if (BaseSpec->isVirtual())
8590         return Error(OOE);
8591
8592       // Find the layout of the class whose base we are looking into.
8593       const RecordType *RT = CurrentType->getAs<RecordType>();
8594       if (!RT)
8595         return Error(OOE);
8596       RecordDecl *RD = RT->getDecl();
8597       if (RD->isInvalidDecl()) return false;
8598       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8599
8600       // Find the base class itself.
8601       CurrentType = BaseSpec->getType();
8602       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8603       if (!BaseRT)
8604         return Error(OOE);
8605       
8606       // Add the offset to the base.
8607       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8608       break;
8609     }
8610     }
8611   }
8612   return Success(Result, OOE);
8613 }
8614
8615 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8616   switch (E->getOpcode()) {
8617   default:
8618     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8619     // See C99 6.6p3.
8620     return Error(E);
8621   case UO_Extension:
8622     // FIXME: Should extension allow i-c-e extension expressions in its scope?
8623     // If so, we could clear the diagnostic ID.
8624     return Visit(E->getSubExpr());
8625   case UO_Plus:
8626     // The result is just the value.
8627     return Visit(E->getSubExpr());
8628   case UO_Minus: {
8629     if (!Visit(E->getSubExpr()))
8630       return false;
8631     if (!Result.isInt()) return Error(E);
8632     const APSInt &Value = Result.getInt();
8633     if (Value.isSigned() && Value.isMinSignedValue() &&
8634         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8635                         E->getType()))
8636       return false;
8637     return Success(-Value, E);
8638   }
8639   case UO_Not: {
8640     if (!Visit(E->getSubExpr()))
8641       return false;
8642     if (!Result.isInt()) return Error(E);
8643     return Success(~Result.getInt(), E);
8644   }
8645   case UO_LNot: {
8646     bool bres;
8647     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8648       return false;
8649     return Success(!bres, E);
8650   }
8651   }
8652 }
8653
8654 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8655 /// result type is integer.
8656 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8657   const Expr *SubExpr = E->getSubExpr();
8658   QualType DestType = E->getType();
8659   QualType SrcType = SubExpr->getType();
8660
8661   switch (E->getCastKind()) {
8662   case CK_BaseToDerived:
8663   case CK_DerivedToBase:
8664   case CK_UncheckedDerivedToBase:
8665   case CK_Dynamic:
8666   case CK_ToUnion:
8667   case CK_ArrayToPointerDecay:
8668   case CK_FunctionToPointerDecay:
8669   case CK_NullToPointer:
8670   case CK_NullToMemberPointer:
8671   case CK_BaseToDerivedMemberPointer:
8672   case CK_DerivedToBaseMemberPointer:
8673   case CK_ReinterpretMemberPointer:
8674   case CK_ConstructorConversion:
8675   case CK_IntegralToPointer:
8676   case CK_ToVoid:
8677   case CK_VectorSplat:
8678   case CK_IntegralToFloating:
8679   case CK_FloatingCast:
8680   case CK_CPointerToObjCPointerCast:
8681   case CK_BlockPointerToObjCPointerCast:
8682   case CK_AnyPointerToBlockPointerCast:
8683   case CK_ObjCObjectLValueCast:
8684   case CK_FloatingRealToComplex:
8685   case CK_FloatingComplexToReal:
8686   case CK_FloatingComplexCast:
8687   case CK_FloatingComplexToIntegralComplex:
8688   case CK_IntegralRealToComplex:
8689   case CK_IntegralComplexCast:
8690   case CK_IntegralComplexToFloatingComplex:
8691   case CK_BuiltinFnToFnPtr:
8692   case CK_ZeroToOCLEvent:
8693   case CK_ZeroToOCLQueue:
8694   case CK_NonAtomicToAtomic:
8695   case CK_AddressSpaceConversion:
8696   case CK_IntToOCLSampler:
8697     llvm_unreachable("invalid cast kind for integral value");
8698
8699   case CK_BitCast:
8700   case CK_Dependent:
8701   case CK_LValueBitCast:
8702   case CK_ARCProduceObject:
8703   case CK_ARCConsumeObject:
8704   case CK_ARCReclaimReturnedObject:
8705   case CK_ARCExtendBlockObject:
8706   case CK_CopyAndAutoreleaseBlockObject:
8707     return Error(E);
8708
8709   case CK_UserDefinedConversion:
8710   case CK_LValueToRValue:
8711   case CK_AtomicToNonAtomic:
8712   case CK_NoOp:
8713     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8714
8715   case CK_MemberPointerToBoolean:
8716   case CK_PointerToBoolean:
8717   case CK_IntegralToBoolean:
8718   case CK_FloatingToBoolean:
8719   case CK_BooleanToSignedIntegral:
8720   case CK_FloatingComplexToBoolean:
8721   case CK_IntegralComplexToBoolean: {
8722     bool BoolResult;
8723     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8724       return false;
8725     uint64_t IntResult = BoolResult;
8726     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8727       IntResult = (uint64_t)-1;
8728     return Success(IntResult, E);
8729   }
8730
8731   case CK_IntegralCast: {
8732     if (!Visit(SubExpr))
8733       return false;
8734
8735     if (!Result.isInt()) {
8736       // Allow casts of address-of-label differences if they are no-ops
8737       // or narrowing.  (The narrowing case isn't actually guaranteed to
8738       // be constant-evaluatable except in some narrow cases which are hard
8739       // to detect here.  We let it through on the assumption the user knows
8740       // what they are doing.)
8741       if (Result.isAddrLabelDiff())
8742         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8743       // Only allow casts of lvalues if they are lossless.
8744       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8745     }
8746
8747     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8748                                       Result.getInt()), E);
8749   }
8750
8751   case CK_PointerToIntegral: {
8752     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8753
8754     LValue LV;
8755     if (!EvaluatePointer(SubExpr, LV, Info))
8756       return false;
8757
8758     if (LV.getLValueBase()) {
8759       // Only allow based lvalue casts if they are lossless.
8760       // FIXME: Allow a larger integer size than the pointer size, and allow
8761       // narrowing back down to pointer width in subsequent integral casts.
8762       // FIXME: Check integer type's active bits, not its type size.
8763       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8764         return Error(E);
8765
8766       LV.Designator.setInvalid();
8767       LV.moveInto(Result);
8768       return true;
8769     }
8770
8771     uint64_t V;
8772     if (LV.isNullPointer())
8773       V = Info.Ctx.getTargetNullPointerValue(SrcType);
8774     else
8775       V = LV.getLValueOffset().getQuantity();
8776
8777     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8778     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8779   }
8780
8781   case CK_IntegralComplexToReal: {
8782     ComplexValue C;
8783     if (!EvaluateComplex(SubExpr, C, Info))
8784       return false;
8785     return Success(C.getComplexIntReal(), E);
8786   }
8787
8788   case CK_FloatingToIntegral: {
8789     APFloat F(0.0);
8790     if (!EvaluateFloat(SubExpr, F, Info))
8791       return false;
8792
8793     APSInt Value;
8794     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8795       return false;
8796     return Success(Value, E);
8797   }
8798   }
8799
8800   llvm_unreachable("unknown cast resulting in integral value");
8801 }
8802
8803 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8804   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8805     ComplexValue LV;
8806     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8807       return false;
8808     if (!LV.isComplexInt())
8809       return Error(E);
8810     return Success(LV.getComplexIntReal(), E);
8811   }
8812
8813   return Visit(E->getSubExpr());
8814 }
8815
8816 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8817   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8818     ComplexValue LV;
8819     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8820       return false;
8821     if (!LV.isComplexInt())
8822       return Error(E);
8823     return Success(LV.getComplexIntImag(), E);
8824   }
8825
8826   VisitIgnoredValue(E->getSubExpr());
8827   return Success(0, E);
8828 }
8829
8830 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8831   return Success(E->getPackLength(), E);
8832 }
8833
8834 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8835   return Success(E->getValue(), E);
8836 }
8837
8838 //===----------------------------------------------------------------------===//
8839 // Float Evaluation
8840 //===----------------------------------------------------------------------===//
8841
8842 namespace {
8843 class FloatExprEvaluator
8844   : public ExprEvaluatorBase<FloatExprEvaluator> {
8845   APFloat &Result;
8846 public:
8847   FloatExprEvaluator(EvalInfo &info, APFloat &result)
8848     : ExprEvaluatorBaseTy(info), Result(result) {}
8849
8850   bool Success(const APValue &V, const Expr *e) {
8851     Result = V.getFloat();
8852     return true;
8853   }
8854
8855   bool ZeroInitialization(const Expr *E) {
8856     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8857     return true;
8858   }
8859
8860   bool VisitCallExpr(const CallExpr *E);
8861
8862   bool VisitUnaryOperator(const UnaryOperator *E);
8863   bool VisitBinaryOperator(const BinaryOperator *E);
8864   bool VisitFloatingLiteral(const FloatingLiteral *E);
8865   bool VisitCastExpr(const CastExpr *E);
8866
8867   bool VisitUnaryReal(const UnaryOperator *E);
8868   bool VisitUnaryImag(const UnaryOperator *E);
8869
8870   // FIXME: Missing: array subscript of vector, member of vector
8871 };
8872 } // end anonymous namespace
8873
8874 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8875   assert(E->isRValue() && E->getType()->isRealFloatingType());
8876   return FloatExprEvaluator(Info, Result).Visit(E);
8877 }
8878
8879 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8880                                   QualType ResultTy,
8881                                   const Expr *Arg,
8882                                   bool SNaN,
8883                                   llvm::APFloat &Result) {
8884   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8885   if (!S) return false;
8886
8887   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8888
8889   llvm::APInt fill;
8890
8891   // Treat empty strings as if they were zero.
8892   if (S->getString().empty())
8893     fill = llvm::APInt(32, 0);
8894   else if (S->getString().getAsInteger(0, fill))
8895     return false;
8896
8897   if (Context.getTargetInfo().isNan2008()) {
8898     if (SNaN)
8899       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8900     else
8901       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8902   } else {
8903     // Prior to IEEE 754-2008, architectures were allowed to choose whether
8904     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8905     // a different encoding to what became a standard in 2008, and for pre-
8906     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8907     // sNaN. This is now known as "legacy NaN" encoding.
8908     if (SNaN)
8909       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8910     else
8911       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8912   }
8913
8914   return true;
8915 }
8916
8917 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8918   switch (E->getBuiltinCallee()) {
8919   default:
8920     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8921
8922   case Builtin::BI__builtin_huge_val:
8923   case Builtin::BI__builtin_huge_valf:
8924   case Builtin::BI__builtin_huge_vall:
8925   case Builtin::BI__builtin_inf:
8926   case Builtin::BI__builtin_inff:
8927   case Builtin::BI__builtin_infl: {
8928     const llvm::fltSemantics &Sem =
8929       Info.Ctx.getFloatTypeSemantics(E->getType());
8930     Result = llvm::APFloat::getInf(Sem);
8931     return true;
8932   }
8933
8934   case Builtin::BI__builtin_nans:
8935   case Builtin::BI__builtin_nansf:
8936   case Builtin::BI__builtin_nansl:
8937     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8938                                true, Result))
8939       return Error(E);
8940     return true;
8941
8942   case Builtin::BI__builtin_nan:
8943   case Builtin::BI__builtin_nanf:
8944   case Builtin::BI__builtin_nanl:
8945     // If this is __builtin_nan() turn this into a nan, otherwise we
8946     // can't constant fold it.
8947     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8948                                false, Result))
8949       return Error(E);
8950     return true;
8951
8952   case Builtin::BI__builtin_fabs:
8953   case Builtin::BI__builtin_fabsf:
8954   case Builtin::BI__builtin_fabsl:
8955     if (!EvaluateFloat(E->getArg(0), Result, Info))
8956       return false;
8957
8958     if (Result.isNegative())
8959       Result.changeSign();
8960     return true;
8961
8962   // FIXME: Builtin::BI__builtin_powi
8963   // FIXME: Builtin::BI__builtin_powif
8964   // FIXME: Builtin::BI__builtin_powil
8965
8966   case Builtin::BI__builtin_copysign:
8967   case Builtin::BI__builtin_copysignf:
8968   case Builtin::BI__builtin_copysignl: {
8969     APFloat RHS(0.);
8970     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8971         !EvaluateFloat(E->getArg(1), RHS, Info))
8972       return false;
8973     Result.copySign(RHS);
8974     return true;
8975   }
8976   }
8977 }
8978
8979 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8980   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8981     ComplexValue CV;
8982     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8983       return false;
8984     Result = CV.FloatReal;
8985     return true;
8986   }
8987
8988   return Visit(E->getSubExpr());
8989 }
8990
8991 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8992   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8993     ComplexValue CV;
8994     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8995       return false;
8996     Result = CV.FloatImag;
8997     return true;
8998   }
8999
9000   VisitIgnoredValue(E->getSubExpr());
9001   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9002   Result = llvm::APFloat::getZero(Sem);
9003   return true;
9004 }
9005
9006 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9007   switch (E->getOpcode()) {
9008   default: return Error(E);
9009   case UO_Plus:
9010     return EvaluateFloat(E->getSubExpr(), Result, Info);
9011   case UO_Minus:
9012     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9013       return false;
9014     Result.changeSign();
9015     return true;
9016   }
9017 }
9018
9019 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9020   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9021     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9022
9023   APFloat RHS(0.0);
9024   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9025   if (!LHSOK && !Info.noteFailure())
9026     return false;
9027   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9028          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9029 }
9030
9031 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9032   Result = E->getValue();
9033   return true;
9034 }
9035
9036 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9037   const Expr* SubExpr = E->getSubExpr();
9038
9039   switch (E->getCastKind()) {
9040   default:
9041     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9042
9043   case CK_IntegralToFloating: {
9044     APSInt IntResult;
9045     return EvaluateInteger(SubExpr, IntResult, Info) &&
9046            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9047                                 E->getType(), Result);
9048   }
9049
9050   case CK_FloatingCast: {
9051     if (!Visit(SubExpr))
9052       return false;
9053     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9054                                   Result);
9055   }
9056
9057   case CK_FloatingComplexToReal: {
9058     ComplexValue V;
9059     if (!EvaluateComplex(SubExpr, V, Info))
9060       return false;
9061     Result = V.getComplexFloatReal();
9062     return true;
9063   }
9064   }
9065 }
9066
9067 //===----------------------------------------------------------------------===//
9068 // Complex Evaluation (for float and integer)
9069 //===----------------------------------------------------------------------===//
9070
9071 namespace {
9072 class ComplexExprEvaluator
9073   : public ExprEvaluatorBase<ComplexExprEvaluator> {
9074   ComplexValue &Result;
9075
9076 public:
9077   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9078     : ExprEvaluatorBaseTy(info), Result(Result) {}
9079
9080   bool Success(const APValue &V, const Expr *e) {
9081     Result.setFrom(V);
9082     return true;
9083   }
9084
9085   bool ZeroInitialization(const Expr *E);
9086
9087   //===--------------------------------------------------------------------===//
9088   //                            Visitor Methods
9089   //===--------------------------------------------------------------------===//
9090
9091   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9092   bool VisitCastExpr(const CastExpr *E);
9093   bool VisitBinaryOperator(const BinaryOperator *E);
9094   bool VisitUnaryOperator(const UnaryOperator *E);
9095   bool VisitInitListExpr(const InitListExpr *E);
9096 };
9097 } // end anonymous namespace
9098
9099 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9100                             EvalInfo &Info) {
9101   assert(E->isRValue() && E->getType()->isAnyComplexType());
9102   return ComplexExprEvaluator(Info, Result).Visit(E);
9103 }
9104
9105 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9106   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9107   if (ElemTy->isRealFloatingType()) {
9108     Result.makeComplexFloat();
9109     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9110     Result.FloatReal = Zero;
9111     Result.FloatImag = Zero;
9112   } else {
9113     Result.makeComplexInt();
9114     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9115     Result.IntReal = Zero;
9116     Result.IntImag = Zero;
9117   }
9118   return true;
9119 }
9120
9121 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9122   const Expr* SubExpr = E->getSubExpr();
9123
9124   if (SubExpr->getType()->isRealFloatingType()) {
9125     Result.makeComplexFloat();
9126     APFloat &Imag = Result.FloatImag;
9127     if (!EvaluateFloat(SubExpr, Imag, Info))
9128       return false;
9129
9130     Result.FloatReal = APFloat(Imag.getSemantics());
9131     return true;
9132   } else {
9133     assert(SubExpr->getType()->isIntegerType() &&
9134            "Unexpected imaginary literal.");
9135
9136     Result.makeComplexInt();
9137     APSInt &Imag = Result.IntImag;
9138     if (!EvaluateInteger(SubExpr, Imag, Info))
9139       return false;
9140
9141     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9142     return true;
9143   }
9144 }
9145
9146 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9147
9148   switch (E->getCastKind()) {
9149   case CK_BitCast:
9150   case CK_BaseToDerived:
9151   case CK_DerivedToBase:
9152   case CK_UncheckedDerivedToBase:
9153   case CK_Dynamic:
9154   case CK_ToUnion:
9155   case CK_ArrayToPointerDecay:
9156   case CK_FunctionToPointerDecay:
9157   case CK_NullToPointer:
9158   case CK_NullToMemberPointer:
9159   case CK_BaseToDerivedMemberPointer:
9160   case CK_DerivedToBaseMemberPointer:
9161   case CK_MemberPointerToBoolean:
9162   case CK_ReinterpretMemberPointer:
9163   case CK_ConstructorConversion:
9164   case CK_IntegralToPointer:
9165   case CK_PointerToIntegral:
9166   case CK_PointerToBoolean:
9167   case CK_ToVoid:
9168   case CK_VectorSplat:
9169   case CK_IntegralCast:
9170   case CK_BooleanToSignedIntegral:
9171   case CK_IntegralToBoolean:
9172   case CK_IntegralToFloating:
9173   case CK_FloatingToIntegral:
9174   case CK_FloatingToBoolean:
9175   case CK_FloatingCast:
9176   case CK_CPointerToObjCPointerCast:
9177   case CK_BlockPointerToObjCPointerCast:
9178   case CK_AnyPointerToBlockPointerCast:
9179   case CK_ObjCObjectLValueCast:
9180   case CK_FloatingComplexToReal:
9181   case CK_FloatingComplexToBoolean:
9182   case CK_IntegralComplexToReal:
9183   case CK_IntegralComplexToBoolean:
9184   case CK_ARCProduceObject:
9185   case CK_ARCConsumeObject:
9186   case CK_ARCReclaimReturnedObject:
9187   case CK_ARCExtendBlockObject:
9188   case CK_CopyAndAutoreleaseBlockObject:
9189   case CK_BuiltinFnToFnPtr:
9190   case CK_ZeroToOCLEvent:
9191   case CK_ZeroToOCLQueue:
9192   case CK_NonAtomicToAtomic:
9193   case CK_AddressSpaceConversion:
9194   case CK_IntToOCLSampler:
9195     llvm_unreachable("invalid cast kind for complex value");
9196
9197   case CK_LValueToRValue:
9198   case CK_AtomicToNonAtomic:
9199   case CK_NoOp:
9200     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9201
9202   case CK_Dependent:
9203   case CK_LValueBitCast:
9204   case CK_UserDefinedConversion:
9205     return Error(E);
9206
9207   case CK_FloatingRealToComplex: {
9208     APFloat &Real = Result.FloatReal;
9209     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9210       return false;
9211
9212     Result.makeComplexFloat();
9213     Result.FloatImag = APFloat(Real.getSemantics());
9214     return true;
9215   }
9216
9217   case CK_FloatingComplexCast: {
9218     if (!Visit(E->getSubExpr()))
9219       return false;
9220
9221     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9222     QualType From
9223       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9224
9225     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9226            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9227   }
9228
9229   case CK_FloatingComplexToIntegralComplex: {
9230     if (!Visit(E->getSubExpr()))
9231       return false;
9232
9233     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9234     QualType From
9235       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9236     Result.makeComplexInt();
9237     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9238                                 To, Result.IntReal) &&
9239            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9240                                 To, Result.IntImag);
9241   }
9242
9243   case CK_IntegralRealToComplex: {
9244     APSInt &Real = Result.IntReal;
9245     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9246       return false;
9247
9248     Result.makeComplexInt();
9249     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9250     return true;
9251   }
9252
9253   case CK_IntegralComplexCast: {
9254     if (!Visit(E->getSubExpr()))
9255       return false;
9256
9257     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9258     QualType From
9259       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9260
9261     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9262     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9263     return true;
9264   }
9265
9266   case CK_IntegralComplexToFloatingComplex: {
9267     if (!Visit(E->getSubExpr()))
9268       return false;
9269
9270     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9271     QualType From
9272       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9273     Result.makeComplexFloat();
9274     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9275                                 To, Result.FloatReal) &&
9276            HandleIntToFloatCast(Info, E, From, Result.IntImag,
9277                                 To, Result.FloatImag);
9278   }
9279   }
9280
9281   llvm_unreachable("unknown cast resulting in complex value");
9282 }
9283
9284 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9285   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9286     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9287
9288   // Track whether the LHS or RHS is real at the type system level. When this is
9289   // the case we can simplify our evaluation strategy.
9290   bool LHSReal = false, RHSReal = false;
9291
9292   bool LHSOK;
9293   if (E->getLHS()->getType()->isRealFloatingType()) {
9294     LHSReal = true;
9295     APFloat &Real = Result.FloatReal;
9296     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9297     if (LHSOK) {
9298       Result.makeComplexFloat();
9299       Result.FloatImag = APFloat(Real.getSemantics());
9300     }
9301   } else {
9302     LHSOK = Visit(E->getLHS());
9303   }
9304   if (!LHSOK && !Info.noteFailure())
9305     return false;
9306
9307   ComplexValue RHS;
9308   if (E->getRHS()->getType()->isRealFloatingType()) {
9309     RHSReal = true;
9310     APFloat &Real = RHS.FloatReal;
9311     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9312       return false;
9313     RHS.makeComplexFloat();
9314     RHS.FloatImag = APFloat(Real.getSemantics());
9315   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9316     return false;
9317
9318   assert(!(LHSReal && RHSReal) &&
9319          "Cannot have both operands of a complex operation be real.");
9320   switch (E->getOpcode()) {
9321   default: return Error(E);
9322   case BO_Add:
9323     if (Result.isComplexFloat()) {
9324       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9325                                        APFloat::rmNearestTiesToEven);
9326       if (LHSReal)
9327         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9328       else if (!RHSReal)
9329         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9330                                          APFloat::rmNearestTiesToEven);
9331     } else {
9332       Result.getComplexIntReal() += RHS.getComplexIntReal();
9333       Result.getComplexIntImag() += RHS.getComplexIntImag();
9334     }
9335     break;
9336   case BO_Sub:
9337     if (Result.isComplexFloat()) {
9338       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9339                                             APFloat::rmNearestTiesToEven);
9340       if (LHSReal) {
9341         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9342         Result.getComplexFloatImag().changeSign();
9343       } else if (!RHSReal) {
9344         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9345                                               APFloat::rmNearestTiesToEven);
9346       }
9347     } else {
9348       Result.getComplexIntReal() -= RHS.getComplexIntReal();
9349       Result.getComplexIntImag() -= RHS.getComplexIntImag();
9350     }
9351     break;
9352   case BO_Mul:
9353     if (Result.isComplexFloat()) {
9354       // This is an implementation of complex multiplication according to the
9355       // constraints laid out in C11 Annex G. The implemantion uses the
9356       // following naming scheme:
9357       //   (a + ib) * (c + id)
9358       ComplexValue LHS = Result;
9359       APFloat &A = LHS.getComplexFloatReal();
9360       APFloat &B = LHS.getComplexFloatImag();
9361       APFloat &C = RHS.getComplexFloatReal();
9362       APFloat &D = RHS.getComplexFloatImag();
9363       APFloat &ResR = Result.getComplexFloatReal();
9364       APFloat &ResI = Result.getComplexFloatImag();
9365       if (LHSReal) {
9366         assert(!RHSReal && "Cannot have two real operands for a complex op!");
9367         ResR = A * C;
9368         ResI = A * D;
9369       } else if (RHSReal) {
9370         ResR = C * A;
9371         ResI = C * B;
9372       } else {
9373         // In the fully general case, we need to handle NaNs and infinities
9374         // robustly.
9375         APFloat AC = A * C;
9376         APFloat BD = B * D;
9377         APFloat AD = A * D;
9378         APFloat BC = B * C;
9379         ResR = AC - BD;
9380         ResI = AD + BC;
9381         if (ResR.isNaN() && ResI.isNaN()) {
9382           bool Recalc = false;
9383           if (A.isInfinity() || B.isInfinity()) {
9384             A = APFloat::copySign(
9385                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9386             B = APFloat::copySign(
9387                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9388             if (C.isNaN())
9389               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9390             if (D.isNaN())
9391               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9392             Recalc = true;
9393           }
9394           if (C.isInfinity() || D.isInfinity()) {
9395             C = APFloat::copySign(
9396                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9397             D = APFloat::copySign(
9398                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9399             if (A.isNaN())
9400               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9401             if (B.isNaN())
9402               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9403             Recalc = true;
9404           }
9405           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9406                           AD.isInfinity() || BC.isInfinity())) {
9407             if (A.isNaN())
9408               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9409             if (B.isNaN())
9410               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9411             if (C.isNaN())
9412               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9413             if (D.isNaN())
9414               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9415             Recalc = true;
9416           }
9417           if (Recalc) {
9418             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9419             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9420           }
9421         }
9422       }
9423     } else {
9424       ComplexValue LHS = Result;
9425       Result.getComplexIntReal() =
9426         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9427          LHS.getComplexIntImag() * RHS.getComplexIntImag());
9428       Result.getComplexIntImag() =
9429         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9430          LHS.getComplexIntImag() * RHS.getComplexIntReal());
9431     }
9432     break;
9433   case BO_Div:
9434     if (Result.isComplexFloat()) {
9435       // This is an implementation of complex division according to the
9436       // constraints laid out in C11 Annex G. The implemantion uses the
9437       // following naming scheme:
9438       //   (a + ib) / (c + id)
9439       ComplexValue LHS = Result;
9440       APFloat &A = LHS.getComplexFloatReal();
9441       APFloat &B = LHS.getComplexFloatImag();
9442       APFloat &C = RHS.getComplexFloatReal();
9443       APFloat &D = RHS.getComplexFloatImag();
9444       APFloat &ResR = Result.getComplexFloatReal();
9445       APFloat &ResI = Result.getComplexFloatImag();
9446       if (RHSReal) {
9447         ResR = A / C;
9448         ResI = B / C;
9449       } else {
9450         if (LHSReal) {
9451           // No real optimizations we can do here, stub out with zero.
9452           B = APFloat::getZero(A.getSemantics());
9453         }
9454         int DenomLogB = 0;
9455         APFloat MaxCD = maxnum(abs(C), abs(D));
9456         if (MaxCD.isFinite()) {
9457           DenomLogB = ilogb(MaxCD);
9458           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9459           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9460         }
9461         APFloat Denom = C * C + D * D;
9462         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9463                       APFloat::rmNearestTiesToEven);
9464         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9465                       APFloat::rmNearestTiesToEven);
9466         if (ResR.isNaN() && ResI.isNaN()) {
9467           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9468             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9469             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9470           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9471                      D.isFinite()) {
9472             A = APFloat::copySign(
9473                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9474             B = APFloat::copySign(
9475                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9476             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9477             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9478           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9479             C = APFloat::copySign(
9480                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9481             D = APFloat::copySign(
9482                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9483             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9484             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9485           }
9486         }
9487       }
9488     } else {
9489       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9490         return Error(E, diag::note_expr_divide_by_zero);
9491
9492       ComplexValue LHS = Result;
9493       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9494         RHS.getComplexIntImag() * RHS.getComplexIntImag();
9495       Result.getComplexIntReal() =
9496         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9497          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9498       Result.getComplexIntImag() =
9499         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9500          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9501     }
9502     break;
9503   }
9504
9505   return true;
9506 }
9507
9508 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9509   // Get the operand value into 'Result'.
9510   if (!Visit(E->getSubExpr()))
9511     return false;
9512
9513   switch (E->getOpcode()) {
9514   default:
9515     return Error(E);
9516   case UO_Extension:
9517     return true;
9518   case UO_Plus:
9519     // The result is always just the subexpr.
9520     return true;
9521   case UO_Minus:
9522     if (Result.isComplexFloat()) {
9523       Result.getComplexFloatReal().changeSign();
9524       Result.getComplexFloatImag().changeSign();
9525     }
9526     else {
9527       Result.getComplexIntReal() = -Result.getComplexIntReal();
9528       Result.getComplexIntImag() = -Result.getComplexIntImag();
9529     }
9530     return true;
9531   case UO_Not:
9532     if (Result.isComplexFloat())
9533       Result.getComplexFloatImag().changeSign();
9534     else
9535       Result.getComplexIntImag() = -Result.getComplexIntImag();
9536     return true;
9537   }
9538 }
9539
9540 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9541   if (E->getNumInits() == 2) {
9542     if (E->getType()->isComplexType()) {
9543       Result.makeComplexFloat();
9544       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9545         return false;
9546       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9547         return false;
9548     } else {
9549       Result.makeComplexInt();
9550       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9551         return false;
9552       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9553         return false;
9554     }
9555     return true;
9556   }
9557   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9558 }
9559
9560 //===----------------------------------------------------------------------===//
9561 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9562 // implicit conversion.
9563 //===----------------------------------------------------------------------===//
9564
9565 namespace {
9566 class AtomicExprEvaluator :
9567     public ExprEvaluatorBase<AtomicExprEvaluator> {
9568   APValue &Result;
9569 public:
9570   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9571       : ExprEvaluatorBaseTy(Info), Result(Result) {}
9572
9573   bool Success(const APValue &V, const Expr *E) {
9574     Result = V;
9575     return true;
9576   }
9577
9578   bool ZeroInitialization(const Expr *E) {
9579     ImplicitValueInitExpr VIE(
9580         E->getType()->castAs<AtomicType>()->getValueType());
9581     return Evaluate(Result, Info, &VIE);
9582   }
9583
9584   bool VisitCastExpr(const CastExpr *E) {
9585     switch (E->getCastKind()) {
9586     default:
9587       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9588     case CK_NonAtomicToAtomic:
9589       return Evaluate(Result, Info, E->getSubExpr());
9590     }
9591   }
9592 };
9593 } // end anonymous namespace
9594
9595 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9596   assert(E->isRValue() && E->getType()->isAtomicType());
9597   return AtomicExprEvaluator(Info, Result).Visit(E);
9598 }
9599
9600 //===----------------------------------------------------------------------===//
9601 // Void expression evaluation, primarily for a cast to void on the LHS of a
9602 // comma operator
9603 //===----------------------------------------------------------------------===//
9604
9605 namespace {
9606 class VoidExprEvaluator
9607   : public ExprEvaluatorBase<VoidExprEvaluator> {
9608 public:
9609   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9610
9611   bool Success(const APValue &V, const Expr *e) { return true; }
9612
9613   bool VisitCastExpr(const CastExpr *E) {
9614     switch (E->getCastKind()) {
9615     default:
9616       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9617     case CK_ToVoid:
9618       VisitIgnoredValue(E->getSubExpr());
9619       return true;
9620     }
9621   }
9622
9623   bool VisitCallExpr(const CallExpr *E) {
9624     switch (E->getBuiltinCallee()) {
9625     default:
9626       return ExprEvaluatorBaseTy::VisitCallExpr(E);
9627     case Builtin::BI__assume:
9628     case Builtin::BI__builtin_assume:
9629       // The argument is not evaluated!
9630       return true;
9631     }
9632   }
9633 };
9634 } // end anonymous namespace
9635
9636 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9637   assert(E->isRValue() && E->getType()->isVoidType());
9638   return VoidExprEvaluator(Info).Visit(E);
9639 }
9640
9641 //===----------------------------------------------------------------------===//
9642 // Top level Expr::EvaluateAsRValue method.
9643 //===----------------------------------------------------------------------===//
9644
9645 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9646   // In C, function designators are not lvalues, but we evaluate them as if they
9647   // are.
9648   QualType T = E->getType();
9649   if (E->isGLValue() || T->isFunctionType()) {
9650     LValue LV;
9651     if (!EvaluateLValue(E, LV, Info))
9652       return false;
9653     LV.moveInto(Result);
9654   } else if (T->isVectorType()) {
9655     if (!EvaluateVector(E, Result, Info))
9656       return false;
9657   } else if (T->isIntegralOrEnumerationType()) {
9658     if (!IntExprEvaluator(Info, Result).Visit(E))
9659       return false;
9660   } else if (T->hasPointerRepresentation()) {
9661     LValue LV;
9662     if (!EvaluatePointer(E, LV, Info))
9663       return false;
9664     LV.moveInto(Result);
9665   } else if (T->isRealFloatingType()) {
9666     llvm::APFloat F(0.0);
9667     if (!EvaluateFloat(E, F, Info))
9668       return false;
9669     Result = APValue(F);
9670   } else if (T->isAnyComplexType()) {
9671     ComplexValue C;
9672     if (!EvaluateComplex(E, C, Info))
9673       return false;
9674     C.moveInto(Result);
9675   } else if (T->isMemberPointerType()) {
9676     MemberPtr P;
9677     if (!EvaluateMemberPointer(E, P, Info))
9678       return false;
9679     P.moveInto(Result);
9680     return true;
9681   } else if (T->isArrayType()) {
9682     LValue LV;
9683     LV.set(E, Info.CurrentCall->Index);
9684     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9685     if (!EvaluateArray(E, LV, Value, Info))
9686       return false;
9687     Result = Value;
9688   } else if (T->isRecordType()) {
9689     LValue LV;
9690     LV.set(E, Info.CurrentCall->Index);
9691     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9692     if (!EvaluateRecord(E, LV, Value, Info))
9693       return false;
9694     Result = Value;
9695   } else if (T->isVoidType()) {
9696     if (!Info.getLangOpts().CPlusPlus11)
9697       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9698         << E->getType();
9699     if (!EvaluateVoid(E, Info))
9700       return false;
9701   } else if (T->isAtomicType()) {
9702     if (!EvaluateAtomic(E, Result, Info))
9703       return false;
9704   } else if (Info.getLangOpts().CPlusPlus11) {
9705     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9706     return false;
9707   } else {
9708     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9709     return false;
9710   }
9711
9712   return true;
9713 }
9714
9715 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9716 /// cases, the in-place evaluation is essential, since later initializers for
9717 /// an object can indirectly refer to subobjects which were initialized earlier.
9718 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9719                             const Expr *E, bool AllowNonLiteralTypes) {
9720   assert(!E->isValueDependent());
9721
9722   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9723     return false;
9724
9725   if (E->isRValue()) {
9726     // Evaluate arrays and record types in-place, so that later initializers can
9727     // refer to earlier-initialized members of the object.
9728     if (E->getType()->isArrayType())
9729       return EvaluateArray(E, This, Result, Info);
9730     else if (E->getType()->isRecordType())
9731       return EvaluateRecord(E, This, Result, Info);
9732   }
9733
9734   // For any other type, in-place evaluation is unimportant.
9735   return Evaluate(Result, Info, E);
9736 }
9737
9738 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9739 /// lvalue-to-rvalue cast if it is an lvalue.
9740 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9741   if (E->getType().isNull())
9742     return false;
9743
9744   if (!CheckLiteralType(Info, E))
9745     return false;
9746
9747   if (!::Evaluate(Result, Info, E))
9748     return false;
9749
9750   if (E->isGLValue()) {
9751     LValue LV;
9752     LV.setFrom(Info.Ctx, Result);
9753     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9754       return false;
9755   }
9756
9757   // Check this core constant expression is a constant expression.
9758   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9759 }
9760
9761 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9762                                  const ASTContext &Ctx, bool &IsConst) {
9763   // Fast-path evaluations of integer literals, since we sometimes see files
9764   // containing vast quantities of these.
9765   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9766     Result.Val = APValue(APSInt(L->getValue(),
9767                                 L->getType()->isUnsignedIntegerType()));
9768     IsConst = true;
9769     return true;
9770   }
9771
9772   // This case should be rare, but we need to check it before we check on
9773   // the type below.
9774   if (Exp->getType().isNull()) {
9775     IsConst = false;
9776     return true;
9777   }
9778   
9779   // FIXME: Evaluating values of large array and record types can cause
9780   // performance problems. Only do so in C++11 for now.
9781   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9782                           Exp->getType()->isRecordType()) &&
9783       !Ctx.getLangOpts().CPlusPlus11) {
9784     IsConst = false;
9785     return true;
9786   }
9787   return false;
9788 }
9789
9790
9791 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9792 /// any crazy technique (that has nothing to do with language standards) that
9793 /// we want to.  If this function returns true, it returns the folded constant
9794 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9795 /// will be applied to the result.
9796 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9797   bool IsConst;
9798   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9799     return IsConst;
9800   
9801   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9802   return ::EvaluateAsRValue(Info, this, Result.Val);
9803 }
9804
9805 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9806                                       const ASTContext &Ctx) const {
9807   EvalResult Scratch;
9808   return EvaluateAsRValue(Scratch, Ctx) &&
9809          HandleConversionToBool(Scratch.Val, Result);
9810 }
9811
9812 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9813                                       Expr::SideEffectsKind SEK) {
9814   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9815          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9816 }
9817
9818 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9819                          SideEffectsKind AllowSideEffects) const {
9820   if (!getType()->isIntegralOrEnumerationType())
9821     return false;
9822
9823   EvalResult ExprResult;
9824   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9825       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9826     return false;
9827
9828   Result = ExprResult.Val.getInt();
9829   return true;
9830 }
9831
9832 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9833                            SideEffectsKind AllowSideEffects) const {
9834   if (!getType()->isRealFloatingType())
9835     return false;
9836
9837   EvalResult ExprResult;
9838   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9839       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9840     return false;
9841
9842   Result = ExprResult.Val.getFloat();
9843   return true;
9844 }
9845
9846 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9847   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9848
9849   LValue LV;
9850   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9851       !CheckLValueConstantExpression(Info, getExprLoc(),
9852                                      Ctx.getLValueReferenceType(getType()), LV))
9853     return false;
9854
9855   LV.moveInto(Result.Val);
9856   return true;
9857 }
9858
9859 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9860                                  const VarDecl *VD,
9861                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9862   // FIXME: Evaluating initializers for large array and record types can cause
9863   // performance problems. Only do so in C++11 for now.
9864   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9865       !Ctx.getLangOpts().CPlusPlus11)
9866     return false;
9867
9868   Expr::EvalStatus EStatus;
9869   EStatus.Diag = &Notes;
9870
9871   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9872                                       ? EvalInfo::EM_ConstantExpression
9873                                       : EvalInfo::EM_ConstantFold);
9874   InitInfo.setEvaluatingDecl(VD, Value);
9875
9876   LValue LVal;
9877   LVal.set(VD);
9878
9879   // C++11 [basic.start.init]p2:
9880   //  Variables with static storage duration or thread storage duration shall be
9881   //  zero-initialized before any other initialization takes place.
9882   // This behavior is not present in C.
9883   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9884       !VD->getType()->isReferenceType()) {
9885     ImplicitValueInitExpr VIE(VD->getType());
9886     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9887                          /*AllowNonLiteralTypes=*/true))
9888       return false;
9889   }
9890
9891   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9892                        /*AllowNonLiteralTypes=*/true) ||
9893       EStatus.HasSideEffects)
9894     return false;
9895
9896   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9897                                  Value);
9898 }
9899
9900 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9901 /// constant folded, but discard the result.
9902 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9903   EvalResult Result;
9904   return EvaluateAsRValue(Result, Ctx) &&
9905          !hasUnacceptableSideEffect(Result, SEK);
9906 }
9907
9908 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9909                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9910   EvalResult EvalResult;
9911   EvalResult.Diag = Diag;
9912   bool Result = EvaluateAsRValue(EvalResult, Ctx);
9913   (void)Result;
9914   assert(Result && "Could not evaluate expression");
9915   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9916
9917   return EvalResult.Val.getInt();
9918 }
9919
9920 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9921   bool IsConst;
9922   EvalResult EvalResult;
9923   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9924     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9925     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9926   }
9927 }
9928
9929 bool Expr::EvalResult::isGlobalLValue() const {
9930   assert(Val.isLValue());
9931   return IsGlobalLValue(Val.getLValueBase());
9932 }
9933
9934
9935 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9936 /// an integer constant expression.
9937
9938 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9939 /// comma, etc
9940
9941 // CheckICE - This function does the fundamental ICE checking: the returned
9942 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9943 // and a (possibly null) SourceLocation indicating the location of the problem.
9944 //
9945 // Note that to reduce code duplication, this helper does no evaluation
9946 // itself; the caller checks whether the expression is evaluatable, and
9947 // in the rare cases where CheckICE actually cares about the evaluated
9948 // value, it calls into Evalute.
9949
9950 namespace {
9951
9952 enum ICEKind {
9953   /// This expression is an ICE.
9954   IK_ICE,
9955   /// This expression is not an ICE, but if it isn't evaluated, it's
9956   /// a legal subexpression for an ICE. This return value is used to handle
9957   /// the comma operator in C99 mode, and non-constant subexpressions.
9958   IK_ICEIfUnevaluated,
9959   /// This expression is not an ICE, and is not a legal subexpression for one.
9960   IK_NotICE
9961 };
9962
9963 struct ICEDiag {
9964   ICEKind Kind;
9965   SourceLocation Loc;
9966
9967   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9968 };
9969
9970 }
9971
9972 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9973
9974 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9975
9976 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9977   Expr::EvalResult EVResult;
9978   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9979       !EVResult.Val.isInt())
9980     return ICEDiag(IK_NotICE, E->getLocStart());
9981
9982   return NoDiag();
9983 }
9984
9985 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9986   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9987   if (!E->getType()->isIntegralOrEnumerationType())
9988     return ICEDiag(IK_NotICE, E->getLocStart());
9989
9990   switch (E->getStmtClass()) {
9991 #define ABSTRACT_STMT(Node)
9992 #define STMT(Node, Base) case Expr::Node##Class:
9993 #define EXPR(Node, Base)
9994 #include "clang/AST/StmtNodes.inc"
9995   case Expr::PredefinedExprClass:
9996   case Expr::FloatingLiteralClass:
9997   case Expr::ImaginaryLiteralClass:
9998   case Expr::StringLiteralClass:
9999   case Expr::ArraySubscriptExprClass:
10000   case Expr::OMPArraySectionExprClass:
10001   case Expr::MemberExprClass:
10002   case Expr::CompoundAssignOperatorClass:
10003   case Expr::CompoundLiteralExprClass:
10004   case Expr::ExtVectorElementExprClass:
10005   case Expr::DesignatedInitExprClass:
10006   case Expr::ArrayInitLoopExprClass:
10007   case Expr::ArrayInitIndexExprClass:
10008   case Expr::NoInitExprClass:
10009   case Expr::DesignatedInitUpdateExprClass:
10010   case Expr::ImplicitValueInitExprClass:
10011   case Expr::ParenListExprClass:
10012   case Expr::VAArgExprClass:
10013   case Expr::AddrLabelExprClass:
10014   case Expr::StmtExprClass:
10015   case Expr::CXXMemberCallExprClass:
10016   case Expr::CUDAKernelCallExprClass:
10017   case Expr::CXXDynamicCastExprClass:
10018   case Expr::CXXTypeidExprClass:
10019   case Expr::CXXUuidofExprClass:
10020   case Expr::MSPropertyRefExprClass:
10021   case Expr::MSPropertySubscriptExprClass:
10022   case Expr::CXXNullPtrLiteralExprClass:
10023   case Expr::UserDefinedLiteralClass:
10024   case Expr::CXXThisExprClass:
10025   case Expr::CXXThrowExprClass:
10026   case Expr::CXXNewExprClass:
10027   case Expr::CXXDeleteExprClass:
10028   case Expr::CXXPseudoDestructorExprClass:
10029   case Expr::UnresolvedLookupExprClass:
10030   case Expr::TypoExprClass:
10031   case Expr::DependentScopeDeclRefExprClass:
10032   case Expr::CXXConstructExprClass:
10033   case Expr::CXXInheritedCtorInitExprClass:
10034   case Expr::CXXStdInitializerListExprClass:
10035   case Expr::CXXBindTemporaryExprClass:
10036   case Expr::ExprWithCleanupsClass:
10037   case Expr::CXXTemporaryObjectExprClass:
10038   case Expr::CXXUnresolvedConstructExprClass:
10039   case Expr::CXXDependentScopeMemberExprClass:
10040   case Expr::UnresolvedMemberExprClass:
10041   case Expr::ObjCStringLiteralClass:
10042   case Expr::ObjCBoxedExprClass:
10043   case Expr::ObjCArrayLiteralClass:
10044   case Expr::ObjCDictionaryLiteralClass:
10045   case Expr::ObjCEncodeExprClass:
10046   case Expr::ObjCMessageExprClass:
10047   case Expr::ObjCSelectorExprClass:
10048   case Expr::ObjCProtocolExprClass:
10049   case Expr::ObjCIvarRefExprClass:
10050   case Expr::ObjCPropertyRefExprClass:
10051   case Expr::ObjCSubscriptRefExprClass:
10052   case Expr::ObjCIsaExprClass:
10053   case Expr::ObjCAvailabilityCheckExprClass:
10054   case Expr::ShuffleVectorExprClass:
10055   case Expr::ConvertVectorExprClass:
10056   case Expr::BlockExprClass:
10057   case Expr::NoStmtClass:
10058   case Expr::OpaqueValueExprClass:
10059   case Expr::PackExpansionExprClass:
10060   case Expr::SubstNonTypeTemplateParmPackExprClass:
10061   case Expr::FunctionParmPackExprClass:
10062   case Expr::AsTypeExprClass:
10063   case Expr::ObjCIndirectCopyRestoreExprClass:
10064   case Expr::MaterializeTemporaryExprClass:
10065   case Expr::PseudoObjectExprClass:
10066   case Expr::AtomicExprClass:
10067   case Expr::LambdaExprClass:
10068   case Expr::CXXFoldExprClass:
10069   case Expr::CoawaitExprClass:
10070   case Expr::CoyieldExprClass:
10071     return ICEDiag(IK_NotICE, E->getLocStart());
10072
10073   case Expr::InitListExprClass: {
10074     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10075     // form "T x = { a };" is equivalent to "T x = a;".
10076     // Unless we're initializing a reference, T is a scalar as it is known to be
10077     // of integral or enumeration type.
10078     if (E->isRValue())
10079       if (cast<InitListExpr>(E)->getNumInits() == 1)
10080         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10081     return ICEDiag(IK_NotICE, E->getLocStart());
10082   }
10083
10084   case Expr::SizeOfPackExprClass:
10085   case Expr::GNUNullExprClass:
10086     // GCC considers the GNU __null value to be an integral constant expression.
10087     return NoDiag();
10088
10089   case Expr::SubstNonTypeTemplateParmExprClass:
10090     return
10091       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10092
10093   case Expr::ParenExprClass:
10094     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10095   case Expr::GenericSelectionExprClass:
10096     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10097   case Expr::IntegerLiteralClass:
10098   case Expr::CharacterLiteralClass:
10099   case Expr::ObjCBoolLiteralExprClass:
10100   case Expr::CXXBoolLiteralExprClass:
10101   case Expr::CXXScalarValueInitExprClass:
10102   case Expr::TypeTraitExprClass:
10103   case Expr::ArrayTypeTraitExprClass:
10104   case Expr::ExpressionTraitExprClass:
10105   case Expr::CXXNoexceptExprClass:
10106     return NoDiag();
10107   case Expr::CallExprClass:
10108   case Expr::CXXOperatorCallExprClass: {
10109     // C99 6.6/3 allows function calls within unevaluated subexpressions of
10110     // constant expressions, but they can never be ICEs because an ICE cannot
10111     // contain an operand of (pointer to) function type.
10112     const CallExpr *CE = cast<CallExpr>(E);
10113     if (CE->getBuiltinCallee())
10114       return CheckEvalInICE(E, Ctx);
10115     return ICEDiag(IK_NotICE, E->getLocStart());
10116   }
10117   case Expr::DeclRefExprClass: {
10118     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10119       return NoDiag();
10120     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10121     if (Ctx.getLangOpts().CPlusPlus &&
10122         D && IsConstNonVolatile(D->getType())) {
10123       // Parameter variables are never constants.  Without this check,
10124       // getAnyInitializer() can find a default argument, which leads
10125       // to chaos.
10126       if (isa<ParmVarDecl>(D))
10127         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10128
10129       // C++ 7.1.5.1p2
10130       //   A variable of non-volatile const-qualified integral or enumeration
10131       //   type initialized by an ICE can be used in ICEs.
10132       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10133         if (!Dcl->getType()->isIntegralOrEnumerationType())
10134           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10135
10136         const VarDecl *VD;
10137         // Look for a declaration of this variable that has an initializer, and
10138         // check whether it is an ICE.
10139         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10140           return NoDiag();
10141         else
10142           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10143       }
10144     }
10145     return ICEDiag(IK_NotICE, E->getLocStart());
10146   }
10147   case Expr::UnaryOperatorClass: {
10148     const UnaryOperator *Exp = cast<UnaryOperator>(E);
10149     switch (Exp->getOpcode()) {
10150     case UO_PostInc:
10151     case UO_PostDec:
10152     case UO_PreInc:
10153     case UO_PreDec:
10154     case UO_AddrOf:
10155     case UO_Deref:
10156     case UO_Coawait:
10157       // C99 6.6/3 allows increment and decrement within unevaluated
10158       // subexpressions of constant expressions, but they can never be ICEs
10159       // because an ICE cannot contain an lvalue operand.
10160       return ICEDiag(IK_NotICE, E->getLocStart());
10161     case UO_Extension:
10162     case UO_LNot:
10163     case UO_Plus:
10164     case UO_Minus:
10165     case UO_Not:
10166     case UO_Real:
10167     case UO_Imag:
10168       return CheckICE(Exp->getSubExpr(), Ctx);
10169     }
10170
10171     // OffsetOf falls through here.
10172   }
10173   case Expr::OffsetOfExprClass: {
10174     // Note that per C99, offsetof must be an ICE. And AFAIK, using
10175     // EvaluateAsRValue matches the proposed gcc behavior for cases like
10176     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
10177     // compliance: we should warn earlier for offsetof expressions with
10178     // array subscripts that aren't ICEs, and if the array subscripts
10179     // are ICEs, the value of the offsetof must be an integer constant.
10180     return CheckEvalInICE(E, Ctx);
10181   }
10182   case Expr::UnaryExprOrTypeTraitExprClass: {
10183     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10184     if ((Exp->getKind() ==  UETT_SizeOf) &&
10185         Exp->getTypeOfArgument()->isVariableArrayType())
10186       return ICEDiag(IK_NotICE, E->getLocStart());
10187     return NoDiag();
10188   }
10189   case Expr::BinaryOperatorClass: {
10190     const BinaryOperator *Exp = cast<BinaryOperator>(E);
10191     switch (Exp->getOpcode()) {
10192     case BO_PtrMemD:
10193     case BO_PtrMemI:
10194     case BO_Assign:
10195     case BO_MulAssign:
10196     case BO_DivAssign:
10197     case BO_RemAssign:
10198     case BO_AddAssign:
10199     case BO_SubAssign:
10200     case BO_ShlAssign:
10201     case BO_ShrAssign:
10202     case BO_AndAssign:
10203     case BO_XorAssign:
10204     case BO_OrAssign:
10205       // C99 6.6/3 allows assignments within unevaluated subexpressions of
10206       // constant expressions, but they can never be ICEs because an ICE cannot
10207       // contain an lvalue operand.
10208       return ICEDiag(IK_NotICE, E->getLocStart());
10209
10210     case BO_Mul:
10211     case BO_Div:
10212     case BO_Rem:
10213     case BO_Add:
10214     case BO_Sub:
10215     case BO_Shl:
10216     case BO_Shr:
10217     case BO_LT:
10218     case BO_GT:
10219     case BO_LE:
10220     case BO_GE:
10221     case BO_EQ:
10222     case BO_NE:
10223     case BO_And:
10224     case BO_Xor:
10225     case BO_Or:
10226     case BO_Comma: {
10227       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10228       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10229       if (Exp->getOpcode() == BO_Div ||
10230           Exp->getOpcode() == BO_Rem) {
10231         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10232         // we don't evaluate one.
10233         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10234           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10235           if (REval == 0)
10236             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10237           if (REval.isSigned() && REval.isAllOnesValue()) {
10238             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10239             if (LEval.isMinSignedValue())
10240               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10241           }
10242         }
10243       }
10244       if (Exp->getOpcode() == BO_Comma) {
10245         if (Ctx.getLangOpts().C99) {
10246           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10247           // if it isn't evaluated.
10248           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10249             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10250         } else {
10251           // In both C89 and C++, commas in ICEs are illegal.
10252           return ICEDiag(IK_NotICE, E->getLocStart());
10253         }
10254       }
10255       return Worst(LHSResult, RHSResult);
10256     }
10257     case BO_LAnd:
10258     case BO_LOr: {
10259       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10260       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10261       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10262         // Rare case where the RHS has a comma "side-effect"; we need
10263         // to actually check the condition to see whether the side
10264         // with the comma is evaluated.
10265         if ((Exp->getOpcode() == BO_LAnd) !=
10266             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10267           return RHSResult;
10268         return NoDiag();
10269       }
10270
10271       return Worst(LHSResult, RHSResult);
10272     }
10273     }
10274   }
10275   case Expr::ImplicitCastExprClass:
10276   case Expr::CStyleCastExprClass:
10277   case Expr::CXXFunctionalCastExprClass:
10278   case Expr::CXXStaticCastExprClass:
10279   case Expr::CXXReinterpretCastExprClass:
10280   case Expr::CXXConstCastExprClass:
10281   case Expr::ObjCBridgedCastExprClass: {
10282     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10283     if (isa<ExplicitCastExpr>(E)) {
10284       if (const FloatingLiteral *FL
10285             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10286         unsigned DestWidth = Ctx.getIntWidth(E->getType());
10287         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10288         APSInt IgnoredVal(DestWidth, !DestSigned);
10289         bool Ignored;
10290         // If the value does not fit in the destination type, the behavior is
10291         // undefined, so we are not required to treat it as a constant
10292         // expression.
10293         if (FL->getValue().convertToInteger(IgnoredVal,
10294                                             llvm::APFloat::rmTowardZero,
10295                                             &Ignored) & APFloat::opInvalidOp)
10296           return ICEDiag(IK_NotICE, E->getLocStart());
10297         return NoDiag();
10298       }
10299     }
10300     switch (cast<CastExpr>(E)->getCastKind()) {
10301     case CK_LValueToRValue:
10302     case CK_AtomicToNonAtomic:
10303     case CK_NonAtomicToAtomic:
10304     case CK_NoOp:
10305     case CK_IntegralToBoolean:
10306     case CK_IntegralCast:
10307       return CheckICE(SubExpr, Ctx);
10308     default:
10309       return ICEDiag(IK_NotICE, E->getLocStart());
10310     }
10311   }
10312   case Expr::BinaryConditionalOperatorClass: {
10313     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10314     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10315     if (CommonResult.Kind == IK_NotICE) return CommonResult;
10316     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10317     if (FalseResult.Kind == IK_NotICE) return FalseResult;
10318     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10319     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10320         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10321     return FalseResult;
10322   }
10323   case Expr::ConditionalOperatorClass: {
10324     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10325     // If the condition (ignoring parens) is a __builtin_constant_p call,
10326     // then only the true side is actually considered in an integer constant
10327     // expression, and it is fully evaluated.  This is an important GNU
10328     // extension.  See GCC PR38377 for discussion.
10329     if (const CallExpr *CallCE
10330         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10331       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10332         return CheckEvalInICE(E, Ctx);
10333     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10334     if (CondResult.Kind == IK_NotICE)
10335       return CondResult;
10336
10337     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10338     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10339
10340     if (TrueResult.Kind == IK_NotICE)
10341       return TrueResult;
10342     if (FalseResult.Kind == IK_NotICE)
10343       return FalseResult;
10344     if (CondResult.Kind == IK_ICEIfUnevaluated)
10345       return CondResult;
10346     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10347       return NoDiag();
10348     // Rare case where the diagnostics depend on which side is evaluated
10349     // Note that if we get here, CondResult is 0, and at least one of
10350     // TrueResult and FalseResult is non-zero.
10351     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10352       return FalseResult;
10353     return TrueResult;
10354   }
10355   case Expr::CXXDefaultArgExprClass:
10356     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10357   case Expr::CXXDefaultInitExprClass:
10358     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10359   case Expr::ChooseExprClass: {
10360     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10361   }
10362   }
10363
10364   llvm_unreachable("Invalid StmtClass!");
10365 }
10366
10367 /// Evaluate an expression as a C++11 integral constant expression.
10368 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10369                                                     const Expr *E,
10370                                                     llvm::APSInt *Value,
10371                                                     SourceLocation *Loc) {
10372   if (!E->getType()->isIntegralOrEnumerationType()) {
10373     if (Loc) *Loc = E->getExprLoc();
10374     return false;
10375   }
10376
10377   APValue Result;
10378   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10379     return false;
10380
10381   if (!Result.isInt()) {
10382     if (Loc) *Loc = E->getExprLoc();
10383     return false;
10384   }
10385
10386   if (Value) *Value = Result.getInt();
10387   return true;
10388 }
10389
10390 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10391                                  SourceLocation *Loc) const {
10392   if (Ctx.getLangOpts().CPlusPlus11)
10393     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10394
10395   ICEDiag D = CheckICE(this, Ctx);
10396   if (D.Kind != IK_ICE) {
10397     if (Loc) *Loc = D.Loc;
10398     return false;
10399   }
10400   return true;
10401 }
10402
10403 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10404                                  SourceLocation *Loc, bool isEvaluated) const {
10405   if (Ctx.getLangOpts().CPlusPlus11)
10406     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10407
10408   if (!isIntegerConstantExpr(Ctx, Loc))
10409     return false;
10410   // The only possible side-effects here are due to UB discovered in the
10411   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10412   // required to treat the expression as an ICE, so we produce the folded
10413   // value.
10414   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10415     llvm_unreachable("ICE cannot be evaluated!");
10416   return true;
10417 }
10418
10419 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10420   return CheckICE(this, Ctx).Kind == IK_ICE;
10421 }
10422
10423 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10424                                SourceLocation *Loc) const {
10425   // We support this checking in C++98 mode in order to diagnose compatibility
10426   // issues.
10427   assert(Ctx.getLangOpts().CPlusPlus);
10428
10429   // Build evaluation settings.
10430   Expr::EvalStatus Status;
10431   SmallVector<PartialDiagnosticAt, 8> Diags;
10432   Status.Diag = &Diags;
10433   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10434
10435   APValue Scratch;
10436   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10437
10438   if (!Diags.empty()) {
10439     IsConstExpr = false;
10440     if (Loc) *Loc = Diags[0].first;
10441   } else if (!IsConstExpr) {
10442     // FIXME: This shouldn't happen.
10443     if (Loc) *Loc = getExprLoc();
10444   }
10445
10446   return IsConstExpr;
10447 }
10448
10449 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10450                                     const FunctionDecl *Callee,
10451                                     ArrayRef<const Expr*> Args,
10452                                     const Expr *This) const {
10453   Expr::EvalStatus Status;
10454   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10455
10456   LValue ThisVal;
10457   const LValue *ThisPtr = nullptr;
10458   if (This) {
10459 #ifndef NDEBUG
10460     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10461     assert(MD && "Don't provide `this` for non-methods.");
10462     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10463 #endif
10464     if (EvaluateObjectArgument(Info, This, ThisVal))
10465       ThisPtr = &ThisVal;
10466     if (Info.EvalStatus.HasSideEffects)
10467       return false;
10468   }
10469
10470   ArgVector ArgValues(Args.size());
10471   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10472        I != E; ++I) {
10473     if ((*I)->isValueDependent() ||
10474         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10475       // If evaluation fails, throw away the argument entirely.
10476       ArgValues[I - Args.begin()] = APValue();
10477     if (Info.EvalStatus.HasSideEffects)
10478       return false;
10479   }
10480
10481   // Build fake call to Callee.
10482   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10483                        ArgValues.data());
10484   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10485 }
10486
10487 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10488                                    SmallVectorImpl<
10489                                      PartialDiagnosticAt> &Diags) {
10490   // FIXME: It would be useful to check constexpr function templates, but at the
10491   // moment the constant expression evaluator cannot cope with the non-rigorous
10492   // ASTs which we build for dependent expressions.
10493   if (FD->isDependentContext())
10494     return true;
10495
10496   Expr::EvalStatus Status;
10497   Status.Diag = &Diags;
10498
10499   EvalInfo Info(FD->getASTContext(), Status,
10500                 EvalInfo::EM_PotentialConstantExpression);
10501
10502   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10503   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10504
10505   // Fabricate an arbitrary expression on the stack and pretend that it
10506   // is a temporary being used as the 'this' pointer.
10507   LValue This;
10508   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10509   This.set(&VIE, Info.CurrentCall->Index);
10510
10511   ArrayRef<const Expr*> Args;
10512
10513   APValue Scratch;
10514   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10515     // Evaluate the call as a constant initializer, to allow the construction
10516     // of objects of non-literal types.
10517     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10518     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10519   } else {
10520     SourceLocation Loc = FD->getLocation();
10521     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10522                        Args, FD->getBody(), Info, Scratch, nullptr);
10523   }
10524
10525   return Diags.empty();
10526 }
10527
10528 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10529                                               const FunctionDecl *FD,
10530                                               SmallVectorImpl<
10531                                                 PartialDiagnosticAt> &Diags) {
10532   Expr::EvalStatus Status;
10533   Status.Diag = &Diags;
10534
10535   EvalInfo Info(FD->getASTContext(), Status,
10536                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10537
10538   // Fabricate a call stack frame to give the arguments a plausible cover story.
10539   ArrayRef<const Expr*> Args;
10540   ArgVector ArgValues(0);
10541   bool Success = EvaluateArgs(Args, ArgValues, Info);
10542   (void)Success;
10543   assert(Success &&
10544          "Failed to set up arguments for potential constant evaluation");
10545   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10546
10547   APValue ResultScratch;
10548   Evaluate(ResultScratch, Info, E);
10549   return Diags.empty();
10550 }
10551
10552 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10553                                  unsigned Type) const {
10554   if (!getType()->isPointerType())
10555     return false;
10556
10557   Expr::EvalStatus Status;
10558   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10559   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10560 }