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