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