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