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