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/OSLog.h"
43 #include "clang/AST/RecordLayout.h"
44 #include "clang/AST/StmtVisitor.h"
45 #include "clang/AST/TypeLoc.h"
46 #include "clang/Basic/Builtins.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "llvm/Support/SaveAndRestore.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <cstring>
51 #include <functional>
52 
53 #define DEBUG_TYPE "exprconstant"
54 
55 using namespace clang;
56 using llvm::APSInt;
57 using llvm::APFloat;
58 
59 static bool IsGlobalLValue(APValue::LValueBase B);
60 
61 namespace {
62   struct LValue;
63   struct CallStackFrame;
64   struct EvalInfo;
65 
66   static QualType getType(APValue::LValueBase B) {
67     if (!B) return QualType();
68     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
69       // FIXME: It's unclear where we're supposed to take the type from, and
70       // this actually matters for arrays of unknown bound. Eg:
71       //
72       // extern int arr[]; void f() { extern int arr[3]; };
73       // constexpr int *p = &arr[1]; // valid?
74       //
75       // For now, we take the array bound from the most recent declaration.
76       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78         QualType T = Redecl->getType();
79         if (!T->isIncompleteArrayType())
80           return T;
81       }
82       return D->getType();
83     }
84 
85     const Expr *Base = B.get<const Expr*>();
86 
87     // For a materialized temporary, the type of the temporary we materialized
88     // may not be the type of the expression.
89     if (const MaterializeTemporaryExpr *MTE =
90             dyn_cast<MaterializeTemporaryExpr>(Base)) {
91       SmallVector<const Expr *, 2> CommaLHSs;
92       SmallVector<SubobjectAdjustment, 2> Adjustments;
93       const Expr *Temp = MTE->GetTemporaryExpr();
94       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95                                                                Adjustments);
96       // Keep any cv-qualifiers from the reference if we generated a temporary
97       // for it directly. Otherwise use the type after adjustment.
98       if (!Adjustments.empty())
99         return Inner->getType();
100     }
101 
102     return Base->getType();
103   }
104 
105   /// Get an LValue path entry, which is known to not be an array index, as a
106   /// field or base class.
107   static
108   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
109     APValue::BaseOrMemberType Value;
110     Value.setFromOpaqueValue(E.BaseOrMember);
111     return Value;
112   }
113 
114   /// Get an LValue path entry, which is known to not be an array index, as a
115   /// field declaration.
116   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
117     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
118   }
119   /// Get an LValue path entry, which is known to not be an array index, as a
120   /// base class declaration.
121   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
122     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
123   }
124   /// Determine whether this LValue path entry for a base class names a virtual
125   /// base class.
126   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
127     return getAsBaseOrMember(E).getInt();
128   }
129 
130   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132     const FunctionDecl *Callee = CE->getDirectCallee();
133     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134   }
135 
136   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137   /// This will look through a single cast.
138   ///
139   /// Returns null if we couldn't unwrap a function with alloc_size.
140   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141     if (!E->getType()->isPointerType())
142       return nullptr;
143 
144     E = E->IgnoreParens();
145     // If we're doing a variable assignment from e.g. malloc(N), there will
146     // probably be a cast of some kind. In exotic cases, we might also see a
147     // top-level ExprWithCleanups. Ignore them either way.
148     if (const auto *FE = dyn_cast<FullExpr>(E))
149       E = FE->getSubExpr()->IgnoreParens();
150 
151     if (const auto *Cast = dyn_cast<CastExpr>(E))
152       E = Cast->getSubExpr()->IgnoreParens();
153 
154     if (const auto *CE = dyn_cast<CallExpr>(E))
155       return getAllocSizeAttr(CE) ? CE : nullptr;
156     return nullptr;
157   }
158 
159   /// Determines whether or not the given Base contains a call to a function
160   /// with the alloc_size attribute.
161   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162     const auto *E = Base.dyn_cast<const Expr *>();
163     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164   }
165 
166   /// The bound to claim that an array of unknown bound has.
167   /// The value in MostDerivedArraySize is undefined in this case. So, set it
168   /// to an arbitrary value that's likely to loudly break things if it's used.
169   static const uint64_t AssumedSizeForUnsizedArray =
170       std::numeric_limits<uint64_t>::max() / 2;
171 
172   /// Determines if an LValue with the given LValueBase will have an unsized
173   /// array in its designator.
174   /// Find the path length and type of the most-derived subobject in the given
175   /// path, and find the size of the containing array, if any.
176   static unsigned
177   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178                            ArrayRef<APValue::LValuePathEntry> Path,
179                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
180                            bool &FirstEntryIsUnsizedArray) {
181     // This only accepts LValueBases from APValues, and APValues don't support
182     // arrays that lack size info.
183     assert(!isBaseAnAllocSizeCall(Base) &&
184            "Unsized arrays shouldn't appear here");
185     unsigned MostDerivedLength = 0;
186     Type = getType(Base);
187 
188     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
189       if (Type->isArrayType()) {
190         const ArrayType *AT = Ctx.getAsArrayType(Type);
191         Type = AT->getElementType();
192         MostDerivedLength = I + 1;
193         IsArray = true;
194 
195         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196           ArraySize = CAT->getSize().getZExtValue();
197         } else {
198           assert(I == 0 && "unexpected unsized array designator");
199           FirstEntryIsUnsizedArray = true;
200           ArraySize = AssumedSizeForUnsizedArray;
201         }
202       } else if (Type->isAnyComplexType()) {
203         const ComplexType *CT = Type->castAs<ComplexType>();
204         Type = CT->getElementType();
205         ArraySize = 2;
206         MostDerivedLength = I + 1;
207         IsArray = true;
208       } else if (const FieldDecl *FD = getAsField(Path[I])) {
209         Type = FD->getType();
210         ArraySize = 0;
211         MostDerivedLength = I + 1;
212         IsArray = false;
213       } else {
214         // Path[I] describes a base class.
215         ArraySize = 0;
216         IsArray = false;
217       }
218     }
219     return MostDerivedLength;
220   }
221 
222   // The order of this enum is important for diagnostics.
223   enum CheckSubobjectKind {
224     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
225     CSK_This, CSK_Real, CSK_Imag
226   };
227 
228   /// A path from a glvalue to a subobject of that glvalue.
229   struct SubobjectDesignator {
230     /// True if the subobject was named in a manner not supported by C++11. Such
231     /// lvalues can still be folded, but they are not core constant expressions
232     /// and we cannot perform lvalue-to-rvalue conversions on them.
233     unsigned Invalid : 1;
234 
235     /// Is this a pointer one past the end of an object?
236     unsigned IsOnePastTheEnd : 1;
237 
238     /// Indicator of whether the first entry is an unsized array.
239     unsigned FirstEntryIsAnUnsizedArray : 1;
240 
241     /// Indicator of whether the most-derived object is an array element.
242     unsigned MostDerivedIsArrayElement : 1;
243 
244     /// The length of the path to the most-derived object of which this is a
245     /// subobject.
246     unsigned MostDerivedPathLength : 28;
247 
248     /// The size of the array of which the most-derived object is an element.
249     /// This will always be 0 if the most-derived object is not an array
250     /// element. 0 is not an indicator of whether or not the most-derived object
251     /// is an array, however, because 0-length arrays are allowed.
252     ///
253     /// If the current array is an unsized array, the value of this is
254     /// undefined.
255     uint64_t MostDerivedArraySize;
256 
257     /// The type of the most derived object referred to by this address.
258     QualType MostDerivedType;
259 
260     typedef APValue::LValuePathEntry PathEntry;
261 
262     /// The entries on the path from the glvalue to the designated subobject.
263     SmallVector<PathEntry, 8> Entries;
264 
265     SubobjectDesignator() : Invalid(true) {}
266 
267     explicit SubobjectDesignator(QualType T)
268         : Invalid(false), IsOnePastTheEnd(false),
269           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
270           MostDerivedPathLength(0), MostDerivedArraySize(0),
271           MostDerivedType(T) {}
272 
273     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
274         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
275           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
276           MostDerivedPathLength(0), MostDerivedArraySize(0) {
277       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
278       if (!Invalid) {
279         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
280         ArrayRef<PathEntry> VEntries = V.getLValuePath();
281         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
282         if (V.getLValueBase()) {
283           bool IsArray = false;
284           bool FirstIsUnsizedArray = false;
285           MostDerivedPathLength = findMostDerivedSubobject(
286               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
287               MostDerivedType, IsArray, FirstIsUnsizedArray);
288           MostDerivedIsArrayElement = IsArray;
289           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
290         }
291       }
292     }
293 
294     void setInvalid() {
295       Invalid = true;
296       Entries.clear();
297     }
298 
299     /// Determine whether the most derived subobject is an array without a
300     /// known bound.
301     bool isMostDerivedAnUnsizedArray() const {
302       assert(!Invalid && "Calling this makes no sense on invalid designators");
303       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
304     }
305 
306     /// Determine what the most derived array's size is. Results in an assertion
307     /// failure if the most derived array lacks a size.
308     uint64_t getMostDerivedArraySize() const {
309       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310       return MostDerivedArraySize;
311     }
312 
313     /// Determine whether this is a one-past-the-end pointer.
314     bool isOnePastTheEnd() const {
315       assert(!Invalid);
316       if (IsOnePastTheEnd)
317         return true;
318       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
319           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320         return true;
321       return false;
322     }
323 
324     /// Get the range of valid index adjustments in the form
325     ///   {maximum value that can be subtracted from this pointer,
326     ///    maximum value that can be added to this pointer}
327     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328       if (Invalid || isMostDerivedAnUnsizedArray())
329         return {0, 0};
330 
331       // [expr.add]p4: For the purposes of these operators, a pointer to a
332       // nonarray object behaves the same as a pointer to the first element of
333       // an array of length one with the type of the object as its element type.
334       bool IsArray = MostDerivedPathLength == Entries.size() &&
335                      MostDerivedIsArrayElement;
336       uint64_t ArrayIndex =
337           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338       uint64_t ArraySize =
339           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340       return {ArrayIndex, ArraySize - ArrayIndex};
341     }
342 
343     /// Check that this refers to a valid subobject.
344     bool isValidSubobject() const {
345       if (Invalid)
346         return false;
347       return !isOnePastTheEnd();
348     }
349     /// Check that this refers to a valid subobject, and if not, produce a
350     /// relevant diagnostic and set the designator as invalid.
351     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352 
353     /// Get the type of the designated object.
354     QualType getType(ASTContext &Ctx) const {
355       assert(!Invalid && "invalid designator has no subobject type");
356       return MostDerivedPathLength == Entries.size()
357                  ? MostDerivedType
358                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359     }
360 
361     /// Update this designator to refer to the first element within this array.
362     void addArrayUnchecked(const ConstantArrayType *CAT) {
363       PathEntry Entry;
364       Entry.ArrayIndex = 0;
365       Entries.push_back(Entry);
366 
367       // This is a most-derived object.
368       MostDerivedType = CAT->getElementType();
369       MostDerivedIsArrayElement = true;
370       MostDerivedArraySize = CAT->getSize().getZExtValue();
371       MostDerivedPathLength = Entries.size();
372     }
373     /// Update this designator to refer to the first element within the array of
374     /// elements of type T. This is an array of unknown size.
375     void addUnsizedArrayUnchecked(QualType ElemTy) {
376       PathEntry Entry;
377       Entry.ArrayIndex = 0;
378       Entries.push_back(Entry);
379 
380       MostDerivedType = ElemTy;
381       MostDerivedIsArrayElement = true;
382       // The value in MostDerivedArraySize is undefined in this case. So, set it
383       // to an arbitrary value that's likely to loudly break things if it's
384       // used.
385       MostDerivedArraySize = AssumedSizeForUnsizedArray;
386       MostDerivedPathLength = Entries.size();
387     }
388     /// Update this designator to refer to the given base or member of this
389     /// object.
390     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
391       PathEntry Entry;
392       APValue::BaseOrMemberType Value(D, Virtual);
393       Entry.BaseOrMember = Value.getOpaqueValue();
394       Entries.push_back(Entry);
395 
396       // If this isn't a base class, it's a new most-derived object.
397       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398         MostDerivedType = FD->getType();
399         MostDerivedIsArrayElement = false;
400         MostDerivedArraySize = 0;
401         MostDerivedPathLength = Entries.size();
402       }
403     }
404     /// Update this designator to refer to the given complex component.
405     void addComplexUnchecked(QualType EltTy, bool Imag) {
406       PathEntry Entry;
407       Entry.ArrayIndex = Imag;
408       Entries.push_back(Entry);
409 
410       // This is technically a most-derived object, though in practice this
411       // is unlikely to matter.
412       MostDerivedType = EltTy;
413       MostDerivedIsArrayElement = true;
414       MostDerivedArraySize = 2;
415       MostDerivedPathLength = Entries.size();
416     }
417     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
418     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419                                    const APSInt &N);
420     /// Add N to the address of this subobject.
421     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422       if (Invalid || !N) return;
423       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424       if (isMostDerivedAnUnsizedArray()) {
425         diagnoseUnsizedArrayPointerArithmetic(Info, E);
426         // Can't verify -- trust that the user is doing the right thing (or if
427         // not, trust that the caller will catch the bad behavior).
428         // FIXME: Should we reject if this overflows, at least?
429         Entries.back().ArrayIndex += TruncatedN;
430         return;
431       }
432 
433       // [expr.add]p4: For the purposes of these operators, a pointer to a
434       // nonarray object behaves the same as a pointer to the first element of
435       // an array of length one with the type of the object as its element type.
436       bool IsArray = MostDerivedPathLength == Entries.size() &&
437                      MostDerivedIsArrayElement;
438       uint64_t ArrayIndex =
439           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440       uint64_t ArraySize =
441           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442 
443       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444         // Calculate the actual index in a wide enough type, so we can include
445         // it in the note.
446         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447         (llvm::APInt&)N += ArrayIndex;
448         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449         diagnosePointerArithmetic(Info, E, N);
450         setInvalid();
451         return;
452       }
453 
454       ArrayIndex += TruncatedN;
455       assert(ArrayIndex <= ArraySize &&
456              "bounds check succeeded for out-of-bounds index");
457 
458       if (IsArray)
459         Entries.back().ArrayIndex = ArrayIndex;
460       else
461         IsOnePastTheEnd = (ArrayIndex != 0);
462     }
463   };
464 
465   /// A stack frame in the constexpr call stack.
466   struct CallStackFrame {
467     EvalInfo &Info;
468 
469     /// Parent - The caller of this stack frame.
470     CallStackFrame *Caller;
471 
472     /// Callee - The function which was called.
473     const FunctionDecl *Callee;
474 
475     /// This - The binding for the this pointer in this call, if any.
476     const LValue *This;
477 
478     /// Arguments - Parameter bindings for this function call, indexed by
479     /// parameters' function scope indices.
480     APValue *Arguments;
481 
482     // Note that we intentionally use std::map here so that references to
483     // values are stable.
484     typedef std::pair<const void *, unsigned> MapKeyTy;
485     typedef std::map<MapKeyTy, APValue> MapTy;
486     /// Temporaries - Temporary lvalues materialized within this stack frame.
487     MapTy Temporaries;
488 
489     /// CallLoc - The location of the call expression for this call.
490     SourceLocation CallLoc;
491 
492     /// Index - The call index of this call.
493     unsigned Index;
494 
495     /// The stack of integers for tracking version numbers for temporaries.
496     SmallVector<unsigned, 2> TempVersionStack = {1};
497     unsigned CurTempVersion = TempVersionStack.back();
498 
499     unsigned getTempVersion() const { return TempVersionStack.back(); }
500 
501     void pushTempVersion() {
502       TempVersionStack.push_back(++CurTempVersion);
503     }
504 
505     void popTempVersion() {
506       TempVersionStack.pop_back();
507     }
508 
509     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
510     // on the overall stack usage of deeply-recursing constexpr evaluations.
511     // (We should cache this map rather than recomputing it repeatedly.)
512     // But let's try this and see how it goes; we can look into caching the map
513     // as a later change.
514 
515     /// LambdaCaptureFields - Mapping from captured variables/this to
516     /// corresponding data members in the closure class.
517     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518     FieldDecl *LambdaThisCaptureField;
519 
520     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521                    const FunctionDecl *Callee, const LValue *This,
522                    APValue *Arguments);
523     ~CallStackFrame();
524 
525     // Return the temporary for Key whose version number is Version.
526     APValue *getTemporary(const void *Key, unsigned Version) {
527       MapKeyTy KV(Key, Version);
528       auto LB = Temporaries.lower_bound(KV);
529       if (LB != Temporaries.end() && LB->first == KV)
530         return &LB->second;
531       // Pair (Key,Version) wasn't found in the map. Check that no elements
532       // in the map have 'Key' as their key.
533       assert((LB == Temporaries.end() || LB->first.first != Key) &&
534              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535              "Element with key 'Key' found in map");
536       return nullptr;
537     }
538 
539     // Return the current temporary for Key in the map.
540     APValue *getCurrentTemporary(const void *Key) {
541       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543         return &std::prev(UB)->second;
544       return nullptr;
545     }
546 
547     // Return the version number of the current temporary for Key.
548     unsigned getCurrentTemporaryVersion(const void *Key) const {
549       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551         return std::prev(UB)->first.second;
552       return 0;
553     }
554 
555     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
556   };
557 
558   /// Temporarily override 'this'.
559   class ThisOverrideRAII {
560   public:
561     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562         : Frame(Frame), OldThis(Frame.This) {
563       if (Enable)
564         Frame.This = NewThis;
565     }
566     ~ThisOverrideRAII() {
567       Frame.This = OldThis;
568     }
569   private:
570     CallStackFrame &Frame;
571     const LValue *OldThis;
572   };
573 
574   /// A partial diagnostic which we might know in advance that we are not going
575   /// to emit.
576   class OptionalDiagnostic {
577     PartialDiagnostic *Diag;
578 
579   public:
580     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581       : Diag(Diag) {}
582 
583     template<typename T>
584     OptionalDiagnostic &operator<<(const T &v) {
585       if (Diag)
586         *Diag << v;
587       return *this;
588     }
589 
590     OptionalDiagnostic &operator<<(const APSInt &I) {
591       if (Diag) {
592         SmallVector<char, 32> Buffer;
593         I.toString(Buffer);
594         *Diag << StringRef(Buffer.data(), Buffer.size());
595       }
596       return *this;
597     }
598 
599     OptionalDiagnostic &operator<<(const APFloat &F) {
600       if (Diag) {
601         // FIXME: Force the precision of the source value down so we don't
602         // print digits which are usually useless (we don't really care here if
603         // we truncate a digit by accident in edge cases).  Ideally,
604         // APFloat::toString would automatically print the shortest
605         // representation which rounds to the correct value, but it's a bit
606         // tricky to implement.
607         unsigned precision =
608             llvm::APFloat::semanticsPrecision(F.getSemantics());
609         precision = (precision * 59 + 195) / 196;
610         SmallVector<char, 32> Buffer;
611         F.toString(Buffer, precision);
612         *Diag << StringRef(Buffer.data(), Buffer.size());
613       }
614       return *this;
615     }
616   };
617 
618   /// A cleanup, and a flag indicating whether it is lifetime-extended.
619   class Cleanup {
620     llvm::PointerIntPair<APValue*, 1, bool> Value;
621 
622   public:
623     Cleanup(APValue *Val, bool IsLifetimeExtended)
624         : Value(Val, IsLifetimeExtended) {}
625 
626     bool isLifetimeExtended() const { return Value.getInt(); }
627     void endLifetime() {
628       *Value.getPointer() = APValue();
629     }
630   };
631 
632   /// EvalInfo - This is a private struct used by the evaluator to capture
633   /// information about a subexpression as it is folded.  It retains information
634   /// about the AST context, but also maintains information about the folded
635   /// expression.
636   ///
637   /// If an expression could be evaluated, it is still possible it is not a C
638   /// "integer constant expression" or constant expression.  If not, this struct
639   /// captures information about how and why not.
640   ///
641   /// One bit of information passed *into* the request for constant folding
642   /// indicates whether the subexpression is "evaluated" or not according to C
643   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
644   /// evaluate the expression regardless of what the RHS is, but C only allows
645   /// certain things in certain situations.
646   struct EvalInfo {
647     ASTContext &Ctx;
648 
649     /// EvalStatus - Contains information about the evaluation.
650     Expr::EvalStatus &EvalStatus;
651 
652     /// CurrentCall - The top of the constexpr call stack.
653     CallStackFrame *CurrentCall;
654 
655     /// CallStackDepth - The number of calls in the call stack right now.
656     unsigned CallStackDepth;
657 
658     /// NextCallIndex - The next call index to assign.
659     unsigned NextCallIndex;
660 
661     /// StepsLeft - The remaining number of evaluation steps we're permitted
662     /// to perform. This is essentially a limit for the number of statements
663     /// we will evaluate.
664     unsigned StepsLeft;
665 
666     /// BottomFrame - The frame in which evaluation started. This must be
667     /// initialized after CurrentCall and CallStackDepth.
668     CallStackFrame BottomFrame;
669 
670     /// A stack of values whose lifetimes end at the end of some surrounding
671     /// evaluation frame.
672     llvm::SmallVector<Cleanup, 16> CleanupStack;
673 
674     /// EvaluatingDecl - This is the declaration whose initializer is being
675     /// evaluated, if any.
676     APValue::LValueBase EvaluatingDecl;
677 
678     /// EvaluatingDeclValue - This is the value being constructed for the
679     /// declaration whose initializer is being evaluated, if any.
680     APValue *EvaluatingDeclValue;
681 
682     /// EvaluatingObject - Pair of the AST node that an lvalue represents and
683     /// the call index that that lvalue was allocated in.
684     typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
685         EvaluatingObject;
686 
687     /// EvaluatingConstructors - Set of objects that are currently being
688     /// constructed.
689     llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
690 
691     struct EvaluatingConstructorRAII {
692       EvalInfo &EI;
693       EvaluatingObject Object;
694       bool DidInsert;
695       EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
696           : EI(EI), Object(Object) {
697         DidInsert = EI.EvaluatingConstructors.insert(Object).second;
698       }
699       ~EvaluatingConstructorRAII() {
700         if (DidInsert) EI.EvaluatingConstructors.erase(Object);
701       }
702     };
703 
704     bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
705                                  unsigned Version) {
706       return EvaluatingConstructors.count(
707           EvaluatingObject(Decl, {CallIndex, Version}));
708     }
709 
710     /// The current array initialization index, if we're performing array
711     /// initialization.
712     uint64_t ArrayInitIndex = -1;
713 
714     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
715     /// notes attached to it will also be stored, otherwise they will not be.
716     bool HasActiveDiagnostic;
717 
718     /// Have we emitted a diagnostic explaining why we couldn't constant
719     /// fold (not just why it's not strictly a constant expression)?
720     bool HasFoldFailureDiagnostic;
721 
722     /// Whether or not we're currently speculatively evaluating.
723     bool IsSpeculativelyEvaluating;
724 
725     /// Whether or not we're in a context where the front end requires a
726     /// constant value.
727     bool InConstantContext;
728 
729     enum EvaluationMode {
730       /// Evaluate as a constant expression. Stop if we find that the expression
731       /// is not a constant expression.
732       EM_ConstantExpression,
733 
734       /// Evaluate as a potential constant expression. Keep going if we hit a
735       /// construct that we can't evaluate yet (because we don't yet know the
736       /// value of something) but stop if we hit something that could never be
737       /// a constant expression.
738       EM_PotentialConstantExpression,
739 
740       /// Fold the expression to a constant. Stop if we hit a side-effect that
741       /// we can't model.
742       EM_ConstantFold,
743 
744       /// Evaluate the expression looking for integer overflow and similar
745       /// issues. Don't worry about side-effects, and try to visit all
746       /// subexpressions.
747       EM_EvaluateForOverflow,
748 
749       /// Evaluate in any way we know how. Don't worry about side-effects that
750       /// can't be modeled.
751       EM_IgnoreSideEffects,
752 
753       /// Evaluate as a constant expression. Stop if we find that the expression
754       /// is not a constant expression. Some expressions can be retried in the
755       /// optimizer if we don't constant fold them here, but in an unevaluated
756       /// context we try to fold them immediately since the optimizer never
757       /// gets a chance to look at it.
758       EM_ConstantExpressionUnevaluated,
759 
760       /// Evaluate as a potential constant expression. Keep going if we hit a
761       /// construct that we can't evaluate yet (because we don't yet know the
762       /// value of something) but stop if we hit something that could never be
763       /// a constant expression. Some expressions can be retried in the
764       /// optimizer if we don't constant fold them here, but in an unevaluated
765       /// context we try to fold them immediately since the optimizer never
766       /// gets a chance to look at it.
767       EM_PotentialConstantExpressionUnevaluated,
768     } EvalMode;
769 
770     /// Are we checking whether the expression is a potential constant
771     /// expression?
772     bool checkingPotentialConstantExpression() const {
773       return EvalMode == EM_PotentialConstantExpression ||
774              EvalMode == EM_PotentialConstantExpressionUnevaluated;
775     }
776 
777     /// Are we checking an expression for overflow?
778     // FIXME: We should check for any kind of undefined or suspicious behavior
779     // in such constructs, not just overflow.
780     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
781 
782     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
783       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
784         CallStackDepth(0), NextCallIndex(1),
785         StepsLeft(getLangOpts().ConstexprStepLimit),
786         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
787         EvaluatingDecl((const ValueDecl *)nullptr),
788         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
789         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
790         InConstantContext(false), EvalMode(Mode) {}
791 
792     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
793       EvaluatingDecl = Base;
794       EvaluatingDeclValue = &Value;
795       EvaluatingConstructors.insert({Base, {0, 0}});
796     }
797 
798     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
799 
800     bool CheckCallLimit(SourceLocation Loc) {
801       // Don't perform any constexpr calls (other than the call we're checking)
802       // when checking a potential constant expression.
803       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
804         return false;
805       if (NextCallIndex == 0) {
806         // NextCallIndex has wrapped around.
807         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
808         return false;
809       }
810       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
811         return true;
812       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
813         << getLangOpts().ConstexprCallDepth;
814       return false;
815     }
816 
817     CallStackFrame *getCallFrame(unsigned CallIndex) {
818       assert(CallIndex && "no call index in getCallFrame");
819       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
820       // be null in this loop.
821       CallStackFrame *Frame = CurrentCall;
822       while (Frame->Index > CallIndex)
823         Frame = Frame->Caller;
824       return (Frame->Index == CallIndex) ? Frame : nullptr;
825     }
826 
827     bool nextStep(const Stmt *S) {
828       if (!StepsLeft) {
829         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
830         return false;
831       }
832       --StepsLeft;
833       return true;
834     }
835 
836   private:
837     /// Add a diagnostic to the diagnostics list.
838     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
839       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
840       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
841       return EvalStatus.Diag->back().second;
842     }
843 
844     /// Add notes containing a call stack to the current point of evaluation.
845     void addCallStack(unsigned Limit);
846 
847   private:
848     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
849                             unsigned ExtraNotes, bool IsCCEDiag) {
850 
851       if (EvalStatus.Diag) {
852         // If we have a prior diagnostic, it will be noting that the expression
853         // isn't a constant expression. This diagnostic is more important,
854         // unless we require this evaluation to produce a constant expression.
855         //
856         // FIXME: We might want to show both diagnostics to the user in
857         // EM_ConstantFold mode.
858         if (!EvalStatus.Diag->empty()) {
859           switch (EvalMode) {
860           case EM_ConstantFold:
861           case EM_IgnoreSideEffects:
862           case EM_EvaluateForOverflow:
863             if (!HasFoldFailureDiagnostic)
864               break;
865             // We've already failed to fold something. Keep that diagnostic.
866             LLVM_FALLTHROUGH;
867           case EM_ConstantExpression:
868           case EM_PotentialConstantExpression:
869           case EM_ConstantExpressionUnevaluated:
870           case EM_PotentialConstantExpressionUnevaluated:
871             HasActiveDiagnostic = false;
872             return OptionalDiagnostic();
873           }
874         }
875 
876         unsigned CallStackNotes = CallStackDepth - 1;
877         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
878         if (Limit)
879           CallStackNotes = std::min(CallStackNotes, Limit + 1);
880         if (checkingPotentialConstantExpression())
881           CallStackNotes = 0;
882 
883         HasActiveDiagnostic = true;
884         HasFoldFailureDiagnostic = !IsCCEDiag;
885         EvalStatus.Diag->clear();
886         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
887         addDiag(Loc, DiagId);
888         if (!checkingPotentialConstantExpression())
889           addCallStack(Limit);
890         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
891       }
892       HasActiveDiagnostic = false;
893       return OptionalDiagnostic();
894     }
895   public:
896     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
897     OptionalDiagnostic
898     FFDiag(SourceLocation Loc,
899           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
900           unsigned ExtraNotes = 0) {
901       return Diag(Loc, DiagId, ExtraNotes, false);
902     }
903 
904     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
905                               = diag::note_invalid_subexpr_in_const_expr,
906                             unsigned ExtraNotes = 0) {
907       if (EvalStatus.Diag)
908         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
909       HasActiveDiagnostic = false;
910       return OptionalDiagnostic();
911     }
912 
913     /// Diagnose that the evaluation does not produce a C++11 core constant
914     /// expression.
915     ///
916     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
917     /// EM_PotentialConstantExpression mode and we produce one of these.
918     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
919                                  = diag::note_invalid_subexpr_in_const_expr,
920                                unsigned ExtraNotes = 0) {
921       // Don't override a previous diagnostic. Don't bother collecting
922       // diagnostics if we're evaluating for overflow.
923       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
924         HasActiveDiagnostic = false;
925         return OptionalDiagnostic();
926       }
927       return Diag(Loc, DiagId, ExtraNotes, true);
928     }
929     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
930                                  = diag::note_invalid_subexpr_in_const_expr,
931                                unsigned ExtraNotes = 0) {
932       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
933     }
934     /// Add a note to a prior diagnostic.
935     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
936       if (!HasActiveDiagnostic)
937         return OptionalDiagnostic();
938       return OptionalDiagnostic(&addDiag(Loc, DiagId));
939     }
940 
941     /// Add a stack of notes to a prior diagnostic.
942     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
943       if (HasActiveDiagnostic) {
944         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
945                                 Diags.begin(), Diags.end());
946       }
947     }
948 
949     /// Should we continue evaluation after encountering a side-effect that we
950     /// couldn't model?
951     bool keepEvaluatingAfterSideEffect() {
952       switch (EvalMode) {
953       case EM_PotentialConstantExpression:
954       case EM_PotentialConstantExpressionUnevaluated:
955       case EM_EvaluateForOverflow:
956       case EM_IgnoreSideEffects:
957         return true;
958 
959       case EM_ConstantExpression:
960       case EM_ConstantExpressionUnevaluated:
961       case EM_ConstantFold:
962         return false;
963       }
964       llvm_unreachable("Missed EvalMode case");
965     }
966 
967     /// Note that we have had a side-effect, and determine whether we should
968     /// keep evaluating.
969     bool noteSideEffect() {
970       EvalStatus.HasSideEffects = true;
971       return keepEvaluatingAfterSideEffect();
972     }
973 
974     /// Should we continue evaluation after encountering undefined behavior?
975     bool keepEvaluatingAfterUndefinedBehavior() {
976       switch (EvalMode) {
977       case EM_EvaluateForOverflow:
978       case EM_IgnoreSideEffects:
979       case EM_ConstantFold:
980         return true;
981 
982       case EM_PotentialConstantExpression:
983       case EM_PotentialConstantExpressionUnevaluated:
984       case EM_ConstantExpression:
985       case EM_ConstantExpressionUnevaluated:
986         return false;
987       }
988       llvm_unreachable("Missed EvalMode case");
989     }
990 
991     /// Note that we hit something that was technically undefined behavior, but
992     /// that we can evaluate past it (such as signed overflow or floating-point
993     /// division by zero.)
994     bool noteUndefinedBehavior() {
995       EvalStatus.HasUndefinedBehavior = true;
996       return keepEvaluatingAfterUndefinedBehavior();
997     }
998 
999     /// Should we continue evaluation as much as possible after encountering a
1000     /// construct which can't be reduced to a value?
1001     bool keepEvaluatingAfterFailure() {
1002       if (!StepsLeft)
1003         return false;
1004 
1005       switch (EvalMode) {
1006       case EM_PotentialConstantExpression:
1007       case EM_PotentialConstantExpressionUnevaluated:
1008       case EM_EvaluateForOverflow:
1009         return true;
1010 
1011       case EM_ConstantExpression:
1012       case EM_ConstantExpressionUnevaluated:
1013       case EM_ConstantFold:
1014       case EM_IgnoreSideEffects:
1015         return false;
1016       }
1017       llvm_unreachable("Missed EvalMode case");
1018     }
1019 
1020     /// Notes that we failed to evaluate an expression that other expressions
1021     /// directly depend on, and determine if we should keep evaluating. This
1022     /// should only be called if we actually intend to keep evaluating.
1023     ///
1024     /// Call noteSideEffect() instead if we may be able to ignore the value that
1025     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1026     ///
1027     /// (Foo(), 1)      // use noteSideEffect
1028     /// (Foo() || true) // use noteSideEffect
1029     /// Foo() + 1       // use noteFailure
1030     LLVM_NODISCARD bool noteFailure() {
1031       // Failure when evaluating some expression often means there is some
1032       // subexpression whose evaluation was skipped. Therefore, (because we
1033       // don't track whether we skipped an expression when unwinding after an
1034       // evaluation failure) every evaluation failure that bubbles up from a
1035       // subexpression implies that a side-effect has potentially happened. We
1036       // skip setting the HasSideEffects flag to true until we decide to
1037       // continue evaluating after that point, which happens here.
1038       bool KeepGoing = keepEvaluatingAfterFailure();
1039       EvalStatus.HasSideEffects |= KeepGoing;
1040       return KeepGoing;
1041     }
1042 
1043     class ArrayInitLoopIndex {
1044       EvalInfo &Info;
1045       uint64_t OuterIndex;
1046 
1047     public:
1048       ArrayInitLoopIndex(EvalInfo &Info)
1049           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1050         Info.ArrayInitIndex = 0;
1051       }
1052       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1053 
1054       operator uint64_t&() { return Info.ArrayInitIndex; }
1055     };
1056   };
1057 
1058   /// Object used to treat all foldable expressions as constant expressions.
1059   struct FoldConstant {
1060     EvalInfo &Info;
1061     bool Enabled;
1062     bool HadNoPriorDiags;
1063     EvalInfo::EvaluationMode OldMode;
1064 
1065     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1066       : Info(Info),
1067         Enabled(Enabled),
1068         HadNoPriorDiags(Info.EvalStatus.Diag &&
1069                         Info.EvalStatus.Diag->empty() &&
1070                         !Info.EvalStatus.HasSideEffects),
1071         OldMode(Info.EvalMode) {
1072       if (Enabled &&
1073           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1074            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1075         Info.EvalMode = EvalInfo::EM_ConstantFold;
1076     }
1077     void keepDiagnostics() { Enabled = false; }
1078     ~FoldConstant() {
1079       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1080           !Info.EvalStatus.HasSideEffects)
1081         Info.EvalStatus.Diag->clear();
1082       Info.EvalMode = OldMode;
1083     }
1084   };
1085 
1086   /// RAII object used to set the current evaluation mode to ignore
1087   /// side-effects.
1088   struct IgnoreSideEffectsRAII {
1089     EvalInfo &Info;
1090     EvalInfo::EvaluationMode OldMode;
1091     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1092         : Info(Info), OldMode(Info.EvalMode) {
1093       if (!Info.checkingPotentialConstantExpression())
1094         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1095     }
1096 
1097     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1098   };
1099 
1100   /// RAII object used to optionally suppress diagnostics and side-effects from
1101   /// a speculative evaluation.
1102   class SpeculativeEvaluationRAII {
1103     EvalInfo *Info = nullptr;
1104     Expr::EvalStatus OldStatus;
1105     bool OldIsSpeculativelyEvaluating;
1106 
1107     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1108       Info = Other.Info;
1109       OldStatus = Other.OldStatus;
1110       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1111       Other.Info = nullptr;
1112     }
1113 
1114     void maybeRestoreState() {
1115       if (!Info)
1116         return;
1117 
1118       Info->EvalStatus = OldStatus;
1119       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1120     }
1121 
1122   public:
1123     SpeculativeEvaluationRAII() = default;
1124 
1125     SpeculativeEvaluationRAII(
1126         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1127         : Info(&Info), OldStatus(Info.EvalStatus),
1128           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1129       Info.EvalStatus.Diag = NewDiag;
1130       Info.IsSpeculativelyEvaluating = true;
1131     }
1132 
1133     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1134     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1135       moveFromAndCancel(std::move(Other));
1136     }
1137 
1138     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1139       maybeRestoreState();
1140       moveFromAndCancel(std::move(Other));
1141       return *this;
1142     }
1143 
1144     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1145   };
1146 
1147   /// RAII object wrapping a full-expression or block scope, and handling
1148   /// the ending of the lifetime of temporaries created within it.
1149   template<bool IsFullExpression>
1150   class ScopeRAII {
1151     EvalInfo &Info;
1152     unsigned OldStackSize;
1153   public:
1154     ScopeRAII(EvalInfo &Info)
1155         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1156       // Push a new temporary version. This is needed to distinguish between
1157       // temporaries created in different iterations of a loop.
1158       Info.CurrentCall->pushTempVersion();
1159     }
1160     ~ScopeRAII() {
1161       // Body moved to a static method to encourage the compiler to inline away
1162       // instances of this class.
1163       cleanup(Info, OldStackSize);
1164       Info.CurrentCall->popTempVersion();
1165     }
1166   private:
1167     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1168       unsigned NewEnd = OldStackSize;
1169       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1170            I != N; ++I) {
1171         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1172           // Full-expression cleanup of a lifetime-extended temporary: nothing
1173           // to do, just move this cleanup to the right place in the stack.
1174           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1175           ++NewEnd;
1176         } else {
1177           // End the lifetime of the object.
1178           Info.CleanupStack[I].endLifetime();
1179         }
1180       }
1181       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1182                               Info.CleanupStack.end());
1183     }
1184   };
1185   typedef ScopeRAII<false> BlockScopeRAII;
1186   typedef ScopeRAII<true> FullExpressionRAII;
1187 }
1188 
1189 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1190                                          CheckSubobjectKind CSK) {
1191   if (Invalid)
1192     return false;
1193   if (isOnePastTheEnd()) {
1194     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1195       << CSK;
1196     setInvalid();
1197     return false;
1198   }
1199   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1200   // must actually be at least one array element; even a VLA cannot have a
1201   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1202   return true;
1203 }
1204 
1205 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1206                                                                 const Expr *E) {
1207   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1208   // Do not set the designator as invalid: we can represent this situation,
1209   // and correct handling of __builtin_object_size requires us to do so.
1210 }
1211 
1212 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1213                                                     const Expr *E,
1214                                                     const APSInt &N) {
1215   // If we're complaining, we must be able to statically determine the size of
1216   // the most derived array.
1217   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1218     Info.CCEDiag(E, diag::note_constexpr_array_index)
1219       << N << /*array*/ 0
1220       << static_cast<unsigned>(getMostDerivedArraySize());
1221   else
1222     Info.CCEDiag(E, diag::note_constexpr_array_index)
1223       << N << /*non-array*/ 1;
1224   setInvalid();
1225 }
1226 
1227 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1228                                const FunctionDecl *Callee, const LValue *This,
1229                                APValue *Arguments)
1230     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1231       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1232   Info.CurrentCall = this;
1233   ++Info.CallStackDepth;
1234 }
1235 
1236 CallStackFrame::~CallStackFrame() {
1237   assert(Info.CurrentCall == this && "calls retired out of order");
1238   --Info.CallStackDepth;
1239   Info.CurrentCall = Caller;
1240 }
1241 
1242 APValue &CallStackFrame::createTemporary(const void *Key,
1243                                          bool IsLifetimeExtended) {
1244   unsigned Version = Info.CurrentCall->getTempVersion();
1245   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1246   assert(Result.isUninit() && "temporary created multiple times");
1247   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1248   return Result;
1249 }
1250 
1251 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1252 
1253 void EvalInfo::addCallStack(unsigned Limit) {
1254   // Determine which calls to skip, if any.
1255   unsigned ActiveCalls = CallStackDepth - 1;
1256   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1257   if (Limit && Limit < ActiveCalls) {
1258     SkipStart = Limit / 2 + Limit % 2;
1259     SkipEnd = ActiveCalls - Limit / 2;
1260   }
1261 
1262   // Walk the call stack and add the diagnostics.
1263   unsigned CallIdx = 0;
1264   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1265        Frame = Frame->Caller, ++CallIdx) {
1266     // Skip this call?
1267     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1268       if (CallIdx == SkipStart) {
1269         // Note that we're skipping calls.
1270         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1271           << unsigned(ActiveCalls - Limit);
1272       }
1273       continue;
1274     }
1275 
1276     // Use a different note for an inheriting constructor, because from the
1277     // user's perspective it's not really a function at all.
1278     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1279       if (CD->isInheritingConstructor()) {
1280         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1281           << CD->getParent();
1282         continue;
1283       }
1284     }
1285 
1286     SmallVector<char, 128> Buffer;
1287     llvm::raw_svector_ostream Out(Buffer);
1288     describeCall(Frame, Out);
1289     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1290   }
1291 }
1292 
1293 /// Kinds of access we can perform on an object, for diagnostics.
1294 enum AccessKinds {
1295   AK_Read,
1296   AK_Assign,
1297   AK_Increment,
1298   AK_Decrement
1299 };
1300 
1301 namespace {
1302   struct ComplexValue {
1303   private:
1304     bool IsInt;
1305 
1306   public:
1307     APSInt IntReal, IntImag;
1308     APFloat FloatReal, FloatImag;
1309 
1310     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1311 
1312     void makeComplexFloat() { IsInt = false; }
1313     bool isComplexFloat() const { return !IsInt; }
1314     APFloat &getComplexFloatReal() { return FloatReal; }
1315     APFloat &getComplexFloatImag() { return FloatImag; }
1316 
1317     void makeComplexInt() { IsInt = true; }
1318     bool isComplexInt() const { return IsInt; }
1319     APSInt &getComplexIntReal() { return IntReal; }
1320     APSInt &getComplexIntImag() { return IntImag; }
1321 
1322     void moveInto(APValue &v) const {
1323       if (isComplexFloat())
1324         v = APValue(FloatReal, FloatImag);
1325       else
1326         v = APValue(IntReal, IntImag);
1327     }
1328     void setFrom(const APValue &v) {
1329       assert(v.isComplexFloat() || v.isComplexInt());
1330       if (v.isComplexFloat()) {
1331         makeComplexFloat();
1332         FloatReal = v.getComplexFloatReal();
1333         FloatImag = v.getComplexFloatImag();
1334       } else {
1335         makeComplexInt();
1336         IntReal = v.getComplexIntReal();
1337         IntImag = v.getComplexIntImag();
1338       }
1339     }
1340   };
1341 
1342   struct LValue {
1343     APValue::LValueBase Base;
1344     CharUnits Offset;
1345     SubobjectDesignator Designator;
1346     bool IsNullPtr : 1;
1347     bool InvalidBase : 1;
1348 
1349     const APValue::LValueBase getLValueBase() const { return Base; }
1350     CharUnits &getLValueOffset() { return Offset; }
1351     const CharUnits &getLValueOffset() const { return Offset; }
1352     SubobjectDesignator &getLValueDesignator() { return Designator; }
1353     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1354     bool isNullPointer() const { return IsNullPtr;}
1355 
1356     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1357     unsigned getLValueVersion() const { return Base.getVersion(); }
1358 
1359     void moveInto(APValue &V) const {
1360       if (Designator.Invalid)
1361         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1362       else {
1363         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1364         V = APValue(Base, Offset, Designator.Entries,
1365                     Designator.IsOnePastTheEnd, IsNullPtr);
1366       }
1367     }
1368     void setFrom(ASTContext &Ctx, const APValue &V) {
1369       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1370       Base = V.getLValueBase();
1371       Offset = V.getLValueOffset();
1372       InvalidBase = false;
1373       Designator = SubobjectDesignator(Ctx, V);
1374       IsNullPtr = V.isNullPointer();
1375     }
1376 
1377     void set(APValue::LValueBase B, bool BInvalid = false) {
1378 #ifndef NDEBUG
1379       // We only allow a few types of invalid bases. Enforce that here.
1380       if (BInvalid) {
1381         const auto *E = B.get<const Expr *>();
1382         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1383                "Unexpected type of invalid base");
1384       }
1385 #endif
1386 
1387       Base = B;
1388       Offset = CharUnits::fromQuantity(0);
1389       InvalidBase = BInvalid;
1390       Designator = SubobjectDesignator(getType(B));
1391       IsNullPtr = false;
1392     }
1393 
1394     void setNull(QualType PointerTy, uint64_t TargetVal) {
1395       Base = (Expr *)nullptr;
1396       Offset = CharUnits::fromQuantity(TargetVal);
1397       InvalidBase = false;
1398       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1399       IsNullPtr = true;
1400     }
1401 
1402     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1403       set(B, true);
1404     }
1405 
1406   private:
1407     // Check that this LValue is not based on a null pointer. If it is, produce
1408     // a diagnostic and mark the designator as invalid.
1409     template <typename GenDiagType>
1410     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1411       if (Designator.Invalid)
1412         return false;
1413       if (IsNullPtr) {
1414         GenDiag();
1415         Designator.setInvalid();
1416         return false;
1417       }
1418       return true;
1419     }
1420 
1421   public:
1422     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1423                           CheckSubobjectKind CSK) {
1424       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1425         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1426       });
1427     }
1428 
1429     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1430                                        AccessKinds AK) {
1431       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1432         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1433       });
1434     }
1435 
1436     // Check this LValue refers to an object. If not, set the designator to be
1437     // invalid and emit a diagnostic.
1438     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1439       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1440              Designator.checkSubobject(Info, E, CSK);
1441     }
1442 
1443     void addDecl(EvalInfo &Info, const Expr *E,
1444                  const Decl *D, bool Virtual = false) {
1445       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1446         Designator.addDeclUnchecked(D, Virtual);
1447     }
1448     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1449       if (!Designator.Entries.empty()) {
1450         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1451         Designator.setInvalid();
1452         return;
1453       }
1454       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1455         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1456         Designator.FirstEntryIsAnUnsizedArray = true;
1457         Designator.addUnsizedArrayUnchecked(ElemTy);
1458       }
1459     }
1460     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1461       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1462         Designator.addArrayUnchecked(CAT);
1463     }
1464     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1465       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1466         Designator.addComplexUnchecked(EltTy, Imag);
1467     }
1468     void clearIsNullPointer() {
1469       IsNullPtr = false;
1470     }
1471     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1472                               const APSInt &Index, CharUnits ElementSize) {
1473       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1474       // but we're not required to diagnose it and it's valid in C++.)
1475       if (!Index)
1476         return;
1477 
1478       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1479       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1480       // offsets.
1481       uint64_t Offset64 = Offset.getQuantity();
1482       uint64_t ElemSize64 = ElementSize.getQuantity();
1483       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1484       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1485 
1486       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1487         Designator.adjustIndex(Info, E, Index);
1488       clearIsNullPointer();
1489     }
1490     void adjustOffset(CharUnits N) {
1491       Offset += N;
1492       if (N.getQuantity())
1493         clearIsNullPointer();
1494     }
1495   };
1496 
1497   struct MemberPtr {
1498     MemberPtr() {}
1499     explicit MemberPtr(const ValueDecl *Decl) :
1500       DeclAndIsDerivedMember(Decl, false), Path() {}
1501 
1502     /// The member or (direct or indirect) field referred to by this member
1503     /// pointer, or 0 if this is a null member pointer.
1504     const ValueDecl *getDecl() const {
1505       return DeclAndIsDerivedMember.getPointer();
1506     }
1507     /// Is this actually a member of some type derived from the relevant class?
1508     bool isDerivedMember() const {
1509       return DeclAndIsDerivedMember.getInt();
1510     }
1511     /// Get the class which the declaration actually lives in.
1512     const CXXRecordDecl *getContainingRecord() const {
1513       return cast<CXXRecordDecl>(
1514           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1515     }
1516 
1517     void moveInto(APValue &V) const {
1518       V = APValue(getDecl(), isDerivedMember(), Path);
1519     }
1520     void setFrom(const APValue &V) {
1521       assert(V.isMemberPointer());
1522       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1523       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1524       Path.clear();
1525       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1526       Path.insert(Path.end(), P.begin(), P.end());
1527     }
1528 
1529     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1530     /// whether the member is a member of some class derived from the class type
1531     /// of the member pointer.
1532     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1533     /// Path - The path of base/derived classes from the member declaration's
1534     /// class (exclusive) to the class type of the member pointer (inclusive).
1535     SmallVector<const CXXRecordDecl*, 4> Path;
1536 
1537     /// Perform a cast towards the class of the Decl (either up or down the
1538     /// hierarchy).
1539     bool castBack(const CXXRecordDecl *Class) {
1540       assert(!Path.empty());
1541       const CXXRecordDecl *Expected;
1542       if (Path.size() >= 2)
1543         Expected = Path[Path.size() - 2];
1544       else
1545         Expected = getContainingRecord();
1546       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1547         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1548         // if B does not contain the original member and is not a base or
1549         // derived class of the class containing the original member, the result
1550         // of the cast is undefined.
1551         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1552         // (D::*). We consider that to be a language defect.
1553         return false;
1554       }
1555       Path.pop_back();
1556       return true;
1557     }
1558     /// Perform a base-to-derived member pointer cast.
1559     bool castToDerived(const CXXRecordDecl *Derived) {
1560       if (!getDecl())
1561         return true;
1562       if (!isDerivedMember()) {
1563         Path.push_back(Derived);
1564         return true;
1565       }
1566       if (!castBack(Derived))
1567         return false;
1568       if (Path.empty())
1569         DeclAndIsDerivedMember.setInt(false);
1570       return true;
1571     }
1572     /// Perform a derived-to-base member pointer cast.
1573     bool castToBase(const CXXRecordDecl *Base) {
1574       if (!getDecl())
1575         return true;
1576       if (Path.empty())
1577         DeclAndIsDerivedMember.setInt(true);
1578       if (isDerivedMember()) {
1579         Path.push_back(Base);
1580         return true;
1581       }
1582       return castBack(Base);
1583     }
1584   };
1585 
1586   /// Compare two member pointers, which are assumed to be of the same type.
1587   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1588     if (!LHS.getDecl() || !RHS.getDecl())
1589       return !LHS.getDecl() && !RHS.getDecl();
1590     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1591       return false;
1592     return LHS.Path == RHS.Path;
1593   }
1594 }
1595 
1596 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1597 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1598                             const LValue &This, const Expr *E,
1599                             bool AllowNonLiteralTypes = false);
1600 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1601                            bool InvalidBaseOK = false);
1602 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1603                             bool InvalidBaseOK = false);
1604 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1605                                   EvalInfo &Info);
1606 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1607 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1608 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1609                                     EvalInfo &Info);
1610 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1611 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1612 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1613                            EvalInfo &Info);
1614 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1615 
1616 //===----------------------------------------------------------------------===//
1617 // Misc utilities
1618 //===----------------------------------------------------------------------===//
1619 
1620 /// A helper function to create a temporary and set an LValue.
1621 template <class KeyTy>
1622 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1623                                 LValue &LV, CallStackFrame &Frame) {
1624   LV.set({Key, Frame.Info.CurrentCall->Index,
1625           Frame.Info.CurrentCall->getTempVersion()});
1626   return Frame.createTemporary(Key, IsLifetimeExtended);
1627 }
1628 
1629 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1630 /// preserving its value (by extending by up to one bit as needed).
1631 static void negateAsSigned(APSInt &Int) {
1632   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1633     Int = Int.extend(Int.getBitWidth() + 1);
1634     Int.setIsSigned(true);
1635   }
1636   Int = -Int;
1637 }
1638 
1639 /// Produce a string describing the given constexpr call.
1640 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1641   unsigned ArgIndex = 0;
1642   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1643                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1644                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1645 
1646   if (!IsMemberCall)
1647     Out << *Frame->Callee << '(';
1648 
1649   if (Frame->This && IsMemberCall) {
1650     APValue Val;
1651     Frame->This->moveInto(Val);
1652     Val.printPretty(Out, Frame->Info.Ctx,
1653                     Frame->This->Designator.MostDerivedType);
1654     // FIXME: Add parens around Val if needed.
1655     Out << "->" << *Frame->Callee << '(';
1656     IsMemberCall = false;
1657   }
1658 
1659   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1660        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1661     if (ArgIndex > (unsigned)IsMemberCall)
1662       Out << ", ";
1663 
1664     const ParmVarDecl *Param = *I;
1665     const APValue &Arg = Frame->Arguments[ArgIndex];
1666     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1667 
1668     if (ArgIndex == 0 && IsMemberCall)
1669       Out << "->" << *Frame->Callee << '(';
1670   }
1671 
1672   Out << ')';
1673 }
1674 
1675 /// Evaluate an expression to see if it had side-effects, and discard its
1676 /// result.
1677 /// \return \c true if the caller should keep evaluating.
1678 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1679   APValue Scratch;
1680   if (!Evaluate(Scratch, Info, E))
1681     // We don't need the value, but we might have skipped a side effect here.
1682     return Info.noteSideEffect();
1683   return true;
1684 }
1685 
1686 /// Should this call expression be treated as a string literal?
1687 static bool IsStringLiteralCall(const CallExpr *E) {
1688   unsigned Builtin = E->getBuiltinCallee();
1689   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1690           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1691 }
1692 
1693 static bool IsGlobalLValue(APValue::LValueBase B) {
1694   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1695   // constant expression of pointer type that evaluates to...
1696 
1697   // ... a null pointer value, or a prvalue core constant expression of type
1698   // std::nullptr_t.
1699   if (!B) return true;
1700 
1701   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1702     // ... the address of an object with static storage duration,
1703     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1704       return VD->hasGlobalStorage();
1705     // ... the address of a function,
1706     return isa<FunctionDecl>(D);
1707   }
1708 
1709   const Expr *E = B.get<const Expr*>();
1710   switch (E->getStmtClass()) {
1711   default:
1712     return false;
1713   case Expr::CompoundLiteralExprClass: {
1714     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1715     return CLE->isFileScope() && CLE->isLValue();
1716   }
1717   case Expr::MaterializeTemporaryExprClass:
1718     // A materialized temporary might have been lifetime-extended to static
1719     // storage duration.
1720     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1721   // A string literal has static storage duration.
1722   case Expr::StringLiteralClass:
1723   case Expr::PredefinedExprClass:
1724   case Expr::ObjCStringLiteralClass:
1725   case Expr::ObjCEncodeExprClass:
1726   case Expr::CXXTypeidExprClass:
1727   case Expr::CXXUuidofExprClass:
1728     return true;
1729   case Expr::CallExprClass:
1730     return IsStringLiteralCall(cast<CallExpr>(E));
1731   // For GCC compatibility, &&label has static storage duration.
1732   case Expr::AddrLabelExprClass:
1733     return true;
1734   // A Block literal expression may be used as the initialization value for
1735   // Block variables at global or local static scope.
1736   case Expr::BlockExprClass:
1737     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1738   case Expr::ImplicitValueInitExprClass:
1739     // FIXME:
1740     // We can never form an lvalue with an implicit value initialization as its
1741     // base through expression evaluation, so these only appear in one case: the
1742     // implicit variable declaration we invent when checking whether a constexpr
1743     // constructor can produce a constant expression. We must assume that such
1744     // an expression might be a global lvalue.
1745     return true;
1746   }
1747 }
1748 
1749 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1750   return LVal.Base.dyn_cast<const ValueDecl*>();
1751 }
1752 
1753 static bool IsLiteralLValue(const LValue &Value) {
1754   if (Value.getLValueCallIndex())
1755     return false;
1756   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1757   return E && !isa<MaterializeTemporaryExpr>(E);
1758 }
1759 
1760 static bool IsWeakLValue(const LValue &Value) {
1761   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1762   return Decl && Decl->isWeak();
1763 }
1764 
1765 static bool isZeroSized(const LValue &Value) {
1766   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1767   if (Decl && isa<VarDecl>(Decl)) {
1768     QualType Ty = Decl->getType();
1769     if (Ty->isArrayType())
1770       return Ty->isIncompleteType() ||
1771              Decl->getASTContext().getTypeSize(Ty) == 0;
1772   }
1773   return false;
1774 }
1775 
1776 static bool HasSameBase(const LValue &A, const LValue &B) {
1777   if (!A.getLValueBase())
1778     return !B.getLValueBase();
1779   if (!B.getLValueBase())
1780     return false;
1781 
1782   if (A.getLValueBase().getOpaqueValue() !=
1783       B.getLValueBase().getOpaqueValue()) {
1784     const Decl *ADecl = GetLValueBaseDecl(A);
1785     if (!ADecl)
1786       return false;
1787     const Decl *BDecl = GetLValueBaseDecl(B);
1788     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1789       return false;
1790   }
1791 
1792   return IsGlobalLValue(A.getLValueBase()) ||
1793          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1794           A.getLValueVersion() == B.getLValueVersion());
1795 }
1796 
1797 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1798   assert(Base && "no location for a null lvalue");
1799   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1800   if (VD)
1801     Info.Note(VD->getLocation(), diag::note_declared_at);
1802   else
1803     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1804               diag::note_constexpr_temporary_here);
1805 }
1806 
1807 /// Check that this reference or pointer core constant expression is a valid
1808 /// value for an address or reference constant expression. Return true if we
1809 /// can fold this expression, whether or not it's a constant expression.
1810 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1811                                           QualType Type, const LValue &LVal,
1812                                           Expr::ConstExprUsage Usage) {
1813   bool IsReferenceType = Type->isReferenceType();
1814 
1815   APValue::LValueBase Base = LVal.getLValueBase();
1816   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1817 
1818   // Check that the object is a global. Note that the fake 'this' object we
1819   // manufacture when checking potential constant expressions is conservatively
1820   // assumed to be global here.
1821   if (!IsGlobalLValue(Base)) {
1822     if (Info.getLangOpts().CPlusPlus11) {
1823       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1824       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1825         << IsReferenceType << !Designator.Entries.empty()
1826         << !!VD << VD;
1827       NoteLValueLocation(Info, Base);
1828     } else {
1829       Info.FFDiag(Loc);
1830     }
1831     // Don't allow references to temporaries to escape.
1832     return false;
1833   }
1834   assert((Info.checkingPotentialConstantExpression() ||
1835           LVal.getLValueCallIndex() == 0) &&
1836          "have call index for global lvalue");
1837 
1838   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1839     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1840       // Check if this is a thread-local variable.
1841       if (Var->getTLSKind())
1842         return false;
1843 
1844       // A dllimport variable never acts like a constant.
1845       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1846         return false;
1847     }
1848     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1849       // __declspec(dllimport) must be handled very carefully:
1850       // We must never initialize an expression with the thunk in C++.
1851       // Doing otherwise would allow the same id-expression to yield
1852       // different addresses for the same function in different translation
1853       // units.  However, this means that we must dynamically initialize the
1854       // expression with the contents of the import address table at runtime.
1855       //
1856       // The C language has no notion of ODR; furthermore, it has no notion of
1857       // dynamic initialization.  This means that we are permitted to
1858       // perform initialization with the address of the thunk.
1859       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1860           FD->hasAttr<DLLImportAttr>())
1861         return false;
1862     }
1863   }
1864 
1865   // Allow address constant expressions to be past-the-end pointers. This is
1866   // an extension: the standard requires them to point to an object.
1867   if (!IsReferenceType)
1868     return true;
1869 
1870   // A reference constant expression must refer to an object.
1871   if (!Base) {
1872     // FIXME: diagnostic
1873     Info.CCEDiag(Loc);
1874     return true;
1875   }
1876 
1877   // Does this refer one past the end of some object?
1878   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1879     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1880     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1881       << !Designator.Entries.empty() << !!VD << VD;
1882     NoteLValueLocation(Info, Base);
1883   }
1884 
1885   return true;
1886 }
1887 
1888 /// Member pointers are constant expressions unless they point to a
1889 /// non-virtual dllimport member function.
1890 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1891                                                  SourceLocation Loc,
1892                                                  QualType Type,
1893                                                  const APValue &Value,
1894                                                  Expr::ConstExprUsage Usage) {
1895   const ValueDecl *Member = Value.getMemberPointerDecl();
1896   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1897   if (!FD)
1898     return true;
1899   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1900          !FD->hasAttr<DLLImportAttr>();
1901 }
1902 
1903 /// Check that this core constant expression is of literal type, and if not,
1904 /// produce an appropriate diagnostic.
1905 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1906                              const LValue *This = nullptr) {
1907   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1908     return true;
1909 
1910   // C++1y: A constant initializer for an object o [...] may also invoke
1911   // constexpr constructors for o and its subobjects even if those objects
1912   // are of non-literal class types.
1913   //
1914   // C++11 missed this detail for aggregates, so classes like this:
1915   //   struct foo_t { union { int i; volatile int j; } u; };
1916   // are not (obviously) initializable like so:
1917   //   __attribute__((__require_constant_initialization__))
1918   //   static const foo_t x = {{0}};
1919   // because "i" is a subobject with non-literal initialization (due to the
1920   // volatile member of the union). See:
1921   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1922   // Therefore, we use the C++1y behavior.
1923   if (This && Info.EvaluatingDecl == This->getLValueBase())
1924     return true;
1925 
1926   // Prvalue constant expressions must be of literal types.
1927   if (Info.getLangOpts().CPlusPlus11)
1928     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1929       << E->getType();
1930   else
1931     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1932   return false;
1933 }
1934 
1935 /// Check that this core constant expression value is a valid value for a
1936 /// constant expression. If not, report an appropriate diagnostic. Does not
1937 /// check that the expression is of literal type.
1938 static bool
1939 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1940                         const APValue &Value,
1941                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1942   if (Value.isUninit()) {
1943     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1944       << true << Type;
1945     return false;
1946   }
1947 
1948   // We allow _Atomic(T) to be initialized from anything that T can be
1949   // initialized from.
1950   if (const AtomicType *AT = Type->getAs<AtomicType>())
1951     Type = AT->getValueType();
1952 
1953   // Core issue 1454: For a literal constant expression of array or class type,
1954   // each subobject of its value shall have been initialized by a constant
1955   // expression.
1956   if (Value.isArray()) {
1957     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1958     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1959       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1960                                    Value.getArrayInitializedElt(I), Usage))
1961         return false;
1962     }
1963     if (!Value.hasArrayFiller())
1964       return true;
1965     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1966                                    Usage);
1967   }
1968   if (Value.isUnion() && Value.getUnionField()) {
1969     return CheckConstantExpression(Info, DiagLoc,
1970                                    Value.getUnionField()->getType(),
1971                                    Value.getUnionValue(), Usage);
1972   }
1973   if (Value.isStruct()) {
1974     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1975     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1976       unsigned BaseIndex = 0;
1977       for (const CXXBaseSpecifier &BS : CD->bases()) {
1978         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1979                                      Value.getStructBase(BaseIndex), Usage))
1980           return false;
1981         ++BaseIndex;
1982       }
1983     }
1984     for (const auto *I : RD->fields()) {
1985       if (I->isUnnamedBitfield())
1986         continue;
1987 
1988       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1989                                    Value.getStructField(I->getFieldIndex()),
1990                                    Usage))
1991         return false;
1992     }
1993   }
1994 
1995   if (Value.isLValue()) {
1996     LValue LVal;
1997     LVal.setFrom(Info.Ctx, Value);
1998     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
1999   }
2000 
2001   if (Value.isMemberPointer())
2002     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2003 
2004   // Everything else is fine.
2005   return true;
2006 }
2007 
2008 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2009   // A null base expression indicates a null pointer.  These are always
2010   // evaluatable, and they are false unless the offset is zero.
2011   if (!Value.getLValueBase()) {
2012     Result = !Value.getLValueOffset().isZero();
2013     return true;
2014   }
2015 
2016   // We have a non-null base.  These are generally known to be true, but if it's
2017   // a weak declaration it can be null at runtime.
2018   Result = true;
2019   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2020   return !Decl || !Decl->isWeak();
2021 }
2022 
2023 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2024   switch (Val.getKind()) {
2025   case APValue::Uninitialized:
2026     return false;
2027   case APValue::Int:
2028     Result = Val.getInt().getBoolValue();
2029     return true;
2030   case APValue::Float:
2031     Result = !Val.getFloat().isZero();
2032     return true;
2033   case APValue::ComplexInt:
2034     Result = Val.getComplexIntReal().getBoolValue() ||
2035              Val.getComplexIntImag().getBoolValue();
2036     return true;
2037   case APValue::ComplexFloat:
2038     Result = !Val.getComplexFloatReal().isZero() ||
2039              !Val.getComplexFloatImag().isZero();
2040     return true;
2041   case APValue::LValue:
2042     return EvalPointerValueAsBool(Val, Result);
2043   case APValue::MemberPointer:
2044     Result = Val.getMemberPointerDecl();
2045     return true;
2046   case APValue::Vector:
2047   case APValue::Array:
2048   case APValue::Struct:
2049   case APValue::Union:
2050   case APValue::AddrLabelDiff:
2051     return false;
2052   }
2053 
2054   llvm_unreachable("unknown APValue kind");
2055 }
2056 
2057 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2058                                        EvalInfo &Info) {
2059   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2060   APValue Val;
2061   if (!Evaluate(Val, Info, E))
2062     return false;
2063   return HandleConversionToBool(Val, Result);
2064 }
2065 
2066 template<typename T>
2067 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2068                            const T &SrcValue, QualType DestType) {
2069   Info.CCEDiag(E, diag::note_constexpr_overflow)
2070     << SrcValue << DestType;
2071   return Info.noteUndefinedBehavior();
2072 }
2073 
2074 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2075                                  QualType SrcType, const APFloat &Value,
2076                                  QualType DestType, APSInt &Result) {
2077   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2078   // Determine whether we are converting to unsigned or signed.
2079   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2080 
2081   Result = APSInt(DestWidth, !DestSigned);
2082   bool ignored;
2083   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2084       & APFloat::opInvalidOp)
2085     return HandleOverflow(Info, E, Value, DestType);
2086   return true;
2087 }
2088 
2089 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2090                                    QualType SrcType, QualType DestType,
2091                                    APFloat &Result) {
2092   APFloat Value = Result;
2093   bool ignored;
2094   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2095                      APFloat::rmNearestTiesToEven, &ignored)
2096       & APFloat::opOverflow)
2097     return HandleOverflow(Info, E, Value, DestType);
2098   return true;
2099 }
2100 
2101 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2102                                  QualType DestType, QualType SrcType,
2103                                  const APSInt &Value) {
2104   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2105   // Figure out if this is a truncate, extend or noop cast.
2106   // If the input is signed, do a sign extend, noop, or truncate.
2107   APSInt Result = Value.extOrTrunc(DestWidth);
2108   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2109   if (DestType->isBooleanType())
2110     Result = Value.getBoolValue();
2111   return Result;
2112 }
2113 
2114 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2115                                  QualType SrcType, const APSInt &Value,
2116                                  QualType DestType, APFloat &Result) {
2117   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2118   if (Result.convertFromAPInt(Value, Value.isSigned(),
2119                               APFloat::rmNearestTiesToEven)
2120       & APFloat::opOverflow)
2121     return HandleOverflow(Info, E, Value, DestType);
2122   return true;
2123 }
2124 
2125 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2126                                   APValue &Value, const FieldDecl *FD) {
2127   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2128 
2129   if (!Value.isInt()) {
2130     // Trying to store a pointer-cast-to-integer into a bitfield.
2131     // FIXME: In this case, we should provide the diagnostic for casting
2132     // a pointer to an integer.
2133     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2134     Info.FFDiag(E);
2135     return false;
2136   }
2137 
2138   APSInt &Int = Value.getInt();
2139   unsigned OldBitWidth = Int.getBitWidth();
2140   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2141   if (NewBitWidth < OldBitWidth)
2142     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2143   return true;
2144 }
2145 
2146 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2147                                   llvm::APInt &Res) {
2148   APValue SVal;
2149   if (!Evaluate(SVal, Info, E))
2150     return false;
2151   if (SVal.isInt()) {
2152     Res = SVal.getInt();
2153     return true;
2154   }
2155   if (SVal.isFloat()) {
2156     Res = SVal.getFloat().bitcastToAPInt();
2157     return true;
2158   }
2159   if (SVal.isVector()) {
2160     QualType VecTy = E->getType();
2161     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2162     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2163     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2164     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2165     Res = llvm::APInt::getNullValue(VecSize);
2166     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2167       APValue &Elt = SVal.getVectorElt(i);
2168       llvm::APInt EltAsInt;
2169       if (Elt.isInt()) {
2170         EltAsInt = Elt.getInt();
2171       } else if (Elt.isFloat()) {
2172         EltAsInt = Elt.getFloat().bitcastToAPInt();
2173       } else {
2174         // Don't try to handle vectors of anything other than int or float
2175         // (not sure if it's possible to hit this case).
2176         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2177         return false;
2178       }
2179       unsigned BaseEltSize = EltAsInt.getBitWidth();
2180       if (BigEndian)
2181         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2182       else
2183         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2184     }
2185     return true;
2186   }
2187   // Give up if the input isn't an int, float, or vector.  For example, we
2188   // reject "(v4i16)(intptr_t)&a".
2189   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2190   return false;
2191 }
2192 
2193 /// Perform the given integer operation, which is known to need at most BitWidth
2194 /// bits, and check for overflow in the original type (if that type was not an
2195 /// unsigned type).
2196 template<typename Operation>
2197 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2198                                  const APSInt &LHS, const APSInt &RHS,
2199                                  unsigned BitWidth, Operation Op,
2200                                  APSInt &Result) {
2201   if (LHS.isUnsigned()) {
2202     Result = Op(LHS, RHS);
2203     return true;
2204   }
2205 
2206   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2207   Result = Value.trunc(LHS.getBitWidth());
2208   if (Result.extend(BitWidth) != Value) {
2209     if (Info.checkingForOverflow())
2210       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2211                                        diag::warn_integer_constant_overflow)
2212           << Result.toString(10) << E->getType();
2213     else
2214       return HandleOverflow(Info, E, Value, E->getType());
2215   }
2216   return true;
2217 }
2218 
2219 /// Perform the given binary integer operation.
2220 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2221                               BinaryOperatorKind Opcode, APSInt RHS,
2222                               APSInt &Result) {
2223   switch (Opcode) {
2224   default:
2225     Info.FFDiag(E);
2226     return false;
2227   case BO_Mul:
2228     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2229                                 std::multiplies<APSInt>(), Result);
2230   case BO_Add:
2231     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2232                                 std::plus<APSInt>(), Result);
2233   case BO_Sub:
2234     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2235                                 std::minus<APSInt>(), Result);
2236   case BO_And: Result = LHS & RHS; return true;
2237   case BO_Xor: Result = LHS ^ RHS; return true;
2238   case BO_Or:  Result = LHS | RHS; return true;
2239   case BO_Div:
2240   case BO_Rem:
2241     if (RHS == 0) {
2242       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2243       return false;
2244     }
2245     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2246     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2247     // this operation and gives the two's complement result.
2248     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2249         LHS.isSigned() && LHS.isMinSignedValue())
2250       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2251                             E->getType());
2252     return true;
2253   case BO_Shl: {
2254     if (Info.getLangOpts().OpenCL)
2255       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2256       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2257                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2258                     RHS.isUnsigned());
2259     else if (RHS.isSigned() && RHS.isNegative()) {
2260       // During constant-folding, a negative shift is an opposite shift. Such
2261       // a shift is not a constant expression.
2262       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2263       RHS = -RHS;
2264       goto shift_right;
2265     }
2266   shift_left:
2267     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2268     // the shifted type.
2269     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2270     if (SA != RHS) {
2271       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2272         << RHS << E->getType() << LHS.getBitWidth();
2273     } else if (LHS.isSigned()) {
2274       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2275       // operand, and must not overflow the corresponding unsigned type.
2276       if (LHS.isNegative())
2277         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2278       else if (LHS.countLeadingZeros() < SA)
2279         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2280     }
2281     Result = LHS << SA;
2282     return true;
2283   }
2284   case BO_Shr: {
2285     if (Info.getLangOpts().OpenCL)
2286       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2287       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2288                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2289                     RHS.isUnsigned());
2290     else if (RHS.isSigned() && RHS.isNegative()) {
2291       // During constant-folding, a negative shift is an opposite shift. Such a
2292       // shift is not a constant expression.
2293       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2294       RHS = -RHS;
2295       goto shift_left;
2296     }
2297   shift_right:
2298     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2299     // shifted type.
2300     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2301     if (SA != RHS)
2302       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2303         << RHS << E->getType() << LHS.getBitWidth();
2304     Result = LHS >> SA;
2305     return true;
2306   }
2307 
2308   case BO_LT: Result = LHS < RHS; return true;
2309   case BO_GT: Result = LHS > RHS; return true;
2310   case BO_LE: Result = LHS <= RHS; return true;
2311   case BO_GE: Result = LHS >= RHS; return true;
2312   case BO_EQ: Result = LHS == RHS; return true;
2313   case BO_NE: Result = LHS != RHS; return true;
2314   case BO_Cmp:
2315     llvm_unreachable("BO_Cmp should be handled elsewhere");
2316   }
2317 }
2318 
2319 /// Perform the given binary floating-point operation, in-place, on LHS.
2320 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2321                                   APFloat &LHS, BinaryOperatorKind Opcode,
2322                                   const APFloat &RHS) {
2323   switch (Opcode) {
2324   default:
2325     Info.FFDiag(E);
2326     return false;
2327   case BO_Mul:
2328     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2329     break;
2330   case BO_Add:
2331     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2332     break;
2333   case BO_Sub:
2334     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2335     break;
2336   case BO_Div:
2337     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2338     break;
2339   }
2340 
2341   if (LHS.isInfinity() || LHS.isNaN()) {
2342     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2343     return Info.noteUndefinedBehavior();
2344   }
2345   return true;
2346 }
2347 
2348 /// Cast an lvalue referring to a base subobject to a derived class, by
2349 /// truncating the lvalue's path to the given length.
2350 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2351                                const RecordDecl *TruncatedType,
2352                                unsigned TruncatedElements) {
2353   SubobjectDesignator &D = Result.Designator;
2354 
2355   // Check we actually point to a derived class object.
2356   if (TruncatedElements == D.Entries.size())
2357     return true;
2358   assert(TruncatedElements >= D.MostDerivedPathLength &&
2359          "not casting to a derived class");
2360   if (!Result.checkSubobject(Info, E, CSK_Derived))
2361     return false;
2362 
2363   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2364   const RecordDecl *RD = TruncatedType;
2365   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2366     if (RD->isInvalidDecl()) return false;
2367     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2368     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2369     if (isVirtualBaseClass(D.Entries[I]))
2370       Result.Offset -= Layout.getVBaseClassOffset(Base);
2371     else
2372       Result.Offset -= Layout.getBaseClassOffset(Base);
2373     RD = Base;
2374   }
2375   D.Entries.resize(TruncatedElements);
2376   return true;
2377 }
2378 
2379 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2380                                    const CXXRecordDecl *Derived,
2381                                    const CXXRecordDecl *Base,
2382                                    const ASTRecordLayout *RL = nullptr) {
2383   if (!RL) {
2384     if (Derived->isInvalidDecl()) return false;
2385     RL = &Info.Ctx.getASTRecordLayout(Derived);
2386   }
2387 
2388   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2389   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2390   return true;
2391 }
2392 
2393 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2394                              const CXXRecordDecl *DerivedDecl,
2395                              const CXXBaseSpecifier *Base) {
2396   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2397 
2398   if (!Base->isVirtual())
2399     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2400 
2401   SubobjectDesignator &D = Obj.Designator;
2402   if (D.Invalid)
2403     return false;
2404 
2405   // Extract most-derived object and corresponding type.
2406   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2407   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2408     return false;
2409 
2410   // Find the virtual base class.
2411   if (DerivedDecl->isInvalidDecl()) return false;
2412   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2413   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2414   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2415   return true;
2416 }
2417 
2418 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2419                                  QualType Type, LValue &Result) {
2420   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2421                                      PathE = E->path_end();
2422        PathI != PathE; ++PathI) {
2423     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2424                           *PathI))
2425       return false;
2426     Type = (*PathI)->getType();
2427   }
2428   return true;
2429 }
2430 
2431 /// Update LVal to refer to the given field, which must be a member of the type
2432 /// currently described by LVal.
2433 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2434                                const FieldDecl *FD,
2435                                const ASTRecordLayout *RL = nullptr) {
2436   if (!RL) {
2437     if (FD->getParent()->isInvalidDecl()) return false;
2438     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2439   }
2440 
2441   unsigned I = FD->getFieldIndex();
2442   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2443   LVal.addDecl(Info, E, FD);
2444   return true;
2445 }
2446 
2447 /// Update LVal to refer to the given indirect field.
2448 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2449                                        LValue &LVal,
2450                                        const IndirectFieldDecl *IFD) {
2451   for (const auto *C : IFD->chain())
2452     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2453       return false;
2454   return true;
2455 }
2456 
2457 /// Get the size of the given type in char units.
2458 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2459                          QualType Type, CharUnits &Size) {
2460   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2461   // extension.
2462   if (Type->isVoidType() || Type->isFunctionType()) {
2463     Size = CharUnits::One();
2464     return true;
2465   }
2466 
2467   if (Type->isDependentType()) {
2468     Info.FFDiag(Loc);
2469     return false;
2470   }
2471 
2472   if (!Type->isConstantSizeType()) {
2473     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2474     // FIXME: Better diagnostic.
2475     Info.FFDiag(Loc);
2476     return false;
2477   }
2478 
2479   Size = Info.Ctx.getTypeSizeInChars(Type);
2480   return true;
2481 }
2482 
2483 /// Update a pointer value to model pointer arithmetic.
2484 /// \param Info - Information about the ongoing evaluation.
2485 /// \param E - The expression being evaluated, for diagnostic purposes.
2486 /// \param LVal - The pointer value to be updated.
2487 /// \param EltTy - The pointee type represented by LVal.
2488 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2489 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2490                                         LValue &LVal, QualType EltTy,
2491                                         APSInt Adjustment) {
2492   CharUnits SizeOfPointee;
2493   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2494     return false;
2495 
2496   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2497   return true;
2498 }
2499 
2500 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2501                                         LValue &LVal, QualType EltTy,
2502                                         int64_t Adjustment) {
2503   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2504                                      APSInt::get(Adjustment));
2505 }
2506 
2507 /// Update an lvalue to refer to a component of a complex number.
2508 /// \param Info - Information about the ongoing evaluation.
2509 /// \param LVal - The lvalue to be updated.
2510 /// \param EltTy - The complex number's component type.
2511 /// \param Imag - False for the real component, true for the imaginary.
2512 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2513                                        LValue &LVal, QualType EltTy,
2514                                        bool Imag) {
2515   if (Imag) {
2516     CharUnits SizeOfComponent;
2517     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2518       return false;
2519     LVal.Offset += SizeOfComponent;
2520   }
2521   LVal.addComplex(Info, E, EltTy, Imag);
2522   return true;
2523 }
2524 
2525 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2526                                            QualType Type, const LValue &LVal,
2527                                            APValue &RVal);
2528 
2529 /// Try to evaluate the initializer for a variable declaration.
2530 ///
2531 /// \param Info   Information about the ongoing evaluation.
2532 /// \param E      An expression to be used when printing diagnostics.
2533 /// \param VD     The variable whose initializer should be obtained.
2534 /// \param Frame  The frame in which the variable was created. Must be null
2535 ///               if this variable is not local to the evaluation.
2536 /// \param Result Filled in with a pointer to the value of the variable.
2537 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2538                                 const VarDecl *VD, CallStackFrame *Frame,
2539                                 APValue *&Result, const LValue *LVal) {
2540 
2541   // If this is a parameter to an active constexpr function call, perform
2542   // argument substitution.
2543   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2544     // Assume arguments of a potential constant expression are unknown
2545     // constant expressions.
2546     if (Info.checkingPotentialConstantExpression())
2547       return false;
2548     if (!Frame || !Frame->Arguments) {
2549       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2550       return false;
2551     }
2552     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2553     return true;
2554   }
2555 
2556   // If this is a local variable, dig out its value.
2557   if (Frame) {
2558     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2559                   : Frame->getCurrentTemporary(VD);
2560     if (!Result) {
2561       // Assume variables referenced within a lambda's call operator that were
2562       // not declared within the call operator are captures and during checking
2563       // of a potential constant expression, assume they are unknown constant
2564       // expressions.
2565       assert(isLambdaCallOperator(Frame->Callee) &&
2566              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2567              "missing value for local variable");
2568       if (Info.checkingPotentialConstantExpression())
2569         return false;
2570       // FIXME: implement capture evaluation during constant expr evaluation.
2571       Info.FFDiag(E->getBeginLoc(),
2572                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2573           << "captures not currently allowed";
2574       return false;
2575     }
2576     return true;
2577   }
2578 
2579   // Dig out the initializer, and use the declaration which it's attached to.
2580   const Expr *Init = VD->getAnyInitializer(VD);
2581   if (!Init || Init->isValueDependent()) {
2582     // If we're checking a potential constant expression, the variable could be
2583     // initialized later.
2584     if (!Info.checkingPotentialConstantExpression())
2585       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2586     return false;
2587   }
2588 
2589   // If we're currently evaluating the initializer of this declaration, use that
2590   // in-flight value.
2591   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2592     Result = Info.EvaluatingDeclValue;
2593     return true;
2594   }
2595 
2596   // Never evaluate the initializer of a weak variable. We can't be sure that
2597   // this is the definition which will be used.
2598   if (VD->isWeak()) {
2599     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2600     return false;
2601   }
2602 
2603   // Check that we can fold the initializer. In C++, we will have already done
2604   // this in the cases where it matters for conformance.
2605   SmallVector<PartialDiagnosticAt, 8> Notes;
2606   if (!VD->evaluateValue(Notes)) {
2607     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2608               Notes.size() + 1) << VD;
2609     Info.Note(VD->getLocation(), diag::note_declared_at);
2610     Info.addNotes(Notes);
2611     return false;
2612   } else if (!VD->checkInitIsICE()) {
2613     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2614                  Notes.size() + 1) << VD;
2615     Info.Note(VD->getLocation(), diag::note_declared_at);
2616     Info.addNotes(Notes);
2617   }
2618 
2619   Result = VD->getEvaluatedValue();
2620   return true;
2621 }
2622 
2623 static bool IsConstNonVolatile(QualType T) {
2624   Qualifiers Quals = T.getQualifiers();
2625   return Quals.hasConst() && !Quals.hasVolatile();
2626 }
2627 
2628 /// Get the base index of the given base class within an APValue representing
2629 /// the given derived class.
2630 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2631                              const CXXRecordDecl *Base) {
2632   Base = Base->getCanonicalDecl();
2633   unsigned Index = 0;
2634   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2635          E = Derived->bases_end(); I != E; ++I, ++Index) {
2636     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2637       return Index;
2638   }
2639 
2640   llvm_unreachable("base class missing from derived class's bases list");
2641 }
2642 
2643 /// Extract the value of a character from a string literal.
2644 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2645                                             uint64_t Index) {
2646   // FIXME: Support MakeStringConstant
2647   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2648     std::string Str;
2649     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2650     assert(Index <= Str.size() && "Index too large");
2651     return APSInt::getUnsigned(Str.c_str()[Index]);
2652   }
2653 
2654   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2655     Lit = PE->getFunctionName();
2656   const StringLiteral *S = cast<StringLiteral>(Lit);
2657   const ConstantArrayType *CAT =
2658       Info.Ctx.getAsConstantArrayType(S->getType());
2659   assert(CAT && "string literal isn't an array");
2660   QualType CharType = CAT->getElementType();
2661   assert(CharType->isIntegerType() && "unexpected character type");
2662 
2663   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2664                CharType->isUnsignedIntegerType());
2665   if (Index < S->getLength())
2666     Value = S->getCodeUnit(Index);
2667   return Value;
2668 }
2669 
2670 // Expand a string literal into an array of characters.
2671 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2672                                 APValue &Result) {
2673   const StringLiteral *S = cast<StringLiteral>(Lit);
2674   const ConstantArrayType *CAT =
2675       Info.Ctx.getAsConstantArrayType(S->getType());
2676   assert(CAT && "string literal isn't an array");
2677   QualType CharType = CAT->getElementType();
2678   assert(CharType->isIntegerType() && "unexpected character type");
2679 
2680   unsigned Elts = CAT->getSize().getZExtValue();
2681   Result = APValue(APValue::UninitArray(),
2682                    std::min(S->getLength(), Elts), Elts);
2683   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2684                CharType->isUnsignedIntegerType());
2685   if (Result.hasArrayFiller())
2686     Result.getArrayFiller() = APValue(Value);
2687   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2688     Value = S->getCodeUnit(I);
2689     Result.getArrayInitializedElt(I) = APValue(Value);
2690   }
2691 }
2692 
2693 // Expand an array so that it has more than Index filled elements.
2694 static void expandArray(APValue &Array, unsigned Index) {
2695   unsigned Size = Array.getArraySize();
2696   assert(Index < Size);
2697 
2698   // Always at least double the number of elements for which we store a value.
2699   unsigned OldElts = Array.getArrayInitializedElts();
2700   unsigned NewElts = std::max(Index+1, OldElts * 2);
2701   NewElts = std::min(Size, std::max(NewElts, 8u));
2702 
2703   // Copy the data across.
2704   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2705   for (unsigned I = 0; I != OldElts; ++I)
2706     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2707   for (unsigned I = OldElts; I != NewElts; ++I)
2708     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2709   if (NewValue.hasArrayFiller())
2710     NewValue.getArrayFiller() = Array.getArrayFiller();
2711   Array.swap(NewValue);
2712 }
2713 
2714 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2715 /// conversion. If it's of class type, we may assume that the copy operation
2716 /// is trivial. Note that this is never true for a union type with fields
2717 /// (because the copy always "reads" the active member) and always true for
2718 /// a non-class type.
2719 static bool isReadByLvalueToRvalueConversion(QualType T) {
2720   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2721   if (!RD || (RD->isUnion() && !RD->field_empty()))
2722     return true;
2723   if (RD->isEmpty())
2724     return false;
2725 
2726   for (auto *Field : RD->fields())
2727     if (isReadByLvalueToRvalueConversion(Field->getType()))
2728       return true;
2729 
2730   for (auto &BaseSpec : RD->bases())
2731     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2732       return true;
2733 
2734   return false;
2735 }
2736 
2737 /// Diagnose an attempt to read from any unreadable field within the specified
2738 /// type, which might be a class type.
2739 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2740                                      QualType T) {
2741   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2742   if (!RD)
2743     return false;
2744 
2745   if (!RD->hasMutableFields())
2746     return false;
2747 
2748   for (auto *Field : RD->fields()) {
2749     // If we're actually going to read this field in some way, then it can't
2750     // be mutable. If we're in a union, then assigning to a mutable field
2751     // (even an empty one) can change the active member, so that's not OK.
2752     // FIXME: Add core issue number for the union case.
2753     if (Field->isMutable() &&
2754         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2755       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2756       Info.Note(Field->getLocation(), diag::note_declared_at);
2757       return true;
2758     }
2759 
2760     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2761       return true;
2762   }
2763 
2764   for (auto &BaseSpec : RD->bases())
2765     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2766       return true;
2767 
2768   // All mutable fields were empty, and thus not actually read.
2769   return false;
2770 }
2771 
2772 namespace {
2773 /// A handle to a complete object (an object that is not a subobject of
2774 /// another object).
2775 struct CompleteObject {
2776   /// The value of the complete object.
2777   APValue *Value;
2778   /// The type of the complete object.
2779   QualType Type;
2780   bool LifetimeStartedInEvaluation;
2781 
2782   CompleteObject() : Value(nullptr) {}
2783   CompleteObject(APValue *Value, QualType Type,
2784                  bool LifetimeStartedInEvaluation)
2785       : Value(Value), Type(Type),
2786         LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2787     assert(Value && "missing value for complete object");
2788   }
2789 
2790   explicit operator bool() const { return Value; }
2791 };
2792 } // end anonymous namespace
2793 
2794 /// Find the designated sub-object of an rvalue.
2795 template<typename SubobjectHandler>
2796 typename SubobjectHandler::result_type
2797 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2798               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2799   if (Sub.Invalid)
2800     // A diagnostic will have already been produced.
2801     return handler.failed();
2802   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2803     if (Info.getLangOpts().CPlusPlus11)
2804       Info.FFDiag(E, Sub.isOnePastTheEnd()
2805                          ? diag::note_constexpr_access_past_end
2806                          : diag::note_constexpr_access_unsized_array)
2807           << handler.AccessKind;
2808     else
2809       Info.FFDiag(E);
2810     return handler.failed();
2811   }
2812 
2813   APValue *O = Obj.Value;
2814   QualType ObjType = Obj.Type;
2815   const FieldDecl *LastField = nullptr;
2816   const bool MayReadMutableMembers =
2817       Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2818 
2819   // Walk the designator's path to find the subobject.
2820   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2821     if (O->isUninit()) {
2822       if (!Info.checkingPotentialConstantExpression())
2823         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2824       return handler.failed();
2825     }
2826 
2827     if (I == N) {
2828       // If we are reading an object of class type, there may still be more
2829       // things we need to check: if there are any mutable subobjects, we
2830       // cannot perform this read. (This only happens when performing a trivial
2831       // copy or assignment.)
2832       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2833           !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2834         return handler.failed();
2835 
2836       if (!handler.found(*O, ObjType))
2837         return false;
2838 
2839       // If we modified a bit-field, truncate it to the right width.
2840       if (handler.AccessKind != AK_Read &&
2841           LastField && LastField->isBitField() &&
2842           !truncateBitfieldValue(Info, E, *O, LastField))
2843         return false;
2844 
2845       return true;
2846     }
2847 
2848     LastField = nullptr;
2849     if (ObjType->isArrayType()) {
2850       // Next subobject is an array element.
2851       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2852       assert(CAT && "vla in literal type?");
2853       uint64_t Index = Sub.Entries[I].ArrayIndex;
2854       if (CAT->getSize().ule(Index)) {
2855         // Note, it should not be possible to form a pointer with a valid
2856         // designator which points more than one past the end of the array.
2857         if (Info.getLangOpts().CPlusPlus11)
2858           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2859             << handler.AccessKind;
2860         else
2861           Info.FFDiag(E);
2862         return handler.failed();
2863       }
2864 
2865       ObjType = CAT->getElementType();
2866 
2867       // An array object is represented as either an Array APValue or as an
2868       // LValue which refers to a string literal.
2869       if (O->isLValue()) {
2870         assert(I == N - 1 && "extracting subobject of character?");
2871         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2872         if (handler.AccessKind != AK_Read)
2873           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2874                               *O);
2875         else
2876           return handler.foundString(*O, ObjType, Index);
2877       }
2878 
2879       if (O->getArrayInitializedElts() > Index)
2880         O = &O->getArrayInitializedElt(Index);
2881       else if (handler.AccessKind != AK_Read) {
2882         expandArray(*O, Index);
2883         O = &O->getArrayInitializedElt(Index);
2884       } else
2885         O = &O->getArrayFiller();
2886     } else if (ObjType->isAnyComplexType()) {
2887       // Next subobject is a complex number.
2888       uint64_t Index = Sub.Entries[I].ArrayIndex;
2889       if (Index > 1) {
2890         if (Info.getLangOpts().CPlusPlus11)
2891           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2892             << handler.AccessKind;
2893         else
2894           Info.FFDiag(E);
2895         return handler.failed();
2896       }
2897 
2898       bool WasConstQualified = ObjType.isConstQualified();
2899       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2900       if (WasConstQualified)
2901         ObjType.addConst();
2902 
2903       assert(I == N - 1 && "extracting subobject of scalar?");
2904       if (O->isComplexInt()) {
2905         return handler.found(Index ? O->getComplexIntImag()
2906                                    : O->getComplexIntReal(), ObjType);
2907       } else {
2908         assert(O->isComplexFloat());
2909         return handler.found(Index ? O->getComplexFloatImag()
2910                                    : O->getComplexFloatReal(), ObjType);
2911       }
2912     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2913       // In C++14 onwards, it is permitted to read a mutable member whose
2914       // lifetime began within the evaluation.
2915       // FIXME: Should we also allow this in C++11?
2916       if (Field->isMutable() && handler.AccessKind == AK_Read &&
2917           !MayReadMutableMembers) {
2918         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2919           << Field;
2920         Info.Note(Field->getLocation(), diag::note_declared_at);
2921         return handler.failed();
2922       }
2923 
2924       // Next subobject is a class, struct or union field.
2925       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2926       if (RD->isUnion()) {
2927         const FieldDecl *UnionField = O->getUnionField();
2928         if (!UnionField ||
2929             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2930           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2931             << handler.AccessKind << Field << !UnionField << UnionField;
2932           return handler.failed();
2933         }
2934         O = &O->getUnionValue();
2935       } else
2936         O = &O->getStructField(Field->getFieldIndex());
2937 
2938       bool WasConstQualified = ObjType.isConstQualified();
2939       ObjType = Field->getType();
2940       if (WasConstQualified && !Field->isMutable())
2941         ObjType.addConst();
2942 
2943       if (ObjType.isVolatileQualified()) {
2944         if (Info.getLangOpts().CPlusPlus) {
2945           // FIXME: Include a description of the path to the volatile subobject.
2946           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2947             << handler.AccessKind << 2 << Field;
2948           Info.Note(Field->getLocation(), diag::note_declared_at);
2949         } else {
2950           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2951         }
2952         return handler.failed();
2953       }
2954 
2955       LastField = Field;
2956     } else {
2957       // Next subobject is a base class.
2958       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2959       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2960       O = &O->getStructBase(getBaseIndex(Derived, Base));
2961 
2962       bool WasConstQualified = ObjType.isConstQualified();
2963       ObjType = Info.Ctx.getRecordType(Base);
2964       if (WasConstQualified)
2965         ObjType.addConst();
2966     }
2967   }
2968 }
2969 
2970 namespace {
2971 struct ExtractSubobjectHandler {
2972   EvalInfo &Info;
2973   APValue &Result;
2974 
2975   static const AccessKinds AccessKind = AK_Read;
2976 
2977   typedef bool result_type;
2978   bool failed() { return false; }
2979   bool found(APValue &Subobj, QualType SubobjType) {
2980     Result = Subobj;
2981     return true;
2982   }
2983   bool found(APSInt &Value, QualType SubobjType) {
2984     Result = APValue(Value);
2985     return true;
2986   }
2987   bool found(APFloat &Value, QualType SubobjType) {
2988     Result = APValue(Value);
2989     return true;
2990   }
2991   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2992     Result = APValue(extractStringLiteralCharacter(
2993         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2994     return true;
2995   }
2996 };
2997 } // end anonymous namespace
2998 
2999 const AccessKinds ExtractSubobjectHandler::AccessKind;
3000 
3001 /// Extract the designated sub-object of an rvalue.
3002 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3003                              const CompleteObject &Obj,
3004                              const SubobjectDesignator &Sub,
3005                              APValue &Result) {
3006   ExtractSubobjectHandler Handler = { Info, Result };
3007   return findSubobject(Info, E, Obj, Sub, Handler);
3008 }
3009 
3010 namespace {
3011 struct ModifySubobjectHandler {
3012   EvalInfo &Info;
3013   APValue &NewVal;
3014   const Expr *E;
3015 
3016   typedef bool result_type;
3017   static const AccessKinds AccessKind = AK_Assign;
3018 
3019   bool checkConst(QualType QT) {
3020     // Assigning to a const object has undefined behavior.
3021     if (QT.isConstQualified()) {
3022       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3023       return false;
3024     }
3025     return true;
3026   }
3027 
3028   bool failed() { return false; }
3029   bool found(APValue &Subobj, QualType SubobjType) {
3030     if (!checkConst(SubobjType))
3031       return false;
3032     // We've been given ownership of NewVal, so just swap it in.
3033     Subobj.swap(NewVal);
3034     return true;
3035   }
3036   bool found(APSInt &Value, QualType SubobjType) {
3037     if (!checkConst(SubobjType))
3038       return false;
3039     if (!NewVal.isInt()) {
3040       // Maybe trying to write a cast pointer value into a complex?
3041       Info.FFDiag(E);
3042       return false;
3043     }
3044     Value = NewVal.getInt();
3045     return true;
3046   }
3047   bool found(APFloat &Value, QualType SubobjType) {
3048     if (!checkConst(SubobjType))
3049       return false;
3050     Value = NewVal.getFloat();
3051     return true;
3052   }
3053   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3054     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3055   }
3056 };
3057 } // end anonymous namespace
3058 
3059 const AccessKinds ModifySubobjectHandler::AccessKind;
3060 
3061 /// Update the designated sub-object of an rvalue to the given value.
3062 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3063                             const CompleteObject &Obj,
3064                             const SubobjectDesignator &Sub,
3065                             APValue &NewVal) {
3066   ModifySubobjectHandler Handler = { Info, NewVal, E };
3067   return findSubobject(Info, E, Obj, Sub, Handler);
3068 }
3069 
3070 /// Find the position where two subobject designators diverge, or equivalently
3071 /// the length of the common initial subsequence.
3072 static unsigned FindDesignatorMismatch(QualType ObjType,
3073                                        const SubobjectDesignator &A,
3074                                        const SubobjectDesignator &B,
3075                                        bool &WasArrayIndex) {
3076   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3077   for (/**/; I != N; ++I) {
3078     if (!ObjType.isNull() &&
3079         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3080       // Next subobject is an array element.
3081       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3082         WasArrayIndex = true;
3083         return I;
3084       }
3085       if (ObjType->isAnyComplexType())
3086         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3087       else
3088         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3089     } else {
3090       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3091         WasArrayIndex = false;
3092         return I;
3093       }
3094       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3095         // Next subobject is a field.
3096         ObjType = FD->getType();
3097       else
3098         // Next subobject is a base class.
3099         ObjType = QualType();
3100     }
3101   }
3102   WasArrayIndex = false;
3103   return I;
3104 }
3105 
3106 /// Determine whether the given subobject designators refer to elements of the
3107 /// same array object.
3108 static bool AreElementsOfSameArray(QualType ObjType,
3109                                    const SubobjectDesignator &A,
3110                                    const SubobjectDesignator &B) {
3111   if (A.Entries.size() != B.Entries.size())
3112     return false;
3113 
3114   bool IsArray = A.MostDerivedIsArrayElement;
3115   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3116     // A is a subobject of the array element.
3117     return false;
3118 
3119   // If A (and B) designates an array element, the last entry will be the array
3120   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3121   // of length 1' case, and the entire path must match.
3122   bool WasArrayIndex;
3123   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3124   return CommonLength >= A.Entries.size() - IsArray;
3125 }
3126 
3127 /// Find the complete object to which an LValue refers.
3128 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3129                                          AccessKinds AK, const LValue &LVal,
3130                                          QualType LValType) {
3131   if (!LVal.Base) {
3132     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3133     return CompleteObject();
3134   }
3135 
3136   CallStackFrame *Frame = nullptr;
3137   if (LVal.getLValueCallIndex()) {
3138     Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3139     if (!Frame) {
3140       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3141         << AK << LVal.Base.is<const ValueDecl*>();
3142       NoteLValueLocation(Info, LVal.Base);
3143       return CompleteObject();
3144     }
3145   }
3146 
3147   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3148   // is not a constant expression (even if the object is non-volatile). We also
3149   // apply this rule to C++98, in order to conform to the expected 'volatile'
3150   // semantics.
3151   if (LValType.isVolatileQualified()) {
3152     if (Info.getLangOpts().CPlusPlus)
3153       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3154         << AK << LValType;
3155     else
3156       Info.FFDiag(E);
3157     return CompleteObject();
3158   }
3159 
3160   // Compute value storage location and type of base object.
3161   APValue *BaseVal = nullptr;
3162   QualType BaseType = getType(LVal.Base);
3163   bool LifetimeStartedInEvaluation = Frame;
3164 
3165   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3166     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3167     // In C++11, constexpr, non-volatile variables initialized with constant
3168     // expressions are constant expressions too. Inside constexpr functions,
3169     // parameters are constant expressions even if they're non-const.
3170     // In C++1y, objects local to a constant expression (those with a Frame) are
3171     // both readable and writable inside constant expressions.
3172     // In C, such things can also be folded, although they are not ICEs.
3173     const VarDecl *VD = dyn_cast<VarDecl>(D);
3174     if (VD) {
3175       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3176         VD = VDef;
3177     }
3178     if (!VD || VD->isInvalidDecl()) {
3179       Info.FFDiag(E);
3180       return CompleteObject();
3181     }
3182 
3183     // Accesses of volatile-qualified objects are not allowed.
3184     if (BaseType.isVolatileQualified()) {
3185       if (Info.getLangOpts().CPlusPlus) {
3186         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3187           << AK << 1 << VD;
3188         Info.Note(VD->getLocation(), diag::note_declared_at);
3189       } else {
3190         Info.FFDiag(E);
3191       }
3192       return CompleteObject();
3193     }
3194 
3195     // Unless we're looking at a local variable or argument in a constexpr call,
3196     // the variable we're reading must be const.
3197     if (!Frame) {
3198       if (Info.getLangOpts().CPlusPlus14 &&
3199           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3200         // OK, we can read and modify an object if we're in the process of
3201         // evaluating its initializer, because its lifetime began in this
3202         // evaluation.
3203       } else if (AK != AK_Read) {
3204         // All the remaining cases only permit reading.
3205         Info.FFDiag(E, diag::note_constexpr_modify_global);
3206         return CompleteObject();
3207       } else if (VD->isConstexpr()) {
3208         // OK, we can read this variable.
3209       } else if (BaseType->isIntegralOrEnumerationType()) {
3210         // In OpenCL if a variable is in constant address space it is a const value.
3211         if (!(BaseType.isConstQualified() ||
3212               (Info.getLangOpts().OpenCL &&
3213                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3214           if (Info.getLangOpts().CPlusPlus) {
3215             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3216             Info.Note(VD->getLocation(), diag::note_declared_at);
3217           } else {
3218             Info.FFDiag(E);
3219           }
3220           return CompleteObject();
3221         }
3222       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3223         // We support folding of const floating-point types, in order to make
3224         // static const data members of such types (supported as an extension)
3225         // more useful.
3226         if (Info.getLangOpts().CPlusPlus11) {
3227           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3228           Info.Note(VD->getLocation(), diag::note_declared_at);
3229         } else {
3230           Info.CCEDiag(E);
3231         }
3232       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3233         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3234         // Keep evaluating to see what we can do.
3235       } else {
3236         // FIXME: Allow folding of values of any literal type in all languages.
3237         if (Info.checkingPotentialConstantExpression() &&
3238             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3239           // The definition of this variable could be constexpr. We can't
3240           // access it right now, but may be able to in future.
3241         } else if (Info.getLangOpts().CPlusPlus11) {
3242           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3243           Info.Note(VD->getLocation(), diag::note_declared_at);
3244         } else {
3245           Info.FFDiag(E);
3246         }
3247         return CompleteObject();
3248       }
3249     }
3250 
3251     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3252       return CompleteObject();
3253   } else {
3254     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3255 
3256     if (!Frame) {
3257       if (const MaterializeTemporaryExpr *MTE =
3258               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3259         assert(MTE->getStorageDuration() == SD_Static &&
3260                "should have a frame for a non-global materialized temporary");
3261 
3262         // Per C++1y [expr.const]p2:
3263         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3264         //   - a [...] glvalue of integral or enumeration type that refers to
3265         //     a non-volatile const object [...]
3266         //   [...]
3267         //   - a [...] glvalue of literal type that refers to a non-volatile
3268         //     object whose lifetime began within the evaluation of e.
3269         //
3270         // C++11 misses the 'began within the evaluation of e' check and
3271         // instead allows all temporaries, including things like:
3272         //   int &&r = 1;
3273         //   int x = ++r;
3274         //   constexpr int k = r;
3275         // Therefore we use the C++14 rules in C++11 too.
3276         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3277         const ValueDecl *ED = MTE->getExtendingDecl();
3278         if (!(BaseType.isConstQualified() &&
3279               BaseType->isIntegralOrEnumerationType()) &&
3280             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3281           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3282           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3283           return CompleteObject();
3284         }
3285 
3286         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3287         assert(BaseVal && "got reference to unevaluated temporary");
3288         LifetimeStartedInEvaluation = true;
3289       } else {
3290         Info.FFDiag(E);
3291         return CompleteObject();
3292       }
3293     } else {
3294       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3295       assert(BaseVal && "missing value for temporary");
3296     }
3297 
3298     // Volatile temporary objects cannot be accessed in constant expressions.
3299     if (BaseType.isVolatileQualified()) {
3300       if (Info.getLangOpts().CPlusPlus) {
3301         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3302           << AK << 0;
3303         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3304       } else {
3305         Info.FFDiag(E);
3306       }
3307       return CompleteObject();
3308     }
3309   }
3310 
3311   // During the construction of an object, it is not yet 'const'.
3312   // FIXME: This doesn't do quite the right thing for const subobjects of the
3313   // object under construction.
3314   if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3315                                    LVal.getLValueCallIndex(),
3316                                    LVal.getLValueVersion())) {
3317     BaseType = Info.Ctx.getCanonicalType(BaseType);
3318     BaseType.removeLocalConst();
3319     LifetimeStartedInEvaluation = true;
3320   }
3321 
3322   // In C++14, we can't safely access any mutable state when we might be
3323   // evaluating after an unmodeled side effect.
3324   //
3325   // FIXME: Not all local state is mutable. Allow local constant subobjects
3326   // to be read here (but take care with 'mutable' fields).
3327   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3328        Info.EvalStatus.HasSideEffects) ||
3329       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3330     return CompleteObject();
3331 
3332   return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3333 }
3334 
3335 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3336 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3337 /// glvalue referred to by an entity of reference type.
3338 ///
3339 /// \param Info - Information about the ongoing evaluation.
3340 /// \param Conv - The expression for which we are performing the conversion.
3341 ///               Used for diagnostics.
3342 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3343 ///               case of a non-class type).
3344 /// \param LVal - The glvalue on which we are attempting to perform this action.
3345 /// \param RVal - The produced value will be placed here.
3346 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3347                                            QualType Type,
3348                                            const LValue &LVal, APValue &RVal) {
3349   if (LVal.Designator.Invalid)
3350     return false;
3351 
3352   // Check for special cases where there is no existing APValue to look at.
3353   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3354   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3355     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3356       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3357       // initializer until now for such expressions. Such an expression can't be
3358       // an ICE in C, so this only matters for fold.
3359       if (Type.isVolatileQualified()) {
3360         Info.FFDiag(Conv);
3361         return false;
3362       }
3363       APValue Lit;
3364       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3365         return false;
3366       CompleteObject LitObj(&Lit, Base->getType(), false);
3367       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3368     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3369       // We represent a string literal array as an lvalue pointing at the
3370       // corresponding expression, rather than building an array of chars.
3371       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3372       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3373       CompleteObject StrObj(&Str, Base->getType(), false);
3374       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3375     }
3376   }
3377 
3378   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3379   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3380 }
3381 
3382 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3383 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3384                              QualType LValType, APValue &Val) {
3385   if (LVal.Designator.Invalid)
3386     return false;
3387 
3388   if (!Info.getLangOpts().CPlusPlus14) {
3389     Info.FFDiag(E);
3390     return false;
3391   }
3392 
3393   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3394   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3395 }
3396 
3397 namespace {
3398 struct CompoundAssignSubobjectHandler {
3399   EvalInfo &Info;
3400   const Expr *E;
3401   QualType PromotedLHSType;
3402   BinaryOperatorKind Opcode;
3403   const APValue &RHS;
3404 
3405   static const AccessKinds AccessKind = AK_Assign;
3406 
3407   typedef bool result_type;
3408 
3409   bool checkConst(QualType QT) {
3410     // Assigning to a const object has undefined behavior.
3411     if (QT.isConstQualified()) {
3412       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3413       return false;
3414     }
3415     return true;
3416   }
3417 
3418   bool failed() { return false; }
3419   bool found(APValue &Subobj, QualType SubobjType) {
3420     switch (Subobj.getKind()) {
3421     case APValue::Int:
3422       return found(Subobj.getInt(), SubobjType);
3423     case APValue::Float:
3424       return found(Subobj.getFloat(), SubobjType);
3425     case APValue::ComplexInt:
3426     case APValue::ComplexFloat:
3427       // FIXME: Implement complex compound assignment.
3428       Info.FFDiag(E);
3429       return false;
3430     case APValue::LValue:
3431       return foundPointer(Subobj, SubobjType);
3432     default:
3433       // FIXME: can this happen?
3434       Info.FFDiag(E);
3435       return false;
3436     }
3437   }
3438   bool found(APSInt &Value, QualType SubobjType) {
3439     if (!checkConst(SubobjType))
3440       return false;
3441 
3442     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3443       // We don't support compound assignment on integer-cast-to-pointer
3444       // values.
3445       Info.FFDiag(E);
3446       return false;
3447     }
3448 
3449     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3450                                     SubobjType, Value);
3451     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3452       return false;
3453     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3454     return true;
3455   }
3456   bool found(APFloat &Value, QualType SubobjType) {
3457     return checkConst(SubobjType) &&
3458            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3459                                   Value) &&
3460            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3461            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3462   }
3463   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3464     if (!checkConst(SubobjType))
3465       return false;
3466 
3467     QualType PointeeType;
3468     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3469       PointeeType = PT->getPointeeType();
3470 
3471     if (PointeeType.isNull() || !RHS.isInt() ||
3472         (Opcode != BO_Add && Opcode != BO_Sub)) {
3473       Info.FFDiag(E);
3474       return false;
3475     }
3476 
3477     APSInt Offset = RHS.getInt();
3478     if (Opcode == BO_Sub)
3479       negateAsSigned(Offset);
3480 
3481     LValue LVal;
3482     LVal.setFrom(Info.Ctx, Subobj);
3483     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3484       return false;
3485     LVal.moveInto(Subobj);
3486     return true;
3487   }
3488   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3489     llvm_unreachable("shouldn't encounter string elements here");
3490   }
3491 };
3492 } // end anonymous namespace
3493 
3494 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3495 
3496 /// Perform a compound assignment of LVal <op>= RVal.
3497 static bool handleCompoundAssignment(
3498     EvalInfo &Info, const Expr *E,
3499     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3500     BinaryOperatorKind Opcode, const APValue &RVal) {
3501   if (LVal.Designator.Invalid)
3502     return false;
3503 
3504   if (!Info.getLangOpts().CPlusPlus14) {
3505     Info.FFDiag(E);
3506     return false;
3507   }
3508 
3509   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3510   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3511                                              RVal };
3512   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3513 }
3514 
3515 namespace {
3516 struct IncDecSubobjectHandler {
3517   EvalInfo &Info;
3518   const UnaryOperator *E;
3519   AccessKinds AccessKind;
3520   APValue *Old;
3521 
3522   typedef bool result_type;
3523 
3524   bool checkConst(QualType QT) {
3525     // Assigning to a const object has undefined behavior.
3526     if (QT.isConstQualified()) {
3527       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3528       return false;
3529     }
3530     return true;
3531   }
3532 
3533   bool failed() { return false; }
3534   bool found(APValue &Subobj, QualType SubobjType) {
3535     // Stash the old value. Also clear Old, so we don't clobber it later
3536     // if we're post-incrementing a complex.
3537     if (Old) {
3538       *Old = Subobj;
3539       Old = nullptr;
3540     }
3541 
3542     switch (Subobj.getKind()) {
3543     case APValue::Int:
3544       return found(Subobj.getInt(), SubobjType);
3545     case APValue::Float:
3546       return found(Subobj.getFloat(), SubobjType);
3547     case APValue::ComplexInt:
3548       return found(Subobj.getComplexIntReal(),
3549                    SubobjType->castAs<ComplexType>()->getElementType()
3550                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3551     case APValue::ComplexFloat:
3552       return found(Subobj.getComplexFloatReal(),
3553                    SubobjType->castAs<ComplexType>()->getElementType()
3554                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3555     case APValue::LValue:
3556       return foundPointer(Subobj, SubobjType);
3557     default:
3558       // FIXME: can this happen?
3559       Info.FFDiag(E);
3560       return false;
3561     }
3562   }
3563   bool found(APSInt &Value, QualType SubobjType) {
3564     if (!checkConst(SubobjType))
3565       return false;
3566 
3567     if (!SubobjType->isIntegerType()) {
3568       // We don't support increment / decrement on integer-cast-to-pointer
3569       // values.
3570       Info.FFDiag(E);
3571       return false;
3572     }
3573 
3574     if (Old) *Old = APValue(Value);
3575 
3576     // bool arithmetic promotes to int, and the conversion back to bool
3577     // doesn't reduce mod 2^n, so special-case it.
3578     if (SubobjType->isBooleanType()) {
3579       if (AccessKind == AK_Increment)
3580         Value = 1;
3581       else
3582         Value = !Value;
3583       return true;
3584     }
3585 
3586     bool WasNegative = Value.isNegative();
3587     if (AccessKind == AK_Increment) {
3588       ++Value;
3589 
3590       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3591         APSInt ActualValue(Value, /*IsUnsigned*/true);
3592         return HandleOverflow(Info, E, ActualValue, SubobjType);
3593       }
3594     } else {
3595       --Value;
3596 
3597       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3598         unsigned BitWidth = Value.getBitWidth();
3599         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3600         ActualValue.setBit(BitWidth);
3601         return HandleOverflow(Info, E, ActualValue, SubobjType);
3602       }
3603     }
3604     return true;
3605   }
3606   bool found(APFloat &Value, QualType SubobjType) {
3607     if (!checkConst(SubobjType))
3608       return false;
3609 
3610     if (Old) *Old = APValue(Value);
3611 
3612     APFloat One(Value.getSemantics(), 1);
3613     if (AccessKind == AK_Increment)
3614       Value.add(One, APFloat::rmNearestTiesToEven);
3615     else
3616       Value.subtract(One, APFloat::rmNearestTiesToEven);
3617     return true;
3618   }
3619   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3620     if (!checkConst(SubobjType))
3621       return false;
3622 
3623     QualType PointeeType;
3624     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3625       PointeeType = PT->getPointeeType();
3626     else {
3627       Info.FFDiag(E);
3628       return false;
3629     }
3630 
3631     LValue LVal;
3632     LVal.setFrom(Info.Ctx, Subobj);
3633     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3634                                      AccessKind == AK_Increment ? 1 : -1))
3635       return false;
3636     LVal.moveInto(Subobj);
3637     return true;
3638   }
3639   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3640     llvm_unreachable("shouldn't encounter string elements here");
3641   }
3642 };
3643 } // end anonymous namespace
3644 
3645 /// Perform an increment or decrement on LVal.
3646 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3647                          QualType LValType, bool IsIncrement, APValue *Old) {
3648   if (LVal.Designator.Invalid)
3649     return false;
3650 
3651   if (!Info.getLangOpts().CPlusPlus14) {
3652     Info.FFDiag(E);
3653     return false;
3654   }
3655 
3656   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3657   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3658   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3659   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3660 }
3661 
3662 /// Build an lvalue for the object argument of a member function call.
3663 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3664                                    LValue &This) {
3665   if (Object->getType()->isPointerType())
3666     return EvaluatePointer(Object, This, Info);
3667 
3668   if (Object->isGLValue())
3669     return EvaluateLValue(Object, This, Info);
3670 
3671   if (Object->getType()->isLiteralType(Info.Ctx))
3672     return EvaluateTemporary(Object, This, Info);
3673 
3674   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3675   return false;
3676 }
3677 
3678 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3679 /// lvalue referring to the result.
3680 ///
3681 /// \param Info - Information about the ongoing evaluation.
3682 /// \param LV - An lvalue referring to the base of the member pointer.
3683 /// \param RHS - The member pointer expression.
3684 /// \param IncludeMember - Specifies whether the member itself is included in
3685 ///        the resulting LValue subobject designator. This is not possible when
3686 ///        creating a bound member function.
3687 /// \return The field or method declaration to which the member pointer refers,
3688 ///         or 0 if evaluation fails.
3689 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3690                                                   QualType LVType,
3691                                                   LValue &LV,
3692                                                   const Expr *RHS,
3693                                                   bool IncludeMember = true) {
3694   MemberPtr MemPtr;
3695   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3696     return nullptr;
3697 
3698   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3699   // member value, the behavior is undefined.
3700   if (!MemPtr.getDecl()) {
3701     // FIXME: Specific diagnostic.
3702     Info.FFDiag(RHS);
3703     return nullptr;
3704   }
3705 
3706   if (MemPtr.isDerivedMember()) {
3707     // This is a member of some derived class. Truncate LV appropriately.
3708     // The end of the derived-to-base path for the base object must match the
3709     // derived-to-base path for the member pointer.
3710     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3711         LV.Designator.Entries.size()) {
3712       Info.FFDiag(RHS);
3713       return nullptr;
3714     }
3715     unsigned PathLengthToMember =
3716         LV.Designator.Entries.size() - MemPtr.Path.size();
3717     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3718       const CXXRecordDecl *LVDecl = getAsBaseClass(
3719           LV.Designator.Entries[PathLengthToMember + I]);
3720       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3721       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3722         Info.FFDiag(RHS);
3723         return nullptr;
3724       }
3725     }
3726 
3727     // Truncate the lvalue to the appropriate derived class.
3728     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3729                             PathLengthToMember))
3730       return nullptr;
3731   } else if (!MemPtr.Path.empty()) {
3732     // Extend the LValue path with the member pointer's path.
3733     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3734                                   MemPtr.Path.size() + IncludeMember);
3735 
3736     // Walk down to the appropriate base class.
3737     if (const PointerType *PT = LVType->getAs<PointerType>())
3738       LVType = PT->getPointeeType();
3739     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3740     assert(RD && "member pointer access on non-class-type expression");
3741     // The first class in the path is that of the lvalue.
3742     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3743       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3744       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3745         return nullptr;
3746       RD = Base;
3747     }
3748     // Finally cast to the class containing the member.
3749     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3750                                 MemPtr.getContainingRecord()))
3751       return nullptr;
3752   }
3753 
3754   // Add the member. Note that we cannot build bound member functions here.
3755   if (IncludeMember) {
3756     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3757       if (!HandleLValueMember(Info, RHS, LV, FD))
3758         return nullptr;
3759     } else if (const IndirectFieldDecl *IFD =
3760                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3761       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3762         return nullptr;
3763     } else {
3764       llvm_unreachable("can't construct reference to bound member function");
3765     }
3766   }
3767 
3768   return MemPtr.getDecl();
3769 }
3770 
3771 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3772                                                   const BinaryOperator *BO,
3773                                                   LValue &LV,
3774                                                   bool IncludeMember = true) {
3775   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3776 
3777   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3778     if (Info.noteFailure()) {
3779       MemberPtr MemPtr;
3780       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3781     }
3782     return nullptr;
3783   }
3784 
3785   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3786                                    BO->getRHS(), IncludeMember);
3787 }
3788 
3789 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3790 /// the provided lvalue, which currently refers to the base object.
3791 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3792                                     LValue &Result) {
3793   SubobjectDesignator &D = Result.Designator;
3794   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3795     return false;
3796 
3797   QualType TargetQT = E->getType();
3798   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3799     TargetQT = PT->getPointeeType();
3800 
3801   // Check this cast lands within the final derived-to-base subobject path.
3802   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3803     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3804       << D.MostDerivedType << TargetQT;
3805     return false;
3806   }
3807 
3808   // Check the type of the final cast. We don't need to check the path,
3809   // since a cast can only be formed if the path is unique.
3810   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3811   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3812   const CXXRecordDecl *FinalType;
3813   if (NewEntriesSize == D.MostDerivedPathLength)
3814     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3815   else
3816     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3817   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3818     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3819       << D.MostDerivedType << TargetQT;
3820     return false;
3821   }
3822 
3823   // Truncate the lvalue to the appropriate derived class.
3824   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3825 }
3826 
3827 namespace {
3828 enum EvalStmtResult {
3829   /// Evaluation failed.
3830   ESR_Failed,
3831   /// Hit a 'return' statement.
3832   ESR_Returned,
3833   /// Evaluation succeeded.
3834   ESR_Succeeded,
3835   /// Hit a 'continue' statement.
3836   ESR_Continue,
3837   /// Hit a 'break' statement.
3838   ESR_Break,
3839   /// Still scanning for 'case' or 'default' statement.
3840   ESR_CaseNotFound
3841 };
3842 }
3843 
3844 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3845   // We don't need to evaluate the initializer for a static local.
3846   if (!VD->hasLocalStorage())
3847     return true;
3848 
3849   LValue Result;
3850   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3851 
3852   const Expr *InitE = VD->getInit();
3853   if (!InitE) {
3854     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3855         << false << VD->getType();
3856     Val = APValue();
3857     return false;
3858   }
3859 
3860   if (InitE->isValueDependent())
3861     return false;
3862 
3863   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3864     // Wipe out any partially-computed value, to allow tracking that this
3865     // evaluation failed.
3866     Val = APValue();
3867     return false;
3868   }
3869 
3870   return true;
3871 }
3872 
3873 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3874   bool OK = true;
3875 
3876   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3877     OK &= EvaluateVarDecl(Info, VD);
3878 
3879   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3880     for (auto *BD : DD->bindings())
3881       if (auto *VD = BD->getHoldingVar())
3882         OK &= EvaluateDecl(Info, VD);
3883 
3884   return OK;
3885 }
3886 
3887 
3888 /// Evaluate a condition (either a variable declaration or an expression).
3889 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3890                          const Expr *Cond, bool &Result) {
3891   FullExpressionRAII Scope(Info);
3892   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3893     return false;
3894   return EvaluateAsBooleanCondition(Cond, Result, Info);
3895 }
3896 
3897 namespace {
3898 /// A location where the result (returned value) of evaluating a
3899 /// statement should be stored.
3900 struct StmtResult {
3901   /// The APValue that should be filled in with the returned value.
3902   APValue &Value;
3903   /// The location containing the result, if any (used to support RVO).
3904   const LValue *Slot;
3905 };
3906 
3907 struct TempVersionRAII {
3908   CallStackFrame &Frame;
3909 
3910   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3911     Frame.pushTempVersion();
3912   }
3913 
3914   ~TempVersionRAII() {
3915     Frame.popTempVersion();
3916   }
3917 };
3918 
3919 }
3920 
3921 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3922                                    const Stmt *S,
3923                                    const SwitchCase *SC = nullptr);
3924 
3925 /// Evaluate the body of a loop, and translate the result as appropriate.
3926 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3927                                        const Stmt *Body,
3928                                        const SwitchCase *Case = nullptr) {
3929   BlockScopeRAII Scope(Info);
3930   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3931   case ESR_Break:
3932     return ESR_Succeeded;
3933   case ESR_Succeeded:
3934   case ESR_Continue:
3935     return ESR_Continue;
3936   case ESR_Failed:
3937   case ESR_Returned:
3938   case ESR_CaseNotFound:
3939     return ESR;
3940   }
3941   llvm_unreachable("Invalid EvalStmtResult!");
3942 }
3943 
3944 /// Evaluate a switch statement.
3945 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3946                                      const SwitchStmt *SS) {
3947   BlockScopeRAII Scope(Info);
3948 
3949   // Evaluate the switch condition.
3950   APSInt Value;
3951   {
3952     FullExpressionRAII Scope(Info);
3953     if (const Stmt *Init = SS->getInit()) {
3954       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3955       if (ESR != ESR_Succeeded)
3956         return ESR;
3957     }
3958     if (SS->getConditionVariable() &&
3959         !EvaluateDecl(Info, SS->getConditionVariable()))
3960       return ESR_Failed;
3961     if (!EvaluateInteger(SS->getCond(), Value, Info))
3962       return ESR_Failed;
3963   }
3964 
3965   // Find the switch case corresponding to the value of the condition.
3966   // FIXME: Cache this lookup.
3967   const SwitchCase *Found = nullptr;
3968   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3969        SC = SC->getNextSwitchCase()) {
3970     if (isa<DefaultStmt>(SC)) {
3971       Found = SC;
3972       continue;
3973     }
3974 
3975     const CaseStmt *CS = cast<CaseStmt>(SC);
3976     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3977     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3978                               : LHS;
3979     if (LHS <= Value && Value <= RHS) {
3980       Found = SC;
3981       break;
3982     }
3983   }
3984 
3985   if (!Found)
3986     return ESR_Succeeded;
3987 
3988   // Search the switch body for the switch case and evaluate it from there.
3989   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3990   case ESR_Break:
3991     return ESR_Succeeded;
3992   case ESR_Succeeded:
3993   case ESR_Continue:
3994   case ESR_Failed:
3995   case ESR_Returned:
3996     return ESR;
3997   case ESR_CaseNotFound:
3998     // This can only happen if the switch case is nested within a statement
3999     // expression. We have no intention of supporting that.
4000     Info.FFDiag(Found->getBeginLoc(),
4001                 diag::note_constexpr_stmt_expr_unsupported);
4002     return ESR_Failed;
4003   }
4004   llvm_unreachable("Invalid EvalStmtResult!");
4005 }
4006 
4007 // Evaluate a statement.
4008 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4009                                    const Stmt *S, const SwitchCase *Case) {
4010   if (!Info.nextStep(S))
4011     return ESR_Failed;
4012 
4013   // If we're hunting down a 'case' or 'default' label, recurse through
4014   // substatements until we hit the label.
4015   if (Case) {
4016     // FIXME: We don't start the lifetime of objects whose initialization we
4017     // jump over. However, such objects must be of class type with a trivial
4018     // default constructor that initialize all subobjects, so must be empty,
4019     // so this almost never matters.
4020     switch (S->getStmtClass()) {
4021     case Stmt::CompoundStmtClass:
4022       // FIXME: Precompute which substatement of a compound statement we
4023       // would jump to, and go straight there rather than performing a
4024       // linear scan each time.
4025     case Stmt::LabelStmtClass:
4026     case Stmt::AttributedStmtClass:
4027     case Stmt::DoStmtClass:
4028       break;
4029 
4030     case Stmt::CaseStmtClass:
4031     case Stmt::DefaultStmtClass:
4032       if (Case == S)
4033         Case = nullptr;
4034       break;
4035 
4036     case Stmt::IfStmtClass: {
4037       // FIXME: Precompute which side of an 'if' we would jump to, and go
4038       // straight there rather than scanning both sides.
4039       const IfStmt *IS = cast<IfStmt>(S);
4040 
4041       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4042       // preceded by our switch label.
4043       BlockScopeRAII Scope(Info);
4044 
4045       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4046       if (ESR != ESR_CaseNotFound || !IS->getElse())
4047         return ESR;
4048       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4049     }
4050 
4051     case Stmt::WhileStmtClass: {
4052       EvalStmtResult ESR =
4053           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4054       if (ESR != ESR_Continue)
4055         return ESR;
4056       break;
4057     }
4058 
4059     case Stmt::ForStmtClass: {
4060       const ForStmt *FS = cast<ForStmt>(S);
4061       EvalStmtResult ESR =
4062           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4063       if (ESR != ESR_Continue)
4064         return ESR;
4065       if (FS->getInc()) {
4066         FullExpressionRAII IncScope(Info);
4067         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4068           return ESR_Failed;
4069       }
4070       break;
4071     }
4072 
4073     case Stmt::DeclStmtClass:
4074       // FIXME: If the variable has initialization that can't be jumped over,
4075       // bail out of any immediately-surrounding compound-statement too.
4076     default:
4077       return ESR_CaseNotFound;
4078     }
4079   }
4080 
4081   switch (S->getStmtClass()) {
4082   default:
4083     if (const Expr *E = dyn_cast<Expr>(S)) {
4084       // Don't bother evaluating beyond an expression-statement which couldn't
4085       // be evaluated.
4086       FullExpressionRAII Scope(Info);
4087       if (!EvaluateIgnoredValue(Info, E))
4088         return ESR_Failed;
4089       return ESR_Succeeded;
4090     }
4091 
4092     Info.FFDiag(S->getBeginLoc());
4093     return ESR_Failed;
4094 
4095   case Stmt::NullStmtClass:
4096     return ESR_Succeeded;
4097 
4098   case Stmt::DeclStmtClass: {
4099     const DeclStmt *DS = cast<DeclStmt>(S);
4100     for (const auto *DclIt : DS->decls()) {
4101       // Each declaration initialization is its own full-expression.
4102       // FIXME: This isn't quite right; if we're performing aggregate
4103       // initialization, each braced subexpression is its own full-expression.
4104       FullExpressionRAII Scope(Info);
4105       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4106         return ESR_Failed;
4107     }
4108     return ESR_Succeeded;
4109   }
4110 
4111   case Stmt::ReturnStmtClass: {
4112     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4113     FullExpressionRAII Scope(Info);
4114     if (RetExpr &&
4115         !(Result.Slot
4116               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4117               : Evaluate(Result.Value, Info, RetExpr)))
4118       return ESR_Failed;
4119     return ESR_Returned;
4120   }
4121 
4122   case Stmt::CompoundStmtClass: {
4123     BlockScopeRAII Scope(Info);
4124 
4125     const CompoundStmt *CS = cast<CompoundStmt>(S);
4126     for (const auto *BI : CS->body()) {
4127       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4128       if (ESR == ESR_Succeeded)
4129         Case = nullptr;
4130       else if (ESR != ESR_CaseNotFound)
4131         return ESR;
4132     }
4133     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4134   }
4135 
4136   case Stmt::IfStmtClass: {
4137     const IfStmt *IS = cast<IfStmt>(S);
4138 
4139     // Evaluate the condition, as either a var decl or as an expression.
4140     BlockScopeRAII Scope(Info);
4141     if (const Stmt *Init = IS->getInit()) {
4142       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4143       if (ESR != ESR_Succeeded)
4144         return ESR;
4145     }
4146     bool Cond;
4147     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4148       return ESR_Failed;
4149 
4150     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4151       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4152       if (ESR != ESR_Succeeded)
4153         return ESR;
4154     }
4155     return ESR_Succeeded;
4156   }
4157 
4158   case Stmt::WhileStmtClass: {
4159     const WhileStmt *WS = cast<WhileStmt>(S);
4160     while (true) {
4161       BlockScopeRAII Scope(Info);
4162       bool Continue;
4163       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4164                         Continue))
4165         return ESR_Failed;
4166       if (!Continue)
4167         break;
4168 
4169       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4170       if (ESR != ESR_Continue)
4171         return ESR;
4172     }
4173     return ESR_Succeeded;
4174   }
4175 
4176   case Stmt::DoStmtClass: {
4177     const DoStmt *DS = cast<DoStmt>(S);
4178     bool Continue;
4179     do {
4180       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4181       if (ESR != ESR_Continue)
4182         return ESR;
4183       Case = nullptr;
4184 
4185       FullExpressionRAII CondScope(Info);
4186       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4187         return ESR_Failed;
4188     } while (Continue);
4189     return ESR_Succeeded;
4190   }
4191 
4192   case Stmt::ForStmtClass: {
4193     const ForStmt *FS = cast<ForStmt>(S);
4194     BlockScopeRAII Scope(Info);
4195     if (FS->getInit()) {
4196       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4197       if (ESR != ESR_Succeeded)
4198         return ESR;
4199     }
4200     while (true) {
4201       BlockScopeRAII Scope(Info);
4202       bool Continue = true;
4203       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4204                                          FS->getCond(), Continue))
4205         return ESR_Failed;
4206       if (!Continue)
4207         break;
4208 
4209       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4210       if (ESR != ESR_Continue)
4211         return ESR;
4212 
4213       if (FS->getInc()) {
4214         FullExpressionRAII IncScope(Info);
4215         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4216           return ESR_Failed;
4217       }
4218     }
4219     return ESR_Succeeded;
4220   }
4221 
4222   case Stmt::CXXForRangeStmtClass: {
4223     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4224     BlockScopeRAII Scope(Info);
4225 
4226     // Evaluate the init-statement if present.
4227     if (FS->getInit()) {
4228       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4229       if (ESR != ESR_Succeeded)
4230         return ESR;
4231     }
4232 
4233     // Initialize the __range variable.
4234     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4235     if (ESR != ESR_Succeeded)
4236       return ESR;
4237 
4238     // Create the __begin and __end iterators.
4239     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4240     if (ESR != ESR_Succeeded)
4241       return ESR;
4242     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4243     if (ESR != ESR_Succeeded)
4244       return ESR;
4245 
4246     while (true) {
4247       // Condition: __begin != __end.
4248       {
4249         bool Continue = true;
4250         FullExpressionRAII CondExpr(Info);
4251         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4252           return ESR_Failed;
4253         if (!Continue)
4254           break;
4255       }
4256 
4257       // User's variable declaration, initialized by *__begin.
4258       BlockScopeRAII InnerScope(Info);
4259       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4260       if (ESR != ESR_Succeeded)
4261         return ESR;
4262 
4263       // Loop body.
4264       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4265       if (ESR != ESR_Continue)
4266         return ESR;
4267 
4268       // Increment: ++__begin
4269       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4270         return ESR_Failed;
4271     }
4272 
4273     return ESR_Succeeded;
4274   }
4275 
4276   case Stmt::SwitchStmtClass:
4277     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4278 
4279   case Stmt::ContinueStmtClass:
4280     return ESR_Continue;
4281 
4282   case Stmt::BreakStmtClass:
4283     return ESR_Break;
4284 
4285   case Stmt::LabelStmtClass:
4286     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4287 
4288   case Stmt::AttributedStmtClass:
4289     // As a general principle, C++11 attributes can be ignored without
4290     // any semantic impact.
4291     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4292                         Case);
4293 
4294   case Stmt::CaseStmtClass:
4295   case Stmt::DefaultStmtClass:
4296     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4297   case Stmt::CXXTryStmtClass:
4298     // Evaluate try blocks by evaluating all sub statements.
4299     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4300   }
4301 }
4302 
4303 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4304 /// default constructor. If so, we'll fold it whether or not it's marked as
4305 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4306 /// so we need special handling.
4307 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4308                                            const CXXConstructorDecl *CD,
4309                                            bool IsValueInitialization) {
4310   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4311     return false;
4312 
4313   // Value-initialization does not call a trivial default constructor, so such a
4314   // call is a core constant expression whether or not the constructor is
4315   // constexpr.
4316   if (!CD->isConstexpr() && !IsValueInitialization) {
4317     if (Info.getLangOpts().CPlusPlus11) {
4318       // FIXME: If DiagDecl is an implicitly-declared special member function,
4319       // we should be much more explicit about why it's not constexpr.
4320       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4321         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4322       Info.Note(CD->getLocation(), diag::note_declared_at);
4323     } else {
4324       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4325     }
4326   }
4327   return true;
4328 }
4329 
4330 /// CheckConstexprFunction - Check that a function can be called in a constant
4331 /// expression.
4332 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4333                                    const FunctionDecl *Declaration,
4334                                    const FunctionDecl *Definition,
4335                                    const Stmt *Body) {
4336   // Potential constant expressions can contain calls to declared, but not yet
4337   // defined, constexpr functions.
4338   if (Info.checkingPotentialConstantExpression() && !Definition &&
4339       Declaration->isConstexpr())
4340     return false;
4341 
4342   // Bail out if the function declaration itself is invalid.  We will
4343   // have produced a relevant diagnostic while parsing it, so just
4344   // note the problematic sub-expression.
4345   if (Declaration->isInvalidDecl()) {
4346     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4347     return false;
4348   }
4349 
4350   // Can we evaluate this function call?
4351   if (Definition && Definition->isConstexpr() &&
4352       !Definition->isInvalidDecl() && Body)
4353     return true;
4354 
4355   if (Info.getLangOpts().CPlusPlus11) {
4356     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4357 
4358     // If this function is not constexpr because it is an inherited
4359     // non-constexpr constructor, diagnose that directly.
4360     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4361     if (CD && CD->isInheritingConstructor()) {
4362       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4363       if (!Inherited->isConstexpr())
4364         DiagDecl = CD = Inherited;
4365     }
4366 
4367     // FIXME: If DiagDecl is an implicitly-declared special member function
4368     // or an inheriting constructor, we should be much more explicit about why
4369     // it's not constexpr.
4370     if (CD && CD->isInheritingConstructor())
4371       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4372         << CD->getInheritedConstructor().getConstructor()->getParent();
4373     else
4374       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4375         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4376     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4377   } else {
4378     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4379   }
4380   return false;
4381 }
4382 
4383 /// Determine if a class has any fields that might need to be copied by a
4384 /// trivial copy or move operation.
4385 static bool hasFields(const CXXRecordDecl *RD) {
4386   if (!RD || RD->isEmpty())
4387     return false;
4388   for (auto *FD : RD->fields()) {
4389     if (FD->isUnnamedBitfield())
4390       continue;
4391     return true;
4392   }
4393   for (auto &Base : RD->bases())
4394     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4395       return true;
4396   return false;
4397 }
4398 
4399 namespace {
4400 typedef SmallVector<APValue, 8> ArgVector;
4401 }
4402 
4403 /// EvaluateArgs - Evaluate the arguments to a function call.
4404 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4405                          EvalInfo &Info) {
4406   bool Success = true;
4407   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4408        I != E; ++I) {
4409     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4410       // If we're checking for a potential constant expression, evaluate all
4411       // initializers even if some of them fail.
4412       if (!Info.noteFailure())
4413         return false;
4414       Success = false;
4415     }
4416   }
4417   return Success;
4418 }
4419 
4420 /// Evaluate a function call.
4421 static bool HandleFunctionCall(SourceLocation CallLoc,
4422                                const FunctionDecl *Callee, const LValue *This,
4423                                ArrayRef<const Expr*> Args, const Stmt *Body,
4424                                EvalInfo &Info, APValue &Result,
4425                                const LValue *ResultSlot) {
4426   ArgVector ArgValues(Args.size());
4427   if (!EvaluateArgs(Args, ArgValues, Info))
4428     return false;
4429 
4430   if (!Info.CheckCallLimit(CallLoc))
4431     return false;
4432 
4433   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4434 
4435   // For a trivial copy or move assignment, perform an APValue copy. This is
4436   // essential for unions, where the operations performed by the assignment
4437   // operator cannot be represented as statements.
4438   //
4439   // Skip this for non-union classes with no fields; in that case, the defaulted
4440   // copy/move does not actually read the object.
4441   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4442   if (MD && MD->isDefaulted() &&
4443       (MD->getParent()->isUnion() ||
4444        (MD->isTrivial() && hasFields(MD->getParent())))) {
4445     assert(This &&
4446            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4447     LValue RHS;
4448     RHS.setFrom(Info.Ctx, ArgValues[0]);
4449     APValue RHSValue;
4450     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4451                                         RHS, RHSValue))
4452       return false;
4453     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4454                           RHSValue))
4455       return false;
4456     This->moveInto(Result);
4457     return true;
4458   } else if (MD && isLambdaCallOperator(MD)) {
4459     // We're in a lambda; determine the lambda capture field maps unless we're
4460     // just constexpr checking a lambda's call operator. constexpr checking is
4461     // done before the captures have been added to the closure object (unless
4462     // we're inferring constexpr-ness), so we don't have access to them in this
4463     // case. But since we don't need the captures to constexpr check, we can
4464     // just ignore them.
4465     if (!Info.checkingPotentialConstantExpression())
4466       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4467                                         Frame.LambdaThisCaptureField);
4468   }
4469 
4470   StmtResult Ret = {Result, ResultSlot};
4471   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4472   if (ESR == ESR_Succeeded) {
4473     if (Callee->getReturnType()->isVoidType())
4474       return true;
4475     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4476   }
4477   return ESR == ESR_Returned;
4478 }
4479 
4480 /// Evaluate a constructor call.
4481 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4482                                   APValue *ArgValues,
4483                                   const CXXConstructorDecl *Definition,
4484                                   EvalInfo &Info, APValue &Result) {
4485   SourceLocation CallLoc = E->getExprLoc();
4486   if (!Info.CheckCallLimit(CallLoc))
4487     return false;
4488 
4489   const CXXRecordDecl *RD = Definition->getParent();
4490   if (RD->getNumVBases()) {
4491     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4492     return false;
4493   }
4494 
4495   EvalInfo::EvaluatingConstructorRAII EvalObj(
4496       Info, {This.getLValueBase(),
4497              {This.getLValueCallIndex(), This.getLValueVersion()}});
4498   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4499 
4500   // FIXME: Creating an APValue just to hold a nonexistent return value is
4501   // wasteful.
4502   APValue RetVal;
4503   StmtResult Ret = {RetVal, nullptr};
4504 
4505   // If it's a delegating constructor, delegate.
4506   if (Definition->isDelegatingConstructor()) {
4507     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4508     {
4509       FullExpressionRAII InitScope(Info);
4510       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4511         return false;
4512     }
4513     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4514   }
4515 
4516   // For a trivial copy or move constructor, perform an APValue copy. This is
4517   // essential for unions (or classes with anonymous union members), where the
4518   // operations performed by the constructor cannot be represented by
4519   // ctor-initializers.
4520   //
4521   // Skip this for empty non-union classes; we should not perform an
4522   // lvalue-to-rvalue conversion on them because their copy constructor does not
4523   // actually read them.
4524   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4525       (Definition->getParent()->isUnion() ||
4526        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4527     LValue RHS;
4528     RHS.setFrom(Info.Ctx, ArgValues[0]);
4529     return handleLValueToRValueConversion(
4530         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4531         RHS, Result);
4532   }
4533 
4534   // Reserve space for the struct members.
4535   if (!RD->isUnion() && Result.isUninit())
4536     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4537                      std::distance(RD->field_begin(), RD->field_end()));
4538 
4539   if (RD->isInvalidDecl()) return false;
4540   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4541 
4542   // A scope for temporaries lifetime-extended by reference members.
4543   BlockScopeRAII LifetimeExtendedScope(Info);
4544 
4545   bool Success = true;
4546   unsigned BasesSeen = 0;
4547 #ifndef NDEBUG
4548   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4549 #endif
4550   for (const auto *I : Definition->inits()) {
4551     LValue Subobject = This;
4552     LValue SubobjectParent = This;
4553     APValue *Value = &Result;
4554 
4555     // Determine the subobject to initialize.
4556     FieldDecl *FD = nullptr;
4557     if (I->isBaseInitializer()) {
4558       QualType BaseType(I->getBaseClass(), 0);
4559 #ifndef NDEBUG
4560       // Non-virtual base classes are initialized in the order in the class
4561       // definition. We have already checked for virtual base classes.
4562       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4563       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4564              "base class initializers not in expected order");
4565       ++BaseIt;
4566 #endif
4567       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4568                                   BaseType->getAsCXXRecordDecl(), &Layout))
4569         return false;
4570       Value = &Result.getStructBase(BasesSeen++);
4571     } else if ((FD = I->getMember())) {
4572       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4573         return false;
4574       if (RD->isUnion()) {
4575         Result = APValue(FD);
4576         Value = &Result.getUnionValue();
4577       } else {
4578         Value = &Result.getStructField(FD->getFieldIndex());
4579       }
4580     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4581       // Walk the indirect field decl's chain to find the object to initialize,
4582       // and make sure we've initialized every step along it.
4583       auto IndirectFieldChain = IFD->chain();
4584       for (auto *C : IndirectFieldChain) {
4585         FD = cast<FieldDecl>(C);
4586         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4587         // Switch the union field if it differs. This happens if we had
4588         // preceding zero-initialization, and we're now initializing a union
4589         // subobject other than the first.
4590         // FIXME: In this case, the values of the other subobjects are
4591         // specified, since zero-initialization sets all padding bits to zero.
4592         if (Value->isUninit() ||
4593             (Value->isUnion() && Value->getUnionField() != FD)) {
4594           if (CD->isUnion())
4595             *Value = APValue(FD);
4596           else
4597             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4598                              std::distance(CD->field_begin(), CD->field_end()));
4599         }
4600         // Store Subobject as its parent before updating it for the last element
4601         // in the chain.
4602         if (C == IndirectFieldChain.back())
4603           SubobjectParent = Subobject;
4604         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4605           return false;
4606         if (CD->isUnion())
4607           Value = &Value->getUnionValue();
4608         else
4609           Value = &Value->getStructField(FD->getFieldIndex());
4610       }
4611     } else {
4612       llvm_unreachable("unknown base initializer kind");
4613     }
4614 
4615     // Need to override This for implicit field initializers as in this case
4616     // This refers to innermost anonymous struct/union containing initializer,
4617     // not to currently constructed class.
4618     const Expr *Init = I->getInit();
4619     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4620                                   isa<CXXDefaultInitExpr>(Init));
4621     FullExpressionRAII InitScope(Info);
4622     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4623         (FD && FD->isBitField() &&
4624          !truncateBitfieldValue(Info, Init, *Value, FD))) {
4625       // If we're checking for a potential constant expression, evaluate all
4626       // initializers even if some of them fail.
4627       if (!Info.noteFailure())
4628         return false;
4629       Success = false;
4630     }
4631   }
4632 
4633   return Success &&
4634          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4635 }
4636 
4637 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4638                                   ArrayRef<const Expr*> Args,
4639                                   const CXXConstructorDecl *Definition,
4640                                   EvalInfo &Info, APValue &Result) {
4641   ArgVector ArgValues(Args.size());
4642   if (!EvaluateArgs(Args, ArgValues, Info))
4643     return false;
4644 
4645   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4646                                Info, Result);
4647 }
4648 
4649 //===----------------------------------------------------------------------===//
4650 // Generic Evaluation
4651 //===----------------------------------------------------------------------===//
4652 namespace {
4653 
4654 template <class Derived>
4655 class ExprEvaluatorBase
4656   : public ConstStmtVisitor<Derived, bool> {
4657 private:
4658   Derived &getDerived() { return static_cast<Derived&>(*this); }
4659   bool DerivedSuccess(const APValue &V, const Expr *E) {
4660     return getDerived().Success(V, E);
4661   }
4662   bool DerivedZeroInitialization(const Expr *E) {
4663     return getDerived().ZeroInitialization(E);
4664   }
4665 
4666   // Check whether a conditional operator with a non-constant condition is a
4667   // potential constant expression. If neither arm is a potential constant
4668   // expression, then the conditional operator is not either.
4669   template<typename ConditionalOperator>
4670   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4671     assert(Info.checkingPotentialConstantExpression());
4672 
4673     // Speculatively evaluate both arms.
4674     SmallVector<PartialDiagnosticAt, 8> Diag;
4675     {
4676       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4677       StmtVisitorTy::Visit(E->getFalseExpr());
4678       if (Diag.empty())
4679         return;
4680     }
4681 
4682     {
4683       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4684       Diag.clear();
4685       StmtVisitorTy::Visit(E->getTrueExpr());
4686       if (Diag.empty())
4687         return;
4688     }
4689 
4690     Error(E, diag::note_constexpr_conditional_never_const);
4691   }
4692 
4693 
4694   template<typename ConditionalOperator>
4695   bool HandleConditionalOperator(const ConditionalOperator *E) {
4696     bool BoolResult;
4697     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4698       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4699         CheckPotentialConstantConditional(E);
4700         return false;
4701       }
4702       if (Info.noteFailure()) {
4703         StmtVisitorTy::Visit(E->getTrueExpr());
4704         StmtVisitorTy::Visit(E->getFalseExpr());
4705       }
4706       return false;
4707     }
4708 
4709     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4710     return StmtVisitorTy::Visit(EvalExpr);
4711   }
4712 
4713 protected:
4714   EvalInfo &Info;
4715   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4716   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4717 
4718   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4719     return Info.CCEDiag(E, D);
4720   }
4721 
4722   bool ZeroInitialization(const Expr *E) { return Error(E); }
4723 
4724 public:
4725   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4726 
4727   EvalInfo &getEvalInfo() { return Info; }
4728 
4729   /// Report an evaluation error. This should only be called when an error is
4730   /// first discovered. When propagating an error, just return false.
4731   bool Error(const Expr *E, diag::kind D) {
4732     Info.FFDiag(E, D);
4733     return false;
4734   }
4735   bool Error(const Expr *E) {
4736     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4737   }
4738 
4739   bool VisitStmt(const Stmt *) {
4740     llvm_unreachable("Expression evaluator should not be called on stmts");
4741   }
4742   bool VisitExpr(const Expr *E) {
4743     return Error(E);
4744   }
4745 
4746   bool VisitConstantExpr(const ConstantExpr *E)
4747     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4748   bool VisitParenExpr(const ParenExpr *E)
4749     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4750   bool VisitUnaryExtension(const UnaryOperator *E)
4751     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4752   bool VisitUnaryPlus(const UnaryOperator *E)
4753     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4754   bool VisitChooseExpr(const ChooseExpr *E)
4755     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4756   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4757     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4758   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4759     { return StmtVisitorTy::Visit(E->getReplacement()); }
4760   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4761     TempVersionRAII RAII(*Info.CurrentCall);
4762     return StmtVisitorTy::Visit(E->getExpr());
4763   }
4764   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4765     TempVersionRAII RAII(*Info.CurrentCall);
4766     // The initializer may not have been parsed yet, or might be erroneous.
4767     if (!E->getExpr())
4768       return Error(E);
4769     return StmtVisitorTy::Visit(E->getExpr());
4770   }
4771   // We cannot create any objects for which cleanups are required, so there is
4772   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4773   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4774     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4775 
4776   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4777     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4778     return static_cast<Derived*>(this)->VisitCastExpr(E);
4779   }
4780   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4781     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4782     return static_cast<Derived*>(this)->VisitCastExpr(E);
4783   }
4784 
4785   bool VisitBinaryOperator(const BinaryOperator *E) {
4786     switch (E->getOpcode()) {
4787     default:
4788       return Error(E);
4789 
4790     case BO_Comma:
4791       VisitIgnoredValue(E->getLHS());
4792       return StmtVisitorTy::Visit(E->getRHS());
4793 
4794     case BO_PtrMemD:
4795     case BO_PtrMemI: {
4796       LValue Obj;
4797       if (!HandleMemberPointerAccess(Info, E, Obj))
4798         return false;
4799       APValue Result;
4800       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4801         return false;
4802       return DerivedSuccess(Result, E);
4803     }
4804     }
4805   }
4806 
4807   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4808     // Evaluate and cache the common expression. We treat it as a temporary,
4809     // even though it's not quite the same thing.
4810     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4811                   Info, E->getCommon()))
4812       return false;
4813 
4814     return HandleConditionalOperator(E);
4815   }
4816 
4817   bool VisitConditionalOperator(const ConditionalOperator *E) {
4818     bool IsBcpCall = false;
4819     // If the condition (ignoring parens) is a __builtin_constant_p call,
4820     // the result is a constant expression if it can be folded without
4821     // side-effects. This is an important GNU extension. See GCC PR38377
4822     // for discussion.
4823     if (const CallExpr *CallCE =
4824           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4825       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4826         IsBcpCall = true;
4827 
4828     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4829     // constant expression; we can't check whether it's potentially foldable.
4830     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4831       return false;
4832 
4833     FoldConstant Fold(Info, IsBcpCall);
4834     if (!HandleConditionalOperator(E)) {
4835       Fold.keepDiagnostics();
4836       return false;
4837     }
4838 
4839     return true;
4840   }
4841 
4842   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4843     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4844       return DerivedSuccess(*Value, E);
4845 
4846     const Expr *Source = E->getSourceExpr();
4847     if (!Source)
4848       return Error(E);
4849     if (Source == E) { // sanity checking.
4850       assert(0 && "OpaqueValueExpr recursively refers to itself");
4851       return Error(E);
4852     }
4853     return StmtVisitorTy::Visit(Source);
4854   }
4855 
4856   bool VisitCallExpr(const CallExpr *E) {
4857     APValue Result;
4858     if (!handleCallExpr(E, Result, nullptr))
4859       return false;
4860     return DerivedSuccess(Result, E);
4861   }
4862 
4863   bool handleCallExpr(const CallExpr *E, APValue &Result,
4864                      const LValue *ResultSlot) {
4865     const Expr *Callee = E->getCallee()->IgnoreParens();
4866     QualType CalleeType = Callee->getType();
4867 
4868     const FunctionDecl *FD = nullptr;
4869     LValue *This = nullptr, ThisVal;
4870     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4871     bool HasQualifier = false;
4872 
4873     // Extract function decl and 'this' pointer from the callee.
4874     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4875       const ValueDecl *Member = nullptr;
4876       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4877         // Explicit bound member calls, such as x.f() or p->g();
4878         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4879           return false;
4880         Member = ME->getMemberDecl();
4881         This = &ThisVal;
4882         HasQualifier = ME->hasQualifier();
4883       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4884         // Indirect bound member calls ('.*' or '->*').
4885         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4886         if (!Member) return false;
4887         This = &ThisVal;
4888       } else
4889         return Error(Callee);
4890 
4891       FD = dyn_cast<FunctionDecl>(Member);
4892       if (!FD)
4893         return Error(Callee);
4894     } else if (CalleeType->isFunctionPointerType()) {
4895       LValue Call;
4896       if (!EvaluatePointer(Callee, Call, Info))
4897         return false;
4898 
4899       if (!Call.getLValueOffset().isZero())
4900         return Error(Callee);
4901       FD = dyn_cast_or_null<FunctionDecl>(
4902                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4903       if (!FD)
4904         return Error(Callee);
4905       // Don't call function pointers which have been cast to some other type.
4906       // Per DR (no number yet), the caller and callee can differ in noexcept.
4907       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4908         CalleeType->getPointeeType(), FD->getType())) {
4909         return Error(E);
4910       }
4911 
4912       // Overloaded operator calls to member functions are represented as normal
4913       // calls with '*this' as the first argument.
4914       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4915       if (MD && !MD->isStatic()) {
4916         // FIXME: When selecting an implicit conversion for an overloaded
4917         // operator delete, we sometimes try to evaluate calls to conversion
4918         // operators without a 'this' parameter!
4919         if (Args.empty())
4920           return Error(E);
4921 
4922         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4923           return false;
4924         This = &ThisVal;
4925         Args = Args.slice(1);
4926       } else if (MD && MD->isLambdaStaticInvoker()) {
4927         // Map the static invoker for the lambda back to the call operator.
4928         // Conveniently, we don't have to slice out the 'this' argument (as is
4929         // being done for the non-static case), since a static member function
4930         // doesn't have an implicit argument passed in.
4931         const CXXRecordDecl *ClosureClass = MD->getParent();
4932         assert(
4933             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4934             "Number of captures must be zero for conversion to function-ptr");
4935 
4936         const CXXMethodDecl *LambdaCallOp =
4937             ClosureClass->getLambdaCallOperator();
4938 
4939         // Set 'FD', the function that will be called below, to the call
4940         // operator.  If the closure object represents a generic lambda, find
4941         // the corresponding specialization of the call operator.
4942 
4943         if (ClosureClass->isGenericLambda()) {
4944           assert(MD->isFunctionTemplateSpecialization() &&
4945                  "A generic lambda's static-invoker function must be a "
4946                  "template specialization");
4947           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4948           FunctionTemplateDecl *CallOpTemplate =
4949               LambdaCallOp->getDescribedFunctionTemplate();
4950           void *InsertPos = nullptr;
4951           FunctionDecl *CorrespondingCallOpSpecialization =
4952               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4953           assert(CorrespondingCallOpSpecialization &&
4954                  "We must always have a function call operator specialization "
4955                  "that corresponds to our static invoker specialization");
4956           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4957         } else
4958           FD = LambdaCallOp;
4959       }
4960 
4961 
4962     } else
4963       return Error(E);
4964 
4965     if (This && !This->checkSubobject(Info, E, CSK_This))
4966       return false;
4967 
4968     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4969     // calls to such functions in constant expressions.
4970     if (This && !HasQualifier &&
4971         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4972       return Error(E, diag::note_constexpr_virtual_call);
4973 
4974     const FunctionDecl *Definition = nullptr;
4975     Stmt *Body = FD->getBody(Definition);
4976 
4977     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4978         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4979                             Result, ResultSlot))
4980       return false;
4981 
4982     return true;
4983   }
4984 
4985   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4986     return StmtVisitorTy::Visit(E->getInitializer());
4987   }
4988   bool VisitInitListExpr(const InitListExpr *E) {
4989     if (E->getNumInits() == 0)
4990       return DerivedZeroInitialization(E);
4991     if (E->getNumInits() == 1)
4992       return StmtVisitorTy::Visit(E->getInit(0));
4993     return Error(E);
4994   }
4995   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4996     return DerivedZeroInitialization(E);
4997   }
4998   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4999     return DerivedZeroInitialization(E);
5000   }
5001   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5002     return DerivedZeroInitialization(E);
5003   }
5004 
5005   /// A member expression where the object is a prvalue is itself a prvalue.
5006   bool VisitMemberExpr(const MemberExpr *E) {
5007     assert(!E->isArrow() && "missing call to bound member function?");
5008 
5009     APValue Val;
5010     if (!Evaluate(Val, Info, E->getBase()))
5011       return false;
5012 
5013     QualType BaseTy = E->getBase()->getType();
5014 
5015     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5016     if (!FD) return Error(E);
5017     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5018     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5019            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5020 
5021     CompleteObject Obj(&Val, BaseTy, true);
5022     SubobjectDesignator Designator(BaseTy);
5023     Designator.addDeclUnchecked(FD);
5024 
5025     APValue Result;
5026     return extractSubobject(Info, E, Obj, Designator, Result) &&
5027            DerivedSuccess(Result, E);
5028   }
5029 
5030   bool VisitCastExpr(const CastExpr *E) {
5031     switch (E->getCastKind()) {
5032     default:
5033       break;
5034 
5035     case CK_AtomicToNonAtomic: {
5036       APValue AtomicVal;
5037       // This does not need to be done in place even for class/array types:
5038       // atomic-to-non-atomic conversion implies copying the object
5039       // representation.
5040       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5041         return false;
5042       return DerivedSuccess(AtomicVal, E);
5043     }
5044 
5045     case CK_NoOp:
5046     case CK_UserDefinedConversion:
5047       return StmtVisitorTy::Visit(E->getSubExpr());
5048 
5049     case CK_LValueToRValue: {
5050       LValue LVal;
5051       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5052         return false;
5053       APValue RVal;
5054       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5055       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5056                                           LVal, RVal))
5057         return false;
5058       return DerivedSuccess(RVal, E);
5059     }
5060     }
5061 
5062     return Error(E);
5063   }
5064 
5065   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5066     return VisitUnaryPostIncDec(UO);
5067   }
5068   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5069     return VisitUnaryPostIncDec(UO);
5070   }
5071   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5072     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5073       return Error(UO);
5074 
5075     LValue LVal;
5076     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5077       return false;
5078     APValue RVal;
5079     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5080                       UO->isIncrementOp(), &RVal))
5081       return false;
5082     return DerivedSuccess(RVal, UO);
5083   }
5084 
5085   bool VisitStmtExpr(const StmtExpr *E) {
5086     // We will have checked the full-expressions inside the statement expression
5087     // when they were completed, and don't need to check them again now.
5088     if (Info.checkingForOverflow())
5089       return Error(E);
5090 
5091     BlockScopeRAII Scope(Info);
5092     const CompoundStmt *CS = E->getSubStmt();
5093     if (CS->body_empty())
5094       return true;
5095 
5096     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5097                                            BE = CS->body_end();
5098          /**/; ++BI) {
5099       if (BI + 1 == BE) {
5100         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5101         if (!FinalExpr) {
5102           Info.FFDiag((*BI)->getBeginLoc(),
5103                       diag::note_constexpr_stmt_expr_unsupported);
5104           return false;
5105         }
5106         return this->Visit(FinalExpr);
5107       }
5108 
5109       APValue ReturnValue;
5110       StmtResult Result = { ReturnValue, nullptr };
5111       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5112       if (ESR != ESR_Succeeded) {
5113         // FIXME: If the statement-expression terminated due to 'return',
5114         // 'break', or 'continue', it would be nice to propagate that to
5115         // the outer statement evaluation rather than bailing out.
5116         if (ESR != ESR_Failed)
5117           Info.FFDiag((*BI)->getBeginLoc(),
5118                       diag::note_constexpr_stmt_expr_unsupported);
5119         return false;
5120       }
5121     }
5122 
5123     llvm_unreachable("Return from function from the loop above.");
5124   }
5125 
5126   /// Visit a value which is evaluated, but whose value is ignored.
5127   void VisitIgnoredValue(const Expr *E) {
5128     EvaluateIgnoredValue(Info, E);
5129   }
5130 
5131   /// Potentially visit a MemberExpr's base expression.
5132   void VisitIgnoredBaseExpression(const Expr *E) {
5133     // While MSVC doesn't evaluate the base expression, it does diagnose the
5134     // presence of side-effecting behavior.
5135     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5136       return;
5137     VisitIgnoredValue(E);
5138   }
5139 };
5140 
5141 } // namespace
5142 
5143 //===----------------------------------------------------------------------===//
5144 // Common base class for lvalue and temporary evaluation.
5145 //===----------------------------------------------------------------------===//
5146 namespace {
5147 template<class Derived>
5148 class LValueExprEvaluatorBase
5149   : public ExprEvaluatorBase<Derived> {
5150 protected:
5151   LValue &Result;
5152   bool InvalidBaseOK;
5153   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5154   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5155 
5156   bool Success(APValue::LValueBase B) {
5157     Result.set(B);
5158     return true;
5159   }
5160 
5161   bool evaluatePointer(const Expr *E, LValue &Result) {
5162     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5163   }
5164 
5165 public:
5166   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5167       : ExprEvaluatorBaseTy(Info), Result(Result),
5168         InvalidBaseOK(InvalidBaseOK) {}
5169 
5170   bool Success(const APValue &V, const Expr *E) {
5171     Result.setFrom(this->Info.Ctx, V);
5172     return true;
5173   }
5174 
5175   bool VisitMemberExpr(const MemberExpr *E) {
5176     // Handle non-static data members.
5177     QualType BaseTy;
5178     bool EvalOK;
5179     if (E->isArrow()) {
5180       EvalOK = evaluatePointer(E->getBase(), Result);
5181       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5182     } else if (E->getBase()->isRValue()) {
5183       assert(E->getBase()->getType()->isRecordType());
5184       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5185       BaseTy = E->getBase()->getType();
5186     } else {
5187       EvalOK = this->Visit(E->getBase());
5188       BaseTy = E->getBase()->getType();
5189     }
5190     if (!EvalOK) {
5191       if (!InvalidBaseOK)
5192         return false;
5193       Result.setInvalid(E);
5194       return true;
5195     }
5196 
5197     const ValueDecl *MD = E->getMemberDecl();
5198     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5199       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5200              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5201       (void)BaseTy;
5202       if (!HandleLValueMember(this->Info, E, Result, FD))
5203         return false;
5204     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5205       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5206         return false;
5207     } else
5208       return this->Error(E);
5209 
5210     if (MD->getType()->isReferenceType()) {
5211       APValue RefValue;
5212       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5213                                           RefValue))
5214         return false;
5215       return Success(RefValue, E);
5216     }
5217     return true;
5218   }
5219 
5220   bool VisitBinaryOperator(const BinaryOperator *E) {
5221     switch (E->getOpcode()) {
5222     default:
5223       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5224 
5225     case BO_PtrMemD:
5226     case BO_PtrMemI:
5227       return HandleMemberPointerAccess(this->Info, E, Result);
5228     }
5229   }
5230 
5231   bool VisitCastExpr(const CastExpr *E) {
5232     switch (E->getCastKind()) {
5233     default:
5234       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5235 
5236     case CK_DerivedToBase:
5237     case CK_UncheckedDerivedToBase:
5238       if (!this->Visit(E->getSubExpr()))
5239         return false;
5240 
5241       // Now figure out the necessary offset to add to the base LV to get from
5242       // the derived class to the base class.
5243       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5244                                   Result);
5245     }
5246   }
5247 };
5248 }
5249 
5250 //===----------------------------------------------------------------------===//
5251 // LValue Evaluation
5252 //
5253 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5254 // function designators (in C), decl references to void objects (in C), and
5255 // temporaries (if building with -Wno-address-of-temporary).
5256 //
5257 // LValue evaluation produces values comprising a base expression of one of the
5258 // following types:
5259 // - Declarations
5260 //  * VarDecl
5261 //  * FunctionDecl
5262 // - Literals
5263 //  * CompoundLiteralExpr in C (and in global scope in C++)
5264 //  * StringLiteral
5265 //  * CXXTypeidExpr
5266 //  * PredefinedExpr
5267 //  * ObjCStringLiteralExpr
5268 //  * ObjCEncodeExpr
5269 //  * AddrLabelExpr
5270 //  * BlockExpr
5271 //  * CallExpr for a MakeStringConstant builtin
5272 // - Locals and temporaries
5273 //  * MaterializeTemporaryExpr
5274 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5275 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5276 //    from the AST (FIXME).
5277 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5278 //    CallIndex, for a lifetime-extended temporary.
5279 // plus an offset in bytes.
5280 //===----------------------------------------------------------------------===//
5281 namespace {
5282 class LValueExprEvaluator
5283   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5284 public:
5285   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5286     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5287 
5288   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5289   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5290 
5291   bool VisitDeclRefExpr(const DeclRefExpr *E);
5292   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5293   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5294   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5295   bool VisitMemberExpr(const MemberExpr *E);
5296   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5297   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5298   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5299   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5300   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5301   bool VisitUnaryDeref(const UnaryOperator *E);
5302   bool VisitUnaryReal(const UnaryOperator *E);
5303   bool VisitUnaryImag(const UnaryOperator *E);
5304   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5305     return VisitUnaryPreIncDec(UO);
5306   }
5307   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5308     return VisitUnaryPreIncDec(UO);
5309   }
5310   bool VisitBinAssign(const BinaryOperator *BO);
5311   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5312 
5313   bool VisitCastExpr(const CastExpr *E) {
5314     switch (E->getCastKind()) {
5315     default:
5316       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5317 
5318     case CK_LValueBitCast:
5319       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5320       if (!Visit(E->getSubExpr()))
5321         return false;
5322       Result.Designator.setInvalid();
5323       return true;
5324 
5325     case CK_BaseToDerived:
5326       if (!Visit(E->getSubExpr()))
5327         return false;
5328       return HandleBaseToDerivedCast(Info, E, Result);
5329     }
5330   }
5331 };
5332 } // end anonymous namespace
5333 
5334 /// Evaluate an expression as an lvalue. This can be legitimately called on
5335 /// expressions which are not glvalues, in three cases:
5336 ///  * function designators in C, and
5337 ///  * "extern void" objects
5338 ///  * @selector() expressions in Objective-C
5339 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5340                            bool InvalidBaseOK) {
5341   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5342          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5343   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5344 }
5345 
5346 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5347   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5348     return Success(FD);
5349   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5350     return VisitVarDecl(E, VD);
5351   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5352     return Visit(BD->getBinding());
5353   return Error(E);
5354 }
5355 
5356 
5357 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5358 
5359   // If we are within a lambda's call operator, check whether the 'VD' referred
5360   // to within 'E' actually represents a lambda-capture that maps to a
5361   // data-member/field within the closure object, and if so, evaluate to the
5362   // field or what the field refers to.
5363   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5364       isa<DeclRefExpr>(E) &&
5365       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5366     // We don't always have a complete capture-map when checking or inferring if
5367     // the function call operator meets the requirements of a constexpr function
5368     // - but we don't need to evaluate the captures to determine constexprness
5369     // (dcl.constexpr C++17).
5370     if (Info.checkingPotentialConstantExpression())
5371       return false;
5372 
5373     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5374       // Start with 'Result' referring to the complete closure object...
5375       Result = *Info.CurrentCall->This;
5376       // ... then update it to refer to the field of the closure object
5377       // that represents the capture.
5378       if (!HandleLValueMember(Info, E, Result, FD))
5379         return false;
5380       // And if the field is of reference type, update 'Result' to refer to what
5381       // the field refers to.
5382       if (FD->getType()->isReferenceType()) {
5383         APValue RVal;
5384         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5385                                             RVal))
5386           return false;
5387         Result.setFrom(Info.Ctx, RVal);
5388       }
5389       return true;
5390     }
5391   }
5392   CallStackFrame *Frame = nullptr;
5393   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5394     // Only if a local variable was declared in the function currently being
5395     // evaluated, do we expect to be able to find its value in the current
5396     // frame. (Otherwise it was likely declared in an enclosing context and
5397     // could either have a valid evaluatable value (for e.g. a constexpr
5398     // variable) or be ill-formed (and trigger an appropriate evaluation
5399     // diagnostic)).
5400     if (Info.CurrentCall->Callee &&
5401         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5402       Frame = Info.CurrentCall;
5403     }
5404   }
5405 
5406   if (!VD->getType()->isReferenceType()) {
5407     if (Frame) {
5408       Result.set({VD, Frame->Index,
5409                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5410       return true;
5411     }
5412     return Success(VD);
5413   }
5414 
5415   APValue *V;
5416   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5417     return false;
5418   if (V->isUninit()) {
5419     if (!Info.checkingPotentialConstantExpression())
5420       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5421     return false;
5422   }
5423   return Success(*V, E);
5424 }
5425 
5426 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5427     const MaterializeTemporaryExpr *E) {
5428   // Walk through the expression to find the materialized temporary itself.
5429   SmallVector<const Expr *, 2> CommaLHSs;
5430   SmallVector<SubobjectAdjustment, 2> Adjustments;
5431   const Expr *Inner = E->GetTemporaryExpr()->
5432       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5433 
5434   // If we passed any comma operators, evaluate their LHSs.
5435   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5436     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5437       return false;
5438 
5439   // A materialized temporary with static storage duration can appear within the
5440   // result of a constant expression evaluation, so we need to preserve its
5441   // value for use outside this evaluation.
5442   APValue *Value;
5443   if (E->getStorageDuration() == SD_Static) {
5444     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5445     *Value = APValue();
5446     Result.set(E);
5447   } else {
5448     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5449                              *Info.CurrentCall);
5450   }
5451 
5452   QualType Type = Inner->getType();
5453 
5454   // Materialize the temporary itself.
5455   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5456       (E->getStorageDuration() == SD_Static &&
5457        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5458     *Value = APValue();
5459     return false;
5460   }
5461 
5462   // Adjust our lvalue to refer to the desired subobject.
5463   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5464     --I;
5465     switch (Adjustments[I].Kind) {
5466     case SubobjectAdjustment::DerivedToBaseAdjustment:
5467       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5468                                 Type, Result))
5469         return false;
5470       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5471       break;
5472 
5473     case SubobjectAdjustment::FieldAdjustment:
5474       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5475         return false;
5476       Type = Adjustments[I].Field->getType();
5477       break;
5478 
5479     case SubobjectAdjustment::MemberPointerAdjustment:
5480       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5481                                      Adjustments[I].Ptr.RHS))
5482         return false;
5483       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5484       break;
5485     }
5486   }
5487 
5488   return true;
5489 }
5490 
5491 bool
5492 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5493   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5494          "lvalue compound literal in c++?");
5495   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5496   // only see this when folding in C, so there's no standard to follow here.
5497   return Success(E);
5498 }
5499 
5500 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5501   if (!E->isPotentiallyEvaluated())
5502     return Success(E);
5503 
5504   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5505     << E->getExprOperand()->getType()
5506     << E->getExprOperand()->getSourceRange();
5507   return false;
5508 }
5509 
5510 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5511   return Success(E);
5512 }
5513 
5514 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5515   // Handle static data members.
5516   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5517     VisitIgnoredBaseExpression(E->getBase());
5518     return VisitVarDecl(E, VD);
5519   }
5520 
5521   // Handle static member functions.
5522   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5523     if (MD->isStatic()) {
5524       VisitIgnoredBaseExpression(E->getBase());
5525       return Success(MD);
5526     }
5527   }
5528 
5529   // Handle non-static data members.
5530   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5531 }
5532 
5533 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5534   // FIXME: Deal with vectors as array subscript bases.
5535   if (E->getBase()->getType()->isVectorType())
5536     return Error(E);
5537 
5538   bool Success = true;
5539   if (!evaluatePointer(E->getBase(), Result)) {
5540     if (!Info.noteFailure())
5541       return false;
5542     Success = false;
5543   }
5544 
5545   APSInt Index;
5546   if (!EvaluateInteger(E->getIdx(), Index, Info))
5547     return false;
5548 
5549   return Success &&
5550          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5551 }
5552 
5553 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5554   return evaluatePointer(E->getSubExpr(), Result);
5555 }
5556 
5557 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5558   if (!Visit(E->getSubExpr()))
5559     return false;
5560   // __real is a no-op on scalar lvalues.
5561   if (E->getSubExpr()->getType()->isAnyComplexType())
5562     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5563   return true;
5564 }
5565 
5566 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5567   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5568          "lvalue __imag__ on scalar?");
5569   if (!Visit(E->getSubExpr()))
5570     return false;
5571   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5572   return true;
5573 }
5574 
5575 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5576   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5577     return Error(UO);
5578 
5579   if (!this->Visit(UO->getSubExpr()))
5580     return false;
5581 
5582   return handleIncDec(
5583       this->Info, UO, Result, UO->getSubExpr()->getType(),
5584       UO->isIncrementOp(), nullptr);
5585 }
5586 
5587 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5588     const CompoundAssignOperator *CAO) {
5589   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5590     return Error(CAO);
5591 
5592   APValue RHS;
5593 
5594   // The overall lvalue result is the result of evaluating the LHS.
5595   if (!this->Visit(CAO->getLHS())) {
5596     if (Info.noteFailure())
5597       Evaluate(RHS, this->Info, CAO->getRHS());
5598     return false;
5599   }
5600 
5601   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5602     return false;
5603 
5604   return handleCompoundAssignment(
5605       this->Info, CAO,
5606       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5607       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5608 }
5609 
5610 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5611   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5612     return Error(E);
5613 
5614   APValue NewVal;
5615 
5616   if (!this->Visit(E->getLHS())) {
5617     if (Info.noteFailure())
5618       Evaluate(NewVal, this->Info, E->getRHS());
5619     return false;
5620   }
5621 
5622   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5623     return false;
5624 
5625   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5626                           NewVal);
5627 }
5628 
5629 //===----------------------------------------------------------------------===//
5630 // Pointer Evaluation
5631 //===----------------------------------------------------------------------===//
5632 
5633 /// Attempts to compute the number of bytes available at the pointer
5634 /// returned by a function with the alloc_size attribute. Returns true if we
5635 /// were successful. Places an unsigned number into `Result`.
5636 ///
5637 /// This expects the given CallExpr to be a call to a function with an
5638 /// alloc_size attribute.
5639 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5640                                             const CallExpr *Call,
5641                                             llvm::APInt &Result) {
5642   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5643 
5644   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5645   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5646   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5647   if (Call->getNumArgs() <= SizeArgNo)
5648     return false;
5649 
5650   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5651     Expr::EvalResult ExprResult;
5652     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
5653       return false;
5654     Into = ExprResult.Val.getInt();
5655     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5656       return false;
5657     Into = Into.zextOrSelf(BitsInSizeT);
5658     return true;
5659   };
5660 
5661   APSInt SizeOfElem;
5662   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5663     return false;
5664 
5665   if (!AllocSize->getNumElemsParam().isValid()) {
5666     Result = std::move(SizeOfElem);
5667     return true;
5668   }
5669 
5670   APSInt NumberOfElems;
5671   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5672   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5673     return false;
5674 
5675   bool Overflow;
5676   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5677   if (Overflow)
5678     return false;
5679 
5680   Result = std::move(BytesAvailable);
5681   return true;
5682 }
5683 
5684 /// Convenience function. LVal's base must be a call to an alloc_size
5685 /// function.
5686 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5687                                             const LValue &LVal,
5688                                             llvm::APInt &Result) {
5689   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5690          "Can't get the size of a non alloc_size function");
5691   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5692   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5693   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5694 }
5695 
5696 /// Attempts to evaluate the given LValueBase as the result of a call to
5697 /// a function with the alloc_size attribute. If it was possible to do so, this
5698 /// function will return true, make Result's Base point to said function call,
5699 /// and mark Result's Base as invalid.
5700 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5701                                       LValue &Result) {
5702   if (Base.isNull())
5703     return false;
5704 
5705   // Because we do no form of static analysis, we only support const variables.
5706   //
5707   // Additionally, we can't support parameters, nor can we support static
5708   // variables (in the latter case, use-before-assign isn't UB; in the former,
5709   // we have no clue what they'll be assigned to).
5710   const auto *VD =
5711       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5712   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5713     return false;
5714 
5715   const Expr *Init = VD->getAnyInitializer();
5716   if (!Init)
5717     return false;
5718 
5719   const Expr *E = Init->IgnoreParens();
5720   if (!tryUnwrapAllocSizeCall(E))
5721     return false;
5722 
5723   // Store E instead of E unwrapped so that the type of the LValue's base is
5724   // what the user wanted.
5725   Result.setInvalid(E);
5726 
5727   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5728   Result.addUnsizedArray(Info, E, Pointee);
5729   return true;
5730 }
5731 
5732 namespace {
5733 class PointerExprEvaluator
5734   : public ExprEvaluatorBase<PointerExprEvaluator> {
5735   LValue &Result;
5736   bool InvalidBaseOK;
5737 
5738   bool Success(const Expr *E) {
5739     Result.set(E);
5740     return true;
5741   }
5742 
5743   bool evaluateLValue(const Expr *E, LValue &Result) {
5744     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5745   }
5746 
5747   bool evaluatePointer(const Expr *E, LValue &Result) {
5748     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5749   }
5750 
5751   bool visitNonBuiltinCallExpr(const CallExpr *E);
5752 public:
5753 
5754   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5755       : ExprEvaluatorBaseTy(info), Result(Result),
5756         InvalidBaseOK(InvalidBaseOK) {}
5757 
5758   bool Success(const APValue &V, const Expr *E) {
5759     Result.setFrom(Info.Ctx, V);
5760     return true;
5761   }
5762   bool ZeroInitialization(const Expr *E) {
5763     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5764     Result.setNull(E->getType(), TargetVal);
5765     return true;
5766   }
5767 
5768   bool VisitBinaryOperator(const BinaryOperator *E);
5769   bool VisitCastExpr(const CastExpr* E);
5770   bool VisitUnaryAddrOf(const UnaryOperator *E);
5771   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5772       { return Success(E); }
5773   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5774     if (Info.noteFailure())
5775       EvaluateIgnoredValue(Info, E->getSubExpr());
5776     return Error(E);
5777   }
5778   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5779       { return Success(E); }
5780   bool VisitCallExpr(const CallExpr *E);
5781   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5782   bool VisitBlockExpr(const BlockExpr *E) {
5783     if (!E->getBlockDecl()->hasCaptures())
5784       return Success(E);
5785     return Error(E);
5786   }
5787   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5788     // Can't look at 'this' when checking a potential constant expression.
5789     if (Info.checkingPotentialConstantExpression())
5790       return false;
5791     if (!Info.CurrentCall->This) {
5792       if (Info.getLangOpts().CPlusPlus11)
5793         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5794       else
5795         Info.FFDiag(E);
5796       return false;
5797     }
5798     Result = *Info.CurrentCall->This;
5799     // If we are inside a lambda's call operator, the 'this' expression refers
5800     // to the enclosing '*this' object (either by value or reference) which is
5801     // either copied into the closure object's field that represents the '*this'
5802     // or refers to '*this'.
5803     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5804       // Update 'Result' to refer to the data member/field of the closure object
5805       // that represents the '*this' capture.
5806       if (!HandleLValueMember(Info, E, Result,
5807                              Info.CurrentCall->LambdaThisCaptureField))
5808         return false;
5809       // If we captured '*this' by reference, replace the field with its referent.
5810       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5811               ->isPointerType()) {
5812         APValue RVal;
5813         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5814                                             RVal))
5815           return false;
5816 
5817         Result.setFrom(Info.Ctx, RVal);
5818       }
5819     }
5820     return true;
5821   }
5822 
5823   // FIXME: Missing: @protocol, @selector
5824 };
5825 } // end anonymous namespace
5826 
5827 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5828                             bool InvalidBaseOK) {
5829   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5830   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5831 }
5832 
5833 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5834   if (E->getOpcode() != BO_Add &&
5835       E->getOpcode() != BO_Sub)
5836     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5837 
5838   const Expr *PExp = E->getLHS();
5839   const Expr *IExp = E->getRHS();
5840   if (IExp->getType()->isPointerType())
5841     std::swap(PExp, IExp);
5842 
5843   bool EvalPtrOK = evaluatePointer(PExp, Result);
5844   if (!EvalPtrOK && !Info.noteFailure())
5845     return false;
5846 
5847   llvm::APSInt Offset;
5848   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5849     return false;
5850 
5851   if (E->getOpcode() == BO_Sub)
5852     negateAsSigned(Offset);
5853 
5854   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5855   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5856 }
5857 
5858 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5859   return evaluateLValue(E->getSubExpr(), Result);
5860 }
5861 
5862 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5863   const Expr *SubExpr = E->getSubExpr();
5864 
5865   switch (E->getCastKind()) {
5866   default:
5867     break;
5868 
5869   case CK_BitCast:
5870   case CK_CPointerToObjCPointerCast:
5871   case CK_BlockPointerToObjCPointerCast:
5872   case CK_AnyPointerToBlockPointerCast:
5873   case CK_AddressSpaceConversion:
5874     if (!Visit(SubExpr))
5875       return false;
5876     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5877     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5878     // also static_casts, but we disallow them as a resolution to DR1312.
5879     if (!E->getType()->isVoidPointerType()) {
5880       Result.Designator.setInvalid();
5881       if (SubExpr->getType()->isVoidPointerType())
5882         CCEDiag(E, diag::note_constexpr_invalid_cast)
5883           << 3 << SubExpr->getType();
5884       else
5885         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5886     }
5887     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5888       ZeroInitialization(E);
5889     return true;
5890 
5891   case CK_DerivedToBase:
5892   case CK_UncheckedDerivedToBase:
5893     if (!evaluatePointer(E->getSubExpr(), Result))
5894       return false;
5895     if (!Result.Base && Result.Offset.isZero())
5896       return true;
5897 
5898     // Now figure out the necessary offset to add to the base LV to get from
5899     // the derived class to the base class.
5900     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5901                                   castAs<PointerType>()->getPointeeType(),
5902                                 Result);
5903 
5904   case CK_BaseToDerived:
5905     if (!Visit(E->getSubExpr()))
5906       return false;
5907     if (!Result.Base && Result.Offset.isZero())
5908       return true;
5909     return HandleBaseToDerivedCast(Info, E, Result);
5910 
5911   case CK_NullToPointer:
5912     VisitIgnoredValue(E->getSubExpr());
5913     return ZeroInitialization(E);
5914 
5915   case CK_IntegralToPointer: {
5916     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5917 
5918     APValue Value;
5919     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5920       break;
5921 
5922     if (Value.isInt()) {
5923       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5924       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5925       Result.Base = (Expr*)nullptr;
5926       Result.InvalidBase = false;
5927       Result.Offset = CharUnits::fromQuantity(N);
5928       Result.Designator.setInvalid();
5929       Result.IsNullPtr = false;
5930       return true;
5931     } else {
5932       // Cast is of an lvalue, no need to change value.
5933       Result.setFrom(Info.Ctx, Value);
5934       return true;
5935     }
5936   }
5937 
5938   case CK_ArrayToPointerDecay: {
5939     if (SubExpr->isGLValue()) {
5940       if (!evaluateLValue(SubExpr, Result))
5941         return false;
5942     } else {
5943       APValue &Value = createTemporary(SubExpr, false, Result,
5944                                        *Info.CurrentCall);
5945       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5946         return false;
5947     }
5948     // The result is a pointer to the first element of the array.
5949     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5950     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5951       Result.addArray(Info, E, CAT);
5952     else
5953       Result.addUnsizedArray(Info, E, AT->getElementType());
5954     return true;
5955   }
5956 
5957   case CK_FunctionToPointerDecay:
5958     return evaluateLValue(SubExpr, Result);
5959 
5960   case CK_LValueToRValue: {
5961     LValue LVal;
5962     if (!evaluateLValue(E->getSubExpr(), LVal))
5963       return false;
5964 
5965     APValue RVal;
5966     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5967     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5968                                         LVal, RVal))
5969       return InvalidBaseOK &&
5970              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5971     return Success(RVal, E);
5972   }
5973   }
5974 
5975   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5976 }
5977 
5978 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5979                                 UnaryExprOrTypeTrait ExprKind) {
5980   // C++ [expr.alignof]p3:
5981   //     When alignof is applied to a reference type, the result is the
5982   //     alignment of the referenced type.
5983   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5984     T = Ref->getPointeeType();
5985 
5986   if (T.getQualifiers().hasUnaligned())
5987     return CharUnits::One();
5988 
5989   const bool AlignOfReturnsPreferred =
5990       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
5991 
5992   // __alignof is defined to return the preferred alignment.
5993   // Before 8, clang returned the preferred alignment for alignof and _Alignof
5994   // as well.
5995   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
5996     return Info.Ctx.toCharUnitsFromBits(
5997       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5998   // alignof and _Alignof are defined to return the ABI alignment.
5999   else if (ExprKind == UETT_AlignOf)
6000     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6001   else
6002     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6003 }
6004 
6005 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6006                                 UnaryExprOrTypeTrait ExprKind) {
6007   E = E->IgnoreParens();
6008 
6009   // The kinds of expressions that we have special-case logic here for
6010   // should be kept up to date with the special checks for those
6011   // expressions in Sema.
6012 
6013   // alignof decl is always accepted, even if it doesn't make sense: we default
6014   // to 1 in those cases.
6015   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6016     return Info.Ctx.getDeclAlign(DRE->getDecl(),
6017                                  /*RefAsPointee*/true);
6018 
6019   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6020     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6021                                  /*RefAsPointee*/true);
6022 
6023   return GetAlignOfType(Info, E->getType(), ExprKind);
6024 }
6025 
6026 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6027 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6028   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6029     return true;
6030 
6031   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6032     return false;
6033 
6034   Result.setInvalid(E);
6035   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6036   Result.addUnsizedArray(Info, E, PointeeTy);
6037   return true;
6038 }
6039 
6040 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6041   if (IsStringLiteralCall(E))
6042     return Success(E);
6043 
6044   if (unsigned BuiltinOp = E->getBuiltinCallee())
6045     return VisitBuiltinCallExpr(E, BuiltinOp);
6046 
6047   return visitNonBuiltinCallExpr(E);
6048 }
6049 
6050 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6051                                                 unsigned BuiltinOp) {
6052   switch (BuiltinOp) {
6053   case Builtin::BI__builtin_addressof:
6054     return evaluateLValue(E->getArg(0), Result);
6055   case Builtin::BI__builtin_assume_aligned: {
6056     // We need to be very careful here because: if the pointer does not have the
6057     // asserted alignment, then the behavior is undefined, and undefined
6058     // behavior is non-constant.
6059     if (!evaluatePointer(E->getArg(0), Result))
6060       return false;
6061 
6062     LValue OffsetResult(Result);
6063     APSInt Alignment;
6064     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6065       return false;
6066     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6067 
6068     if (E->getNumArgs() > 2) {
6069       APSInt Offset;
6070       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6071         return false;
6072 
6073       int64_t AdditionalOffset = -Offset.getZExtValue();
6074       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6075     }
6076 
6077     // If there is a base object, then it must have the correct alignment.
6078     if (OffsetResult.Base) {
6079       CharUnits BaseAlignment;
6080       if (const ValueDecl *VD =
6081           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6082         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6083       } else {
6084         BaseAlignment = GetAlignOfExpr(
6085             Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
6086       }
6087 
6088       if (BaseAlignment < Align) {
6089         Result.Designator.setInvalid();
6090         // FIXME: Add support to Diagnostic for long / long long.
6091         CCEDiag(E->getArg(0),
6092                 diag::note_constexpr_baa_insufficient_alignment) << 0
6093           << (unsigned)BaseAlignment.getQuantity()
6094           << (unsigned)Align.getQuantity();
6095         return false;
6096       }
6097     }
6098 
6099     // The offset must also have the correct alignment.
6100     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6101       Result.Designator.setInvalid();
6102 
6103       (OffsetResult.Base
6104            ? CCEDiag(E->getArg(0),
6105                      diag::note_constexpr_baa_insufficient_alignment) << 1
6106            : CCEDiag(E->getArg(0),
6107                      diag::note_constexpr_baa_value_insufficient_alignment))
6108         << (int)OffsetResult.Offset.getQuantity()
6109         << (unsigned)Align.getQuantity();
6110       return false;
6111     }
6112 
6113     return true;
6114   }
6115 
6116   case Builtin::BIstrchr:
6117   case Builtin::BIwcschr:
6118   case Builtin::BImemchr:
6119   case Builtin::BIwmemchr:
6120     if (Info.getLangOpts().CPlusPlus11)
6121       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6122         << /*isConstexpr*/0 << /*isConstructor*/0
6123         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6124     else
6125       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6126     LLVM_FALLTHROUGH;
6127   case Builtin::BI__builtin_strchr:
6128   case Builtin::BI__builtin_wcschr:
6129   case Builtin::BI__builtin_memchr:
6130   case Builtin::BI__builtin_char_memchr:
6131   case Builtin::BI__builtin_wmemchr: {
6132     if (!Visit(E->getArg(0)))
6133       return false;
6134     APSInt Desired;
6135     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6136       return false;
6137     uint64_t MaxLength = uint64_t(-1);
6138     if (BuiltinOp != Builtin::BIstrchr &&
6139         BuiltinOp != Builtin::BIwcschr &&
6140         BuiltinOp != Builtin::BI__builtin_strchr &&
6141         BuiltinOp != Builtin::BI__builtin_wcschr) {
6142       APSInt N;
6143       if (!EvaluateInteger(E->getArg(2), N, Info))
6144         return false;
6145       MaxLength = N.getExtValue();
6146     }
6147     // We cannot find the value if there are no candidates to match against.
6148     if (MaxLength == 0u)
6149       return ZeroInitialization(E);
6150     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6151         Result.Designator.Invalid)
6152       return false;
6153     QualType CharTy = Result.Designator.getType(Info.Ctx);
6154     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6155                      BuiltinOp == Builtin::BI__builtin_memchr;
6156     assert(IsRawByte ||
6157            Info.Ctx.hasSameUnqualifiedType(
6158                CharTy, E->getArg(0)->getType()->getPointeeType()));
6159     // Pointers to const void may point to objects of incomplete type.
6160     if (IsRawByte && CharTy->isIncompleteType()) {
6161       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6162       return false;
6163     }
6164     // Give up on byte-oriented matching against multibyte elements.
6165     // FIXME: We can compare the bytes in the correct order.
6166     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6167       return false;
6168     // Figure out what value we're actually looking for (after converting to
6169     // the corresponding unsigned type if necessary).
6170     uint64_t DesiredVal;
6171     bool StopAtNull = false;
6172     switch (BuiltinOp) {
6173     case Builtin::BIstrchr:
6174     case Builtin::BI__builtin_strchr:
6175       // strchr compares directly to the passed integer, and therefore
6176       // always fails if given an int that is not a char.
6177       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6178                                                   E->getArg(1)->getType(),
6179                                                   Desired),
6180                                Desired))
6181         return ZeroInitialization(E);
6182       StopAtNull = true;
6183       LLVM_FALLTHROUGH;
6184     case Builtin::BImemchr:
6185     case Builtin::BI__builtin_memchr:
6186     case Builtin::BI__builtin_char_memchr:
6187       // memchr compares by converting both sides to unsigned char. That's also
6188       // correct for strchr if we get this far (to cope with plain char being
6189       // unsigned in the strchr case).
6190       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6191       break;
6192 
6193     case Builtin::BIwcschr:
6194     case Builtin::BI__builtin_wcschr:
6195       StopAtNull = true;
6196       LLVM_FALLTHROUGH;
6197     case Builtin::BIwmemchr:
6198     case Builtin::BI__builtin_wmemchr:
6199       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6200       DesiredVal = Desired.getZExtValue();
6201       break;
6202     }
6203 
6204     for (; MaxLength; --MaxLength) {
6205       APValue Char;
6206       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6207           !Char.isInt())
6208         return false;
6209       if (Char.getInt().getZExtValue() == DesiredVal)
6210         return true;
6211       if (StopAtNull && !Char.getInt())
6212         break;
6213       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6214         return false;
6215     }
6216     // Not found: return nullptr.
6217     return ZeroInitialization(E);
6218   }
6219 
6220   case Builtin::BImemcpy:
6221   case Builtin::BImemmove:
6222   case Builtin::BIwmemcpy:
6223   case Builtin::BIwmemmove:
6224     if (Info.getLangOpts().CPlusPlus11)
6225       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6226         << /*isConstexpr*/0 << /*isConstructor*/0
6227         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6228     else
6229       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6230     LLVM_FALLTHROUGH;
6231   case Builtin::BI__builtin_memcpy:
6232   case Builtin::BI__builtin_memmove:
6233   case Builtin::BI__builtin_wmemcpy:
6234   case Builtin::BI__builtin_wmemmove: {
6235     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6236                  BuiltinOp == Builtin::BIwmemmove ||
6237                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6238                  BuiltinOp == Builtin::BI__builtin_wmemmove;
6239     bool Move = BuiltinOp == Builtin::BImemmove ||
6240                 BuiltinOp == Builtin::BIwmemmove ||
6241                 BuiltinOp == Builtin::BI__builtin_memmove ||
6242                 BuiltinOp == Builtin::BI__builtin_wmemmove;
6243 
6244     // The result of mem* is the first argument.
6245     if (!Visit(E->getArg(0)))
6246       return false;
6247     LValue Dest = Result;
6248 
6249     LValue Src;
6250     if (!EvaluatePointer(E->getArg(1), Src, Info))
6251       return false;
6252 
6253     APSInt N;
6254     if (!EvaluateInteger(E->getArg(2), N, Info))
6255       return false;
6256     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6257 
6258     // If the size is zero, we treat this as always being a valid no-op.
6259     // (Even if one of the src and dest pointers is null.)
6260     if (!N)
6261       return true;
6262 
6263     // Otherwise, if either of the operands is null, we can't proceed. Don't
6264     // try to determine the type of the copied objects, because there aren't
6265     // any.
6266     if (!Src.Base || !Dest.Base) {
6267       APValue Val;
6268       (!Src.Base ? Src : Dest).moveInto(Val);
6269       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6270           << Move << WChar << !!Src.Base
6271           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6272       return false;
6273     }
6274     if (Src.Designator.Invalid || Dest.Designator.Invalid)
6275       return false;
6276 
6277     // We require that Src and Dest are both pointers to arrays of
6278     // trivially-copyable type. (For the wide version, the designator will be
6279     // invalid if the designated object is not a wchar_t.)
6280     QualType T = Dest.Designator.getType(Info.Ctx);
6281     QualType SrcT = Src.Designator.getType(Info.Ctx);
6282     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6283       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6284       return false;
6285     }
6286     if (T->isIncompleteType()) {
6287       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6288       return false;
6289     }
6290     if (!T.isTriviallyCopyableType(Info.Ctx)) {
6291       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6292       return false;
6293     }
6294 
6295     // Figure out how many T's we're copying.
6296     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6297     if (!WChar) {
6298       uint64_t Remainder;
6299       llvm::APInt OrigN = N;
6300       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6301       if (Remainder) {
6302         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6303             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6304             << (unsigned)TSize;
6305         return false;
6306       }
6307     }
6308 
6309     // Check that the copying will remain within the arrays, just so that we
6310     // can give a more meaningful diagnostic. This implicitly also checks that
6311     // N fits into 64 bits.
6312     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6313     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6314     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6315       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6316           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6317           << N.toString(10, /*Signed*/false);
6318       return false;
6319     }
6320     uint64_t NElems = N.getZExtValue();
6321     uint64_t NBytes = NElems * TSize;
6322 
6323     // Check for overlap.
6324     int Direction = 1;
6325     if (HasSameBase(Src, Dest)) {
6326       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6327       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6328       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6329         // Dest is inside the source region.
6330         if (!Move) {
6331           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6332           return false;
6333         }
6334         // For memmove and friends, copy backwards.
6335         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6336             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6337           return false;
6338         Direction = -1;
6339       } else if (!Move && SrcOffset >= DestOffset &&
6340                  SrcOffset - DestOffset < NBytes) {
6341         // Src is inside the destination region for memcpy: invalid.
6342         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6343         return false;
6344       }
6345     }
6346 
6347     while (true) {
6348       APValue Val;
6349       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6350           !handleAssignment(Info, E, Dest, T, Val))
6351         return false;
6352       // Do not iterate past the last element; if we're copying backwards, that
6353       // might take us off the start of the array.
6354       if (--NElems == 0)
6355         return true;
6356       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6357           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6358         return false;
6359     }
6360   }
6361 
6362   default:
6363     return visitNonBuiltinCallExpr(E);
6364   }
6365 }
6366 
6367 //===----------------------------------------------------------------------===//
6368 // Member Pointer Evaluation
6369 //===----------------------------------------------------------------------===//
6370 
6371 namespace {
6372 class MemberPointerExprEvaluator
6373   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6374   MemberPtr &Result;
6375 
6376   bool Success(const ValueDecl *D) {
6377     Result = MemberPtr(D);
6378     return true;
6379   }
6380 public:
6381 
6382   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6383     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6384 
6385   bool Success(const APValue &V, const Expr *E) {
6386     Result.setFrom(V);
6387     return true;
6388   }
6389   bool ZeroInitialization(const Expr *E) {
6390     return Success((const ValueDecl*)nullptr);
6391   }
6392 
6393   bool VisitCastExpr(const CastExpr *E);
6394   bool VisitUnaryAddrOf(const UnaryOperator *E);
6395 };
6396 } // end anonymous namespace
6397 
6398 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6399                                   EvalInfo &Info) {
6400   assert(E->isRValue() && E->getType()->isMemberPointerType());
6401   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6402 }
6403 
6404 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6405   switch (E->getCastKind()) {
6406   default:
6407     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6408 
6409   case CK_NullToMemberPointer:
6410     VisitIgnoredValue(E->getSubExpr());
6411     return ZeroInitialization(E);
6412 
6413   case CK_BaseToDerivedMemberPointer: {
6414     if (!Visit(E->getSubExpr()))
6415       return false;
6416     if (E->path_empty())
6417       return true;
6418     // Base-to-derived member pointer casts store the path in derived-to-base
6419     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6420     // the wrong end of the derived->base arc, so stagger the path by one class.
6421     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6422     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6423          PathI != PathE; ++PathI) {
6424       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6425       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6426       if (!Result.castToDerived(Derived))
6427         return Error(E);
6428     }
6429     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6430     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6431       return Error(E);
6432     return true;
6433   }
6434 
6435   case CK_DerivedToBaseMemberPointer:
6436     if (!Visit(E->getSubExpr()))
6437       return false;
6438     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6439          PathE = E->path_end(); PathI != PathE; ++PathI) {
6440       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6441       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6442       if (!Result.castToBase(Base))
6443         return Error(E);
6444     }
6445     return true;
6446   }
6447 }
6448 
6449 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6450   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6451   // member can be formed.
6452   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6453 }
6454 
6455 //===----------------------------------------------------------------------===//
6456 // Record Evaluation
6457 //===----------------------------------------------------------------------===//
6458 
6459 namespace {
6460   class RecordExprEvaluator
6461   : public ExprEvaluatorBase<RecordExprEvaluator> {
6462     const LValue &This;
6463     APValue &Result;
6464   public:
6465 
6466     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6467       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6468 
6469     bool Success(const APValue &V, const Expr *E) {
6470       Result = V;
6471       return true;
6472     }
6473     bool ZeroInitialization(const Expr *E) {
6474       return ZeroInitialization(E, E->getType());
6475     }
6476     bool ZeroInitialization(const Expr *E, QualType T);
6477 
6478     bool VisitCallExpr(const CallExpr *E) {
6479       return handleCallExpr(E, Result, &This);
6480     }
6481     bool VisitCastExpr(const CastExpr *E);
6482     bool VisitInitListExpr(const InitListExpr *E);
6483     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6484       return VisitCXXConstructExpr(E, E->getType());
6485     }
6486     bool VisitLambdaExpr(const LambdaExpr *E);
6487     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6488     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6489     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6490 
6491     bool VisitBinCmp(const BinaryOperator *E);
6492   };
6493 }
6494 
6495 /// Perform zero-initialization on an object of non-union class type.
6496 /// C++11 [dcl.init]p5:
6497 ///  To zero-initialize an object or reference of type T means:
6498 ///    [...]
6499 ///    -- if T is a (possibly cv-qualified) non-union class type,
6500 ///       each non-static data member and each base-class subobject is
6501 ///       zero-initialized
6502 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6503                                           const RecordDecl *RD,
6504                                           const LValue &This, APValue &Result) {
6505   assert(!RD->isUnion() && "Expected non-union class type");
6506   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6507   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6508                    std::distance(RD->field_begin(), RD->field_end()));
6509 
6510   if (RD->isInvalidDecl()) return false;
6511   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6512 
6513   if (CD) {
6514     unsigned Index = 0;
6515     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6516            End = CD->bases_end(); I != End; ++I, ++Index) {
6517       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6518       LValue Subobject = This;
6519       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6520         return false;
6521       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6522                                          Result.getStructBase(Index)))
6523         return false;
6524     }
6525   }
6526 
6527   for (const auto *I : RD->fields()) {
6528     // -- if T is a reference type, no initialization is performed.
6529     if (I->getType()->isReferenceType())
6530       continue;
6531 
6532     LValue Subobject = This;
6533     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6534       return false;
6535 
6536     ImplicitValueInitExpr VIE(I->getType());
6537     if (!EvaluateInPlace(
6538           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6539       return false;
6540   }
6541 
6542   return true;
6543 }
6544 
6545 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6546   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6547   if (RD->isInvalidDecl()) return false;
6548   if (RD->isUnion()) {
6549     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6550     // object's first non-static named data member is zero-initialized
6551     RecordDecl::field_iterator I = RD->field_begin();
6552     if (I == RD->field_end()) {
6553       Result = APValue((const FieldDecl*)nullptr);
6554       return true;
6555     }
6556 
6557     LValue Subobject = This;
6558     if (!HandleLValueMember(Info, E, Subobject, *I))
6559       return false;
6560     Result = APValue(*I);
6561     ImplicitValueInitExpr VIE(I->getType());
6562     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6563   }
6564 
6565   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6566     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6567     return false;
6568   }
6569 
6570   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6571 }
6572 
6573 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6574   switch (E->getCastKind()) {
6575   default:
6576     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6577 
6578   case CK_ConstructorConversion:
6579     return Visit(E->getSubExpr());
6580 
6581   case CK_DerivedToBase:
6582   case CK_UncheckedDerivedToBase: {
6583     APValue DerivedObject;
6584     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6585       return false;
6586     if (!DerivedObject.isStruct())
6587       return Error(E->getSubExpr());
6588 
6589     // Derived-to-base rvalue conversion: just slice off the derived part.
6590     APValue *Value = &DerivedObject;
6591     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6592     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6593          PathE = E->path_end(); PathI != PathE; ++PathI) {
6594       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6595       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6596       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6597       RD = Base;
6598     }
6599     Result = *Value;
6600     return true;
6601   }
6602   }
6603 }
6604 
6605 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6606   if (E->isTransparent())
6607     return Visit(E->getInit(0));
6608 
6609   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6610   if (RD->isInvalidDecl()) return false;
6611   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6612 
6613   if (RD->isUnion()) {
6614     const FieldDecl *Field = E->getInitializedFieldInUnion();
6615     Result = APValue(Field);
6616     if (!Field)
6617       return true;
6618 
6619     // If the initializer list for a union does not contain any elements, the
6620     // first element of the union is value-initialized.
6621     // FIXME: The element should be initialized from an initializer list.
6622     //        Is this difference ever observable for initializer lists which
6623     //        we don't build?
6624     ImplicitValueInitExpr VIE(Field->getType());
6625     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6626 
6627     LValue Subobject = This;
6628     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6629       return false;
6630 
6631     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6632     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6633                                   isa<CXXDefaultInitExpr>(InitExpr));
6634 
6635     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6636   }
6637 
6638   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6639   if (Result.isUninit())
6640     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6641                      std::distance(RD->field_begin(), RD->field_end()));
6642   unsigned ElementNo = 0;
6643   bool Success = true;
6644 
6645   // Initialize base classes.
6646   if (CXXRD) {
6647     for (const auto &Base : CXXRD->bases()) {
6648       assert(ElementNo < E->getNumInits() && "missing init for base class");
6649       const Expr *Init = E->getInit(ElementNo);
6650 
6651       LValue Subobject = This;
6652       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6653         return false;
6654 
6655       APValue &FieldVal = Result.getStructBase(ElementNo);
6656       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6657         if (!Info.noteFailure())
6658           return false;
6659         Success = false;
6660       }
6661       ++ElementNo;
6662     }
6663   }
6664 
6665   // Initialize members.
6666   for (const auto *Field : RD->fields()) {
6667     // Anonymous bit-fields are not considered members of the class for
6668     // purposes of aggregate initialization.
6669     if (Field->isUnnamedBitfield())
6670       continue;
6671 
6672     LValue Subobject = This;
6673 
6674     bool HaveInit = ElementNo < E->getNumInits();
6675 
6676     // FIXME: Diagnostics here should point to the end of the initializer
6677     // list, not the start.
6678     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6679                             Subobject, Field, &Layout))
6680       return false;
6681 
6682     // Perform an implicit value-initialization for members beyond the end of
6683     // the initializer list.
6684     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6685     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6686 
6687     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6688     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6689                                   isa<CXXDefaultInitExpr>(Init));
6690 
6691     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6692     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6693         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6694                                                        FieldVal, Field))) {
6695       if (!Info.noteFailure())
6696         return false;
6697       Success = false;
6698     }
6699   }
6700 
6701   return Success;
6702 }
6703 
6704 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6705                                                 QualType T) {
6706   // Note that E's type is not necessarily the type of our class here; we might
6707   // be initializing an array element instead.
6708   const CXXConstructorDecl *FD = E->getConstructor();
6709   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6710 
6711   bool ZeroInit = E->requiresZeroInitialization();
6712   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6713     // If we've already performed zero-initialization, we're already done.
6714     if (!Result.isUninit())
6715       return true;
6716 
6717     // We can get here in two different ways:
6718     //  1) We're performing value-initialization, and should zero-initialize
6719     //     the object, or
6720     //  2) We're performing default-initialization of an object with a trivial
6721     //     constexpr default constructor, in which case we should start the
6722     //     lifetimes of all the base subobjects (there can be no data member
6723     //     subobjects in this case) per [basic.life]p1.
6724     // Either way, ZeroInitialization is appropriate.
6725     return ZeroInitialization(E, T);
6726   }
6727 
6728   const FunctionDecl *Definition = nullptr;
6729   auto Body = FD->getBody(Definition);
6730 
6731   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6732     return false;
6733 
6734   // Avoid materializing a temporary for an elidable copy/move constructor.
6735   if (E->isElidable() && !ZeroInit)
6736     if (const MaterializeTemporaryExpr *ME
6737           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6738       return Visit(ME->GetTemporaryExpr());
6739 
6740   if (ZeroInit && !ZeroInitialization(E, T))
6741     return false;
6742 
6743   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6744   return HandleConstructorCall(E, This, Args,
6745                                cast<CXXConstructorDecl>(Definition), Info,
6746                                Result);
6747 }
6748 
6749 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6750     const CXXInheritedCtorInitExpr *E) {
6751   if (!Info.CurrentCall) {
6752     assert(Info.checkingPotentialConstantExpression());
6753     return false;
6754   }
6755 
6756   const CXXConstructorDecl *FD = E->getConstructor();
6757   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6758     return false;
6759 
6760   const FunctionDecl *Definition = nullptr;
6761   auto Body = FD->getBody(Definition);
6762 
6763   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6764     return false;
6765 
6766   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6767                                cast<CXXConstructorDecl>(Definition), Info,
6768                                Result);
6769 }
6770 
6771 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6772     const CXXStdInitializerListExpr *E) {
6773   const ConstantArrayType *ArrayType =
6774       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6775 
6776   LValue Array;
6777   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6778     return false;
6779 
6780   // Get a pointer to the first element of the array.
6781   Array.addArray(Info, E, ArrayType);
6782 
6783   // FIXME: Perform the checks on the field types in SemaInit.
6784   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6785   RecordDecl::field_iterator Field = Record->field_begin();
6786   if (Field == Record->field_end())
6787     return Error(E);
6788 
6789   // Start pointer.
6790   if (!Field->getType()->isPointerType() ||
6791       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6792                             ArrayType->getElementType()))
6793     return Error(E);
6794 
6795   // FIXME: What if the initializer_list type has base classes, etc?
6796   Result = APValue(APValue::UninitStruct(), 0, 2);
6797   Array.moveInto(Result.getStructField(0));
6798 
6799   if (++Field == Record->field_end())
6800     return Error(E);
6801 
6802   if (Field->getType()->isPointerType() &&
6803       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6804                            ArrayType->getElementType())) {
6805     // End pointer.
6806     if (!HandleLValueArrayAdjustment(Info, E, Array,
6807                                      ArrayType->getElementType(),
6808                                      ArrayType->getSize().getZExtValue()))
6809       return false;
6810     Array.moveInto(Result.getStructField(1));
6811   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6812     // Length.
6813     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6814   else
6815     return Error(E);
6816 
6817   if (++Field != Record->field_end())
6818     return Error(E);
6819 
6820   return true;
6821 }
6822 
6823 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6824   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6825   if (ClosureClass->isInvalidDecl()) return false;
6826 
6827   if (Info.checkingPotentialConstantExpression()) return true;
6828 
6829   const size_t NumFields =
6830       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6831 
6832   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6833                                             E->capture_init_end()) &&
6834          "The number of lambda capture initializers should equal the number of "
6835          "fields within the closure type");
6836 
6837   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6838   // Iterate through all the lambda's closure object's fields and initialize
6839   // them.
6840   auto *CaptureInitIt = E->capture_init_begin();
6841   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6842   bool Success = true;
6843   for (const auto *Field : ClosureClass->fields()) {
6844     assert(CaptureInitIt != E->capture_init_end());
6845     // Get the initializer for this field
6846     Expr *const CurFieldInit = *CaptureInitIt++;
6847 
6848     // If there is no initializer, either this is a VLA or an error has
6849     // occurred.
6850     if (!CurFieldInit)
6851       return Error(E);
6852 
6853     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6854     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6855       if (!Info.keepEvaluatingAfterFailure())
6856         return false;
6857       Success = false;
6858     }
6859     ++CaptureIt;
6860   }
6861   return Success;
6862 }
6863 
6864 static bool EvaluateRecord(const Expr *E, const LValue &This,
6865                            APValue &Result, EvalInfo &Info) {
6866   assert(E->isRValue() && E->getType()->isRecordType() &&
6867          "can't evaluate expression as a record rvalue");
6868   return RecordExprEvaluator(Info, This, Result).Visit(E);
6869 }
6870 
6871 //===----------------------------------------------------------------------===//
6872 // Temporary Evaluation
6873 //
6874 // Temporaries are represented in the AST as rvalues, but generally behave like
6875 // lvalues. The full-object of which the temporary is a subobject is implicitly
6876 // materialized so that a reference can bind to it.
6877 //===----------------------------------------------------------------------===//
6878 namespace {
6879 class TemporaryExprEvaluator
6880   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6881 public:
6882   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6883     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6884 
6885   /// Visit an expression which constructs the value of this temporary.
6886   bool VisitConstructExpr(const Expr *E) {
6887     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6888     return EvaluateInPlace(Value, Info, Result, E);
6889   }
6890 
6891   bool VisitCastExpr(const CastExpr *E) {
6892     switch (E->getCastKind()) {
6893     default:
6894       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6895 
6896     case CK_ConstructorConversion:
6897       return VisitConstructExpr(E->getSubExpr());
6898     }
6899   }
6900   bool VisitInitListExpr(const InitListExpr *E) {
6901     return VisitConstructExpr(E);
6902   }
6903   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6904     return VisitConstructExpr(E);
6905   }
6906   bool VisitCallExpr(const CallExpr *E) {
6907     return VisitConstructExpr(E);
6908   }
6909   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6910     return VisitConstructExpr(E);
6911   }
6912   bool VisitLambdaExpr(const LambdaExpr *E) {
6913     return VisitConstructExpr(E);
6914   }
6915 };
6916 } // end anonymous namespace
6917 
6918 /// Evaluate an expression of record type as a temporary.
6919 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6920   assert(E->isRValue() && E->getType()->isRecordType());
6921   return TemporaryExprEvaluator(Info, Result).Visit(E);
6922 }
6923 
6924 //===----------------------------------------------------------------------===//
6925 // Vector Evaluation
6926 //===----------------------------------------------------------------------===//
6927 
6928 namespace {
6929   class VectorExprEvaluator
6930   : public ExprEvaluatorBase<VectorExprEvaluator> {
6931     APValue &Result;
6932   public:
6933 
6934     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6935       : ExprEvaluatorBaseTy(info), Result(Result) {}
6936 
6937     bool Success(ArrayRef<APValue> V, const Expr *E) {
6938       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6939       // FIXME: remove this APValue copy.
6940       Result = APValue(V.data(), V.size());
6941       return true;
6942     }
6943     bool Success(const APValue &V, const Expr *E) {
6944       assert(V.isVector());
6945       Result = V;
6946       return true;
6947     }
6948     bool ZeroInitialization(const Expr *E);
6949 
6950     bool VisitUnaryReal(const UnaryOperator *E)
6951       { return Visit(E->getSubExpr()); }
6952     bool VisitCastExpr(const CastExpr* E);
6953     bool VisitInitListExpr(const InitListExpr *E);
6954     bool VisitUnaryImag(const UnaryOperator *E);
6955     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6956     //                 binary comparisons, binary and/or/xor,
6957     //                 shufflevector, ExtVectorElementExpr
6958   };
6959 } // end anonymous namespace
6960 
6961 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6962   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6963   return VectorExprEvaluator(Info, Result).Visit(E);
6964 }
6965 
6966 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6967   const VectorType *VTy = E->getType()->castAs<VectorType>();
6968   unsigned NElts = VTy->getNumElements();
6969 
6970   const Expr *SE = E->getSubExpr();
6971   QualType SETy = SE->getType();
6972 
6973   switch (E->getCastKind()) {
6974   case CK_VectorSplat: {
6975     APValue Val = APValue();
6976     if (SETy->isIntegerType()) {
6977       APSInt IntResult;
6978       if (!EvaluateInteger(SE, IntResult, Info))
6979         return false;
6980       Val = APValue(std::move(IntResult));
6981     } else if (SETy->isRealFloatingType()) {
6982       APFloat FloatResult(0.0);
6983       if (!EvaluateFloat(SE, FloatResult, Info))
6984         return false;
6985       Val = APValue(std::move(FloatResult));
6986     } else {
6987       return Error(E);
6988     }
6989 
6990     // Splat and create vector APValue.
6991     SmallVector<APValue, 4> Elts(NElts, Val);
6992     return Success(Elts, E);
6993   }
6994   case CK_BitCast: {
6995     // Evaluate the operand into an APInt we can extract from.
6996     llvm::APInt SValInt;
6997     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6998       return false;
6999     // Extract the elements
7000     QualType EltTy = VTy->getElementType();
7001     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7002     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7003     SmallVector<APValue, 4> Elts;
7004     if (EltTy->isRealFloatingType()) {
7005       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7006       unsigned FloatEltSize = EltSize;
7007       if (&Sem == &APFloat::x87DoubleExtended())
7008         FloatEltSize = 80;
7009       for (unsigned i = 0; i < NElts; i++) {
7010         llvm::APInt Elt;
7011         if (BigEndian)
7012           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7013         else
7014           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7015         Elts.push_back(APValue(APFloat(Sem, Elt)));
7016       }
7017     } else if (EltTy->isIntegerType()) {
7018       for (unsigned i = 0; i < NElts; i++) {
7019         llvm::APInt Elt;
7020         if (BigEndian)
7021           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7022         else
7023           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7024         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7025       }
7026     } else {
7027       return Error(E);
7028     }
7029     return Success(Elts, E);
7030   }
7031   default:
7032     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7033   }
7034 }
7035 
7036 bool
7037 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7038   const VectorType *VT = E->getType()->castAs<VectorType>();
7039   unsigned NumInits = E->getNumInits();
7040   unsigned NumElements = VT->getNumElements();
7041 
7042   QualType EltTy = VT->getElementType();
7043   SmallVector<APValue, 4> Elements;
7044 
7045   // The number of initializers can be less than the number of
7046   // vector elements. For OpenCL, this can be due to nested vector
7047   // initialization. For GCC compatibility, missing trailing elements
7048   // should be initialized with zeroes.
7049   unsigned CountInits = 0, CountElts = 0;
7050   while (CountElts < NumElements) {
7051     // Handle nested vector initialization.
7052     if (CountInits < NumInits
7053         && E->getInit(CountInits)->getType()->isVectorType()) {
7054       APValue v;
7055       if (!EvaluateVector(E->getInit(CountInits), v, Info))
7056         return Error(E);
7057       unsigned vlen = v.getVectorLength();
7058       for (unsigned j = 0; j < vlen; j++)
7059         Elements.push_back(v.getVectorElt(j));
7060       CountElts += vlen;
7061     } else if (EltTy->isIntegerType()) {
7062       llvm::APSInt sInt(32);
7063       if (CountInits < NumInits) {
7064         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7065           return false;
7066       } else // trailing integer zero.
7067         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7068       Elements.push_back(APValue(sInt));
7069       CountElts++;
7070     } else {
7071       llvm::APFloat f(0.0);
7072       if (CountInits < NumInits) {
7073         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7074           return false;
7075       } else // trailing float zero.
7076         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7077       Elements.push_back(APValue(f));
7078       CountElts++;
7079     }
7080     CountInits++;
7081   }
7082   return Success(Elements, E);
7083 }
7084 
7085 bool
7086 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7087   const VectorType *VT = E->getType()->getAs<VectorType>();
7088   QualType EltTy = VT->getElementType();
7089   APValue ZeroElement;
7090   if (EltTy->isIntegerType())
7091     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7092   else
7093     ZeroElement =
7094         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7095 
7096   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7097   return Success(Elements, E);
7098 }
7099 
7100 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7101   VisitIgnoredValue(E->getSubExpr());
7102   return ZeroInitialization(E);
7103 }
7104 
7105 //===----------------------------------------------------------------------===//
7106 // Array Evaluation
7107 //===----------------------------------------------------------------------===//
7108 
7109 namespace {
7110   class ArrayExprEvaluator
7111   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7112     const LValue &This;
7113     APValue &Result;
7114   public:
7115 
7116     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7117       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7118 
7119     bool Success(const APValue &V, const Expr *E) {
7120       assert((V.isArray() || V.isLValue()) &&
7121              "expected array or string literal");
7122       Result = V;
7123       return true;
7124     }
7125 
7126     bool ZeroInitialization(const Expr *E) {
7127       const ConstantArrayType *CAT =
7128           Info.Ctx.getAsConstantArrayType(E->getType());
7129       if (!CAT)
7130         return Error(E);
7131 
7132       Result = APValue(APValue::UninitArray(), 0,
7133                        CAT->getSize().getZExtValue());
7134       if (!Result.hasArrayFiller()) return true;
7135 
7136       // Zero-initialize all elements.
7137       LValue Subobject = This;
7138       Subobject.addArray(Info, E, CAT);
7139       ImplicitValueInitExpr VIE(CAT->getElementType());
7140       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7141     }
7142 
7143     bool VisitCallExpr(const CallExpr *E) {
7144       return handleCallExpr(E, Result, &This);
7145     }
7146     bool VisitInitListExpr(const InitListExpr *E);
7147     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7148     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7149     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7150                                const LValue &Subobject,
7151                                APValue *Value, QualType Type);
7152   };
7153 } // end anonymous namespace
7154 
7155 static bool EvaluateArray(const Expr *E, const LValue &This,
7156                           APValue &Result, EvalInfo &Info) {
7157   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7158   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7159 }
7160 
7161 // Return true iff the given array filler may depend on the element index.
7162 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7163   // For now, just whitelist non-class value-initialization and initialization
7164   // lists comprised of them.
7165   if (isa<ImplicitValueInitExpr>(FillerExpr))
7166     return false;
7167   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7168     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7169       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7170         return true;
7171     }
7172     return false;
7173   }
7174   return true;
7175 }
7176 
7177 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7178   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7179   if (!CAT)
7180     return Error(E);
7181 
7182   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7183   // an appropriately-typed string literal enclosed in braces.
7184   if (E->isStringLiteralInit()) {
7185     LValue LV;
7186     if (!EvaluateLValue(E->getInit(0), LV, Info))
7187       return false;
7188     APValue Val;
7189     LV.moveInto(Val);
7190     return Success(Val, E);
7191   }
7192 
7193   bool Success = true;
7194 
7195   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7196          "zero-initialized array shouldn't have any initialized elts");
7197   APValue Filler;
7198   if (Result.isArray() && Result.hasArrayFiller())
7199     Filler = Result.getArrayFiller();
7200 
7201   unsigned NumEltsToInit = E->getNumInits();
7202   unsigned NumElts = CAT->getSize().getZExtValue();
7203   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7204 
7205   // If the initializer might depend on the array index, run it for each
7206   // array element.
7207   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7208     NumEltsToInit = NumElts;
7209 
7210   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7211                           << NumEltsToInit << ".\n");
7212 
7213   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7214 
7215   // If the array was previously zero-initialized, preserve the
7216   // zero-initialized values.
7217   if (!Filler.isUninit()) {
7218     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7219       Result.getArrayInitializedElt(I) = Filler;
7220     if (Result.hasArrayFiller())
7221       Result.getArrayFiller() = Filler;
7222   }
7223 
7224   LValue Subobject = This;
7225   Subobject.addArray(Info, E, CAT);
7226   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7227     const Expr *Init =
7228         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7229     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7230                          Info, Subobject, Init) ||
7231         !HandleLValueArrayAdjustment(Info, Init, Subobject,
7232                                      CAT->getElementType(), 1)) {
7233       if (!Info.noteFailure())
7234         return false;
7235       Success = false;
7236     }
7237   }
7238 
7239   if (!Result.hasArrayFiller())
7240     return Success;
7241 
7242   // If we get here, we have a trivial filler, which we can just evaluate
7243   // once and splat over the rest of the array elements.
7244   assert(FillerExpr && "no array filler for incomplete init list");
7245   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7246                          FillerExpr) && Success;
7247 }
7248 
7249 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7250   if (E->getCommonExpr() &&
7251       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7252                 Info, E->getCommonExpr()->getSourceExpr()))
7253     return false;
7254 
7255   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7256 
7257   uint64_t Elements = CAT->getSize().getZExtValue();
7258   Result = APValue(APValue::UninitArray(), Elements, Elements);
7259 
7260   LValue Subobject = This;
7261   Subobject.addArray(Info, E, CAT);
7262 
7263   bool Success = true;
7264   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7265     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7266                          Info, Subobject, E->getSubExpr()) ||
7267         !HandleLValueArrayAdjustment(Info, E, Subobject,
7268                                      CAT->getElementType(), 1)) {
7269       if (!Info.noteFailure())
7270         return false;
7271       Success = false;
7272     }
7273   }
7274 
7275   return Success;
7276 }
7277 
7278 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7279   return VisitCXXConstructExpr(E, This, &Result, E->getType());
7280 }
7281 
7282 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7283                                                const LValue &Subobject,
7284                                                APValue *Value,
7285                                                QualType Type) {
7286   bool HadZeroInit = !Value->isUninit();
7287 
7288   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7289     unsigned N = CAT->getSize().getZExtValue();
7290 
7291     // Preserve the array filler if we had prior zero-initialization.
7292     APValue Filler =
7293       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7294                                              : APValue();
7295 
7296     *Value = APValue(APValue::UninitArray(), N, N);
7297 
7298     if (HadZeroInit)
7299       for (unsigned I = 0; I != N; ++I)
7300         Value->getArrayInitializedElt(I) = Filler;
7301 
7302     // Initialize the elements.
7303     LValue ArrayElt = Subobject;
7304     ArrayElt.addArray(Info, E, CAT);
7305     for (unsigned I = 0; I != N; ++I)
7306       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7307                                  CAT->getElementType()) ||
7308           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7309                                        CAT->getElementType(), 1))
7310         return false;
7311 
7312     return true;
7313   }
7314 
7315   if (!Type->isRecordType())
7316     return Error(E);
7317 
7318   return RecordExprEvaluator(Info, Subobject, *Value)
7319              .VisitCXXConstructExpr(E, Type);
7320 }
7321 
7322 //===----------------------------------------------------------------------===//
7323 // Integer Evaluation
7324 //
7325 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7326 // types and back in constant folding. Integer values are thus represented
7327 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7328 //===----------------------------------------------------------------------===//
7329 
7330 namespace {
7331 class IntExprEvaluator
7332         : public ExprEvaluatorBase<IntExprEvaluator> {
7333   APValue &Result;
7334 public:
7335   IntExprEvaluator(EvalInfo &info, APValue &result)
7336       : ExprEvaluatorBaseTy(info), Result(result) {}
7337 
7338   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7339     assert(E->getType()->isIntegralOrEnumerationType() &&
7340            "Invalid evaluation result.");
7341     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7342            "Invalid evaluation result.");
7343     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7344            "Invalid evaluation result.");
7345     Result = APValue(SI);
7346     return true;
7347   }
7348   bool Success(const llvm::APSInt &SI, const Expr *E) {
7349     return Success(SI, E, Result);
7350   }
7351 
7352   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7353     assert(E->getType()->isIntegralOrEnumerationType() &&
7354            "Invalid evaluation result.");
7355     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7356            "Invalid evaluation result.");
7357     Result = APValue(APSInt(I));
7358     Result.getInt().setIsUnsigned(
7359                             E->getType()->isUnsignedIntegerOrEnumerationType());
7360     return true;
7361   }
7362   bool Success(const llvm::APInt &I, const Expr *E) {
7363     return Success(I, E, Result);
7364   }
7365 
7366   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7367     assert(E->getType()->isIntegralOrEnumerationType() &&
7368            "Invalid evaluation result.");
7369     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7370     return true;
7371   }
7372   bool Success(uint64_t Value, const Expr *E) {
7373     return Success(Value, E, Result);
7374   }
7375 
7376   bool Success(CharUnits Size, const Expr *E) {
7377     return Success(Size.getQuantity(), E);
7378   }
7379 
7380   bool Success(const APValue &V, const Expr *E) {
7381     if (V.isLValue() || V.isAddrLabelDiff()) {
7382       Result = V;
7383       return true;
7384     }
7385     return Success(V.getInt(), E);
7386   }
7387 
7388   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7389 
7390   //===--------------------------------------------------------------------===//
7391   //                            Visitor Methods
7392   //===--------------------------------------------------------------------===//
7393 
7394   bool VisitConstantExpr(const ConstantExpr *E);
7395 
7396   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7397     return Success(E->getValue(), E);
7398   }
7399   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7400     return Success(E->getValue(), E);
7401   }
7402 
7403   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7404   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7405     if (CheckReferencedDecl(E, E->getDecl()))
7406       return true;
7407 
7408     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7409   }
7410   bool VisitMemberExpr(const MemberExpr *E) {
7411     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7412       VisitIgnoredBaseExpression(E->getBase());
7413       return true;
7414     }
7415 
7416     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7417   }
7418 
7419   bool VisitCallExpr(const CallExpr *E);
7420   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7421   bool VisitBinaryOperator(const BinaryOperator *E);
7422   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7423   bool VisitUnaryOperator(const UnaryOperator *E);
7424 
7425   bool VisitCastExpr(const CastExpr* E);
7426   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7427 
7428   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7429     return Success(E->getValue(), E);
7430   }
7431 
7432   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7433     return Success(E->getValue(), E);
7434   }
7435 
7436   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7437     if (Info.ArrayInitIndex == uint64_t(-1)) {
7438       // We were asked to evaluate this subexpression independent of the
7439       // enclosing ArrayInitLoopExpr. We can't do that.
7440       Info.FFDiag(E);
7441       return false;
7442     }
7443     return Success(Info.ArrayInitIndex, E);
7444   }
7445 
7446   // Note, GNU defines __null as an integer, not a pointer.
7447   bool VisitGNUNullExpr(const GNUNullExpr *E) {
7448     return ZeroInitialization(E);
7449   }
7450 
7451   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7452     return Success(E->getValue(), E);
7453   }
7454 
7455   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7456     return Success(E->getValue(), E);
7457   }
7458 
7459   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7460     return Success(E->getValue(), E);
7461   }
7462 
7463   bool VisitUnaryReal(const UnaryOperator *E);
7464   bool VisitUnaryImag(const UnaryOperator *E);
7465 
7466   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7467   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7468 
7469   // FIXME: Missing: array subscript of vector, member of vector
7470 };
7471 
7472 class FixedPointExprEvaluator
7473     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7474   APValue &Result;
7475 
7476  public:
7477   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7478       : ExprEvaluatorBaseTy(info), Result(result) {}
7479 
7480   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7481     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7482     assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7483            "Invalid evaluation result.");
7484     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7485            "Invalid evaluation result.");
7486     Result = APValue(SI);
7487     return true;
7488   }
7489   bool Success(const llvm::APSInt &SI, const Expr *E) {
7490     return Success(SI, E, Result);
7491   }
7492 
7493   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7494     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7495     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7496            "Invalid evaluation result.");
7497     Result = APValue(APSInt(I));
7498     Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7499     return true;
7500   }
7501   bool Success(const llvm::APInt &I, const Expr *E) {
7502     return Success(I, E, Result);
7503   }
7504 
7505   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7506     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7507     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7508     return true;
7509   }
7510   bool Success(uint64_t Value, const Expr *E) {
7511     return Success(Value, E, Result);
7512   }
7513 
7514   bool Success(CharUnits Size, const Expr *E) {
7515     return Success(Size.getQuantity(), E);
7516   }
7517 
7518   bool Success(const APValue &V, const Expr *E) {
7519     if (V.isLValue() || V.isAddrLabelDiff()) {
7520       Result = V;
7521       return true;
7522     }
7523     return Success(V.getInt(), E);
7524   }
7525 
7526   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7527 
7528   //===--------------------------------------------------------------------===//
7529   //                            Visitor Methods
7530   //===--------------------------------------------------------------------===//
7531 
7532   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7533     return Success(E->getValue(), E);
7534   }
7535 
7536   bool VisitUnaryOperator(const UnaryOperator *E);
7537 };
7538 } // end anonymous namespace
7539 
7540 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7541 /// produce either the integer value or a pointer.
7542 ///
7543 /// GCC has a heinous extension which folds casts between pointer types and
7544 /// pointer-sized integral types. We support this by allowing the evaluation of
7545 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7546 /// Some simple arithmetic on such values is supported (they are treated much
7547 /// like char*).
7548 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7549                                     EvalInfo &Info) {
7550   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7551   return IntExprEvaluator(Info, Result).Visit(E);
7552 }
7553 
7554 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7555   APValue Val;
7556   if (!EvaluateIntegerOrLValue(E, Val, Info))
7557     return false;
7558   if (!Val.isInt()) {
7559     // FIXME: It would be better to produce the diagnostic for casting
7560     //        a pointer to an integer.
7561     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7562     return false;
7563   }
7564   Result = Val.getInt();
7565   return true;
7566 }
7567 
7568 /// Check whether the given declaration can be directly converted to an integral
7569 /// rvalue. If not, no diagnostic is produced; there are other things we can
7570 /// try.
7571 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7572   // Enums are integer constant exprs.
7573   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7574     // Check for signedness/width mismatches between E type and ECD value.
7575     bool SameSign = (ECD->getInitVal().isSigned()
7576                      == E->getType()->isSignedIntegerOrEnumerationType());
7577     bool SameWidth = (ECD->getInitVal().getBitWidth()
7578                       == Info.Ctx.getIntWidth(E->getType()));
7579     if (SameSign && SameWidth)
7580       return Success(ECD->getInitVal(), E);
7581     else {
7582       // Get rid of mismatch (otherwise Success assertions will fail)
7583       // by computing a new value matching the type of E.
7584       llvm::APSInt Val = ECD->getInitVal();
7585       if (!SameSign)
7586         Val.setIsSigned(!ECD->getInitVal().isSigned());
7587       if (!SameWidth)
7588         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7589       return Success(Val, E);
7590     }
7591   }
7592   return false;
7593 }
7594 
7595 /// Values returned by __builtin_classify_type, chosen to match the values
7596 /// produced by GCC's builtin.
7597 enum class GCCTypeClass {
7598   None = -1,
7599   Void = 0,
7600   Integer = 1,
7601   // GCC reserves 2 for character types, but instead classifies them as
7602   // integers.
7603   Enum = 3,
7604   Bool = 4,
7605   Pointer = 5,
7606   // GCC reserves 6 for references, but appears to never use it (because
7607   // expressions never have reference type, presumably).
7608   PointerToDataMember = 7,
7609   RealFloat = 8,
7610   Complex = 9,
7611   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7612   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7613   // GCC claims to reserve 11 for pointers to member functions, but *actually*
7614   // uses 12 for that purpose, same as for a class or struct. Maybe it
7615   // internally implements a pointer to member as a struct?  Who knows.
7616   PointerToMemberFunction = 12, // Not a bug, see above.
7617   ClassOrStruct = 12,
7618   Union = 13,
7619   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7620   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7621   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7622   // literals.
7623 };
7624 
7625 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7626 /// as GCC.
7627 static GCCTypeClass
7628 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7629   assert(!T->isDependentType() && "unexpected dependent type");
7630 
7631   QualType CanTy = T.getCanonicalType();
7632   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7633 
7634   switch (CanTy->getTypeClass()) {
7635 #define TYPE(ID, BASE)
7636 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7637 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7638 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7639 #include "clang/AST/TypeNodes.def"
7640   case Type::Auto:
7641   case Type::DeducedTemplateSpecialization:
7642       llvm_unreachable("unexpected non-canonical or dependent type");
7643 
7644   case Type::Builtin:
7645     switch (BT->getKind()) {
7646 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7647 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7648     case BuiltinType::ID: return GCCTypeClass::Integer;
7649 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7650     case BuiltinType::ID: return GCCTypeClass::RealFloat;
7651 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7652     case BuiltinType::ID: break;
7653 #include "clang/AST/BuiltinTypes.def"
7654     case BuiltinType::Void:
7655       return GCCTypeClass::Void;
7656 
7657     case BuiltinType::Bool:
7658       return GCCTypeClass::Bool;
7659 
7660     case BuiltinType::Char_U:
7661     case BuiltinType::UChar:
7662     case BuiltinType::WChar_U:
7663     case BuiltinType::Char8:
7664     case BuiltinType::Char16:
7665     case BuiltinType::Char32:
7666     case BuiltinType::UShort:
7667     case BuiltinType::UInt:
7668     case BuiltinType::ULong:
7669     case BuiltinType::ULongLong:
7670     case BuiltinType::UInt128:
7671       return GCCTypeClass::Integer;
7672 
7673     case BuiltinType::UShortAccum:
7674     case BuiltinType::UAccum:
7675     case BuiltinType::ULongAccum:
7676     case BuiltinType::UShortFract:
7677     case BuiltinType::UFract:
7678     case BuiltinType::ULongFract:
7679     case BuiltinType::SatUShortAccum:
7680     case BuiltinType::SatUAccum:
7681     case BuiltinType::SatULongAccum:
7682     case BuiltinType::SatUShortFract:
7683     case BuiltinType::SatUFract:
7684     case BuiltinType::SatULongFract:
7685       return GCCTypeClass::None;
7686 
7687     case BuiltinType::NullPtr:
7688 
7689     case BuiltinType::ObjCId:
7690     case BuiltinType::ObjCClass:
7691     case BuiltinType::ObjCSel:
7692 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7693     case BuiltinType::Id:
7694 #include "clang/Basic/OpenCLImageTypes.def"
7695 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7696     case BuiltinType::Id:
7697 #include "clang/Basic/OpenCLExtensionTypes.def"
7698     case BuiltinType::OCLSampler:
7699     case BuiltinType::OCLEvent:
7700     case BuiltinType::OCLClkEvent:
7701     case BuiltinType::OCLQueue:
7702     case BuiltinType::OCLReserveID:
7703       return GCCTypeClass::None;
7704 
7705     case BuiltinType::Dependent:
7706       llvm_unreachable("unexpected dependent type");
7707     };
7708     llvm_unreachable("unexpected placeholder type");
7709 
7710   case Type::Enum:
7711     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7712 
7713   case Type::Pointer:
7714   case Type::ConstantArray:
7715   case Type::VariableArray:
7716   case Type::IncompleteArray:
7717   case Type::FunctionNoProto:
7718   case Type::FunctionProto:
7719     return GCCTypeClass::Pointer;
7720 
7721   case Type::MemberPointer:
7722     return CanTy->isMemberDataPointerType()
7723                ? GCCTypeClass::PointerToDataMember
7724                : GCCTypeClass::PointerToMemberFunction;
7725 
7726   case Type::Complex:
7727     return GCCTypeClass::Complex;
7728 
7729   case Type::Record:
7730     return CanTy->isUnionType() ? GCCTypeClass::Union
7731                                 : GCCTypeClass::ClassOrStruct;
7732 
7733   case Type::Atomic:
7734     // GCC classifies _Atomic T the same as T.
7735     return EvaluateBuiltinClassifyType(
7736         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7737 
7738   case Type::BlockPointer:
7739   case Type::Vector:
7740   case Type::ExtVector:
7741   case Type::ObjCObject:
7742   case Type::ObjCInterface:
7743   case Type::ObjCObjectPointer:
7744   case Type::Pipe:
7745     // GCC classifies vectors as None. We follow its lead and classify all
7746     // other types that don't fit into the regular classification the same way.
7747     return GCCTypeClass::None;
7748 
7749   case Type::LValueReference:
7750   case Type::RValueReference:
7751     llvm_unreachable("invalid type for expression");
7752   }
7753 
7754   llvm_unreachable("unexpected type class");
7755 }
7756 
7757 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7758 /// as GCC.
7759 static GCCTypeClass
7760 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7761   // If no argument was supplied, default to None. This isn't
7762   // ideal, however it is what gcc does.
7763   if (E->getNumArgs() == 0)
7764     return GCCTypeClass::None;
7765 
7766   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7767   // being an ICE, but still folds it to a constant using the type of the first
7768   // argument.
7769   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7770 }
7771 
7772 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7773 /// __builtin_constant_p when applied to the given lvalue.
7774 ///
7775 /// An lvalue is only "constant" if it is a pointer or reference to the first
7776 /// character of a string literal.
7777 template<typename LValue>
7778 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7779   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7780   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7781 }
7782 
7783 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7784 /// GCC as we can manage.
7785 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7786   QualType ArgType = Arg->getType();
7787 
7788   // __builtin_constant_p always has one operand. The rules which gcc follows
7789   // are not precisely documented, but are as follows:
7790   //
7791   //  - If the operand is of integral, floating, complex or enumeration type,
7792   //    and can be folded to a known value of that type, it returns 1.
7793   //  - If the operand and can be folded to a pointer to the first character
7794   //    of a string literal (or such a pointer cast to an integral type), it
7795   //    returns 1.
7796   //
7797   // Otherwise, it returns 0.
7798   //
7799   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7800   // its support for this does not currently work.
7801   if (ArgType->isIntegralOrEnumerationType()) {
7802     Expr::EvalResult Result;
7803     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7804       return false;
7805 
7806     APValue &V = Result.Val;
7807     if (V.getKind() == APValue::Int)
7808       return true;
7809     if (V.getKind() == APValue::LValue)
7810       return EvaluateBuiltinConstantPForLValue(V);
7811   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7812     return Arg->isEvaluatable(Ctx);
7813   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7814     LValue LV;
7815     Expr::EvalStatus Status;
7816     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7817     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7818                           : EvaluatePointer(Arg, LV, Info)) &&
7819         !Status.HasSideEffects)
7820       return EvaluateBuiltinConstantPForLValue(LV);
7821   }
7822 
7823   // Anything else isn't considered to be sufficiently constant.
7824   return false;
7825 }
7826 
7827 /// Retrieves the "underlying object type" of the given expression,
7828 /// as used by __builtin_object_size.
7829 static QualType getObjectType(APValue::LValueBase B) {
7830   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7831     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7832       return VD->getType();
7833   } else if (const Expr *E = B.get<const Expr*>()) {
7834     if (isa<CompoundLiteralExpr>(E))
7835       return E->getType();
7836   }
7837 
7838   return QualType();
7839 }
7840 
7841 /// A more selective version of E->IgnoreParenCasts for
7842 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7843 /// to change the type of E.
7844 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7845 ///
7846 /// Always returns an RValue with a pointer representation.
7847 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7848   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7849 
7850   auto *NoParens = E->IgnoreParens();
7851   auto *Cast = dyn_cast<CastExpr>(NoParens);
7852   if (Cast == nullptr)
7853     return NoParens;
7854 
7855   // We only conservatively allow a few kinds of casts, because this code is
7856   // inherently a simple solution that seeks to support the common case.
7857   auto CastKind = Cast->getCastKind();
7858   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7859       CastKind != CK_AddressSpaceConversion)
7860     return NoParens;
7861 
7862   auto *SubExpr = Cast->getSubExpr();
7863   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7864     return NoParens;
7865   return ignorePointerCastsAndParens(SubExpr);
7866 }
7867 
7868 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7869 /// record layout. e.g.
7870 ///   struct { struct { int a, b; } fst, snd; } obj;
7871 ///   obj.fst   // no
7872 ///   obj.snd   // yes
7873 ///   obj.fst.a // no
7874 ///   obj.fst.b // no
7875 ///   obj.snd.a // no
7876 ///   obj.snd.b // yes
7877 ///
7878 /// Please note: this function is specialized for how __builtin_object_size
7879 /// views "objects".
7880 ///
7881 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7882 /// correct result, it will always return true.
7883 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7884   assert(!LVal.Designator.Invalid);
7885 
7886   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7887     const RecordDecl *Parent = FD->getParent();
7888     Invalid = Parent->isInvalidDecl();
7889     if (Invalid || Parent->isUnion())
7890       return true;
7891     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7892     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7893   };
7894 
7895   auto &Base = LVal.getLValueBase();
7896   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7897     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7898       bool Invalid;
7899       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7900         return Invalid;
7901     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7902       for (auto *FD : IFD->chain()) {
7903         bool Invalid;
7904         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7905           return Invalid;
7906       }
7907     }
7908   }
7909 
7910   unsigned I = 0;
7911   QualType BaseType = getType(Base);
7912   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7913     // If we don't know the array bound, conservatively assume we're looking at
7914     // the final array element.
7915     ++I;
7916     if (BaseType->isIncompleteArrayType())
7917       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7918     else
7919       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7920   }
7921 
7922   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7923     const auto &Entry = LVal.Designator.Entries[I];
7924     if (BaseType->isArrayType()) {
7925       // Because __builtin_object_size treats arrays as objects, we can ignore
7926       // the index iff this is the last array in the Designator.
7927       if (I + 1 == E)
7928         return true;
7929       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7930       uint64_t Index = Entry.ArrayIndex;
7931       if (Index + 1 != CAT->getSize())
7932         return false;
7933       BaseType = CAT->getElementType();
7934     } else if (BaseType->isAnyComplexType()) {
7935       const auto *CT = BaseType->castAs<ComplexType>();
7936       uint64_t Index = Entry.ArrayIndex;
7937       if (Index != 1)
7938         return false;
7939       BaseType = CT->getElementType();
7940     } else if (auto *FD = getAsField(Entry)) {
7941       bool Invalid;
7942       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7943         return Invalid;
7944       BaseType = FD->getType();
7945     } else {
7946       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7947       return false;
7948     }
7949   }
7950   return true;
7951 }
7952 
7953 /// Tests to see if the LValue has a user-specified designator (that isn't
7954 /// necessarily valid). Note that this always returns 'true' if the LValue has
7955 /// an unsized array as its first designator entry, because there's currently no
7956 /// way to tell if the user typed *foo or foo[0].
7957 static bool refersToCompleteObject(const LValue &LVal) {
7958   if (LVal.Designator.Invalid)
7959     return false;
7960 
7961   if (!LVal.Designator.Entries.empty())
7962     return LVal.Designator.isMostDerivedAnUnsizedArray();
7963 
7964   if (!LVal.InvalidBase)
7965     return true;
7966 
7967   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7968   // the LValueBase.
7969   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7970   return !E || !isa<MemberExpr>(E);
7971 }
7972 
7973 /// Attempts to detect a user writing into a piece of memory that's impossible
7974 /// to figure out the size of by just using types.
7975 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7976   const SubobjectDesignator &Designator = LVal.Designator;
7977   // Notes:
7978   // - Users can only write off of the end when we have an invalid base. Invalid
7979   //   bases imply we don't know where the memory came from.
7980   // - We used to be a bit more aggressive here; we'd only be conservative if
7981   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7982   //   broke some common standard library extensions (PR30346), but was
7983   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7984   //   with some sort of whitelist. OTOH, it seems that GCC is always
7985   //   conservative with the last element in structs (if it's an array), so our
7986   //   current behavior is more compatible than a whitelisting approach would
7987   //   be.
7988   return LVal.InvalidBase &&
7989          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7990          Designator.MostDerivedIsArrayElement &&
7991          isDesignatorAtObjectEnd(Ctx, LVal);
7992 }
7993 
7994 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7995 /// Fails if the conversion would cause loss of precision.
7996 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7997                                             CharUnits &Result) {
7998   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7999   if (Int.ugt(CharUnitsMax))
8000     return false;
8001   Result = CharUnits::fromQuantity(Int.getZExtValue());
8002   return true;
8003 }
8004 
8005 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8006 /// determine how many bytes exist from the beginning of the object to either
8007 /// the end of the current subobject, or the end of the object itself, depending
8008 /// on what the LValue looks like + the value of Type.
8009 ///
8010 /// If this returns false, the value of Result is undefined.
8011 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8012                                unsigned Type, const LValue &LVal,
8013                                CharUnits &EndOffset) {
8014   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8015 
8016   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8017     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8018       return false;
8019     return HandleSizeof(Info, ExprLoc, Ty, Result);
8020   };
8021 
8022   // We want to evaluate the size of the entire object. This is a valid fallback
8023   // for when Type=1 and the designator is invalid, because we're asked for an
8024   // upper-bound.
8025   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8026     // Type=3 wants a lower bound, so we can't fall back to this.
8027     if (Type == 3 && !DetermineForCompleteObject)
8028       return false;
8029 
8030     llvm::APInt APEndOffset;
8031     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8032         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8033       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8034 
8035     if (LVal.InvalidBase)
8036       return false;
8037 
8038     QualType BaseTy = getObjectType(LVal.getLValueBase());
8039     return CheckedHandleSizeof(BaseTy, EndOffset);
8040   }
8041 
8042   // We want to evaluate the size of a subobject.
8043   const SubobjectDesignator &Designator = LVal.Designator;
8044 
8045   // The following is a moderately common idiom in C:
8046   //
8047   // struct Foo { int a; char c[1]; };
8048   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8049   // strcpy(&F->c[0], Bar);
8050   //
8051   // In order to not break too much legacy code, we need to support it.
8052   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8053     // If we can resolve this to an alloc_size call, we can hand that back,
8054     // because we know for certain how many bytes there are to write to.
8055     llvm::APInt APEndOffset;
8056     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8057         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8058       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8059 
8060     // If we cannot determine the size of the initial allocation, then we can't
8061     // given an accurate upper-bound. However, we are still able to give
8062     // conservative lower-bounds for Type=3.
8063     if (Type == 1)
8064       return false;
8065   }
8066 
8067   CharUnits BytesPerElem;
8068   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8069     return false;
8070 
8071   // According to the GCC documentation, we want the size of the subobject
8072   // denoted by the pointer. But that's not quite right -- what we actually
8073   // want is the size of the immediately-enclosing array, if there is one.
8074   int64_t ElemsRemaining;
8075   if (Designator.MostDerivedIsArrayElement &&
8076       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8077     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8078     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8079     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8080   } else {
8081     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8082   }
8083 
8084   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8085   return true;
8086 }
8087 
8088 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8089 /// returns true and stores the result in @p Size.
8090 ///
8091 /// If @p WasError is non-null, this will report whether the failure to evaluate
8092 /// is to be treated as an Error in IntExprEvaluator.
8093 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8094                                          EvalInfo &Info, uint64_t &Size) {
8095   // Determine the denoted object.
8096   LValue LVal;
8097   {
8098     // The operand of __builtin_object_size is never evaluated for side-effects.
8099     // If there are any, but we can determine the pointed-to object anyway, then
8100     // ignore the side-effects.
8101     SpeculativeEvaluationRAII SpeculativeEval(Info);
8102     IgnoreSideEffectsRAII Fold(Info);
8103 
8104     if (E->isGLValue()) {
8105       // It's possible for us to be given GLValues if we're called via
8106       // Expr::tryEvaluateObjectSize.
8107       APValue RVal;
8108       if (!EvaluateAsRValue(Info, E, RVal))
8109         return false;
8110       LVal.setFrom(Info.Ctx, RVal);
8111     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8112                                 /*InvalidBaseOK=*/true))
8113       return false;
8114   }
8115 
8116   // If we point to before the start of the object, there are no accessible
8117   // bytes.
8118   if (LVal.getLValueOffset().isNegative()) {
8119     Size = 0;
8120     return true;
8121   }
8122 
8123   CharUnits EndOffset;
8124   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8125     return false;
8126 
8127   // If we've fallen outside of the end offset, just pretend there's nothing to
8128   // write to/read from.
8129   if (EndOffset <= LVal.getLValueOffset())
8130     Size = 0;
8131   else
8132     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8133   return true;
8134 }
8135 
8136 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8137   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8138   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8139 }
8140 
8141 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8142   if (unsigned BuiltinOp = E->getBuiltinCallee())
8143     return VisitBuiltinCallExpr(E, BuiltinOp);
8144 
8145   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8146 }
8147 
8148 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8149                                             unsigned BuiltinOp) {
8150   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8151   default:
8152     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8153 
8154   case Builtin::BI__builtin_object_size: {
8155     // The type was checked when we built the expression.
8156     unsigned Type =
8157         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8158     assert(Type <= 3 && "unexpected type");
8159 
8160     uint64_t Size;
8161     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8162       return Success(Size, E);
8163 
8164     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8165       return Success((Type & 2) ? 0 : -1, E);
8166 
8167     // Expression had no side effects, but we couldn't statically determine the
8168     // size of the referenced object.
8169     switch (Info.EvalMode) {
8170     case EvalInfo::EM_ConstantExpression:
8171     case EvalInfo::EM_PotentialConstantExpression:
8172     case EvalInfo::EM_ConstantFold:
8173     case EvalInfo::EM_EvaluateForOverflow:
8174     case EvalInfo::EM_IgnoreSideEffects:
8175       // Leave it to IR generation.
8176       return Error(E);
8177     case EvalInfo::EM_ConstantExpressionUnevaluated:
8178     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8179       // Reduce it to a constant now.
8180       return Success((Type & 2) ? 0 : -1, E);
8181     }
8182 
8183     llvm_unreachable("unexpected EvalMode");
8184   }
8185 
8186   case Builtin::BI__builtin_os_log_format_buffer_size: {
8187     analyze_os_log::OSLogBufferLayout Layout;
8188     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8189     return Success(Layout.size().getQuantity(), E);
8190   }
8191 
8192   case Builtin::BI__builtin_bswap16:
8193   case Builtin::BI__builtin_bswap32:
8194   case Builtin::BI__builtin_bswap64: {
8195     APSInt Val;
8196     if (!EvaluateInteger(E->getArg(0), Val, Info))
8197       return false;
8198 
8199     return Success(Val.byteSwap(), E);
8200   }
8201 
8202   case Builtin::BI__builtin_classify_type:
8203     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8204 
8205   case Builtin::BI__builtin_clrsb:
8206   case Builtin::BI__builtin_clrsbl:
8207   case Builtin::BI__builtin_clrsbll: {
8208     APSInt Val;
8209     if (!EvaluateInteger(E->getArg(0), Val, Info))
8210       return false;
8211 
8212     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8213   }
8214 
8215   case Builtin::BI__builtin_clz:
8216   case Builtin::BI__builtin_clzl:
8217   case Builtin::BI__builtin_clzll:
8218   case Builtin::BI__builtin_clzs: {
8219     APSInt Val;
8220     if (!EvaluateInteger(E->getArg(0), Val, Info))
8221       return false;
8222     if (!Val)
8223       return Error(E);
8224 
8225     return Success(Val.countLeadingZeros(), E);
8226   }
8227 
8228   case Builtin::BI__builtin_constant_p: {
8229     auto Arg = E->getArg(0);
8230     if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8231       return Success(true, E);
8232     auto ArgTy = Arg->IgnoreImplicit()->getType();
8233     if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8234         !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8235       // We can delay calculation of __builtin_constant_p until after
8236       // inlining. Note: This diagnostic won't be shown to the user.
8237       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8238       return false;
8239     }
8240     return Success(false, E);
8241   }
8242 
8243   case Builtin::BI__builtin_ctz:
8244   case Builtin::BI__builtin_ctzl:
8245   case Builtin::BI__builtin_ctzll:
8246   case Builtin::BI__builtin_ctzs: {
8247     APSInt Val;
8248     if (!EvaluateInteger(E->getArg(0), Val, Info))
8249       return false;
8250     if (!Val)
8251       return Error(E);
8252 
8253     return Success(Val.countTrailingZeros(), E);
8254   }
8255 
8256   case Builtin::BI__builtin_eh_return_data_regno: {
8257     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8258     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8259     return Success(Operand, E);
8260   }
8261 
8262   case Builtin::BI__builtin_expect:
8263     return Visit(E->getArg(0));
8264 
8265   case Builtin::BI__builtin_ffs:
8266   case Builtin::BI__builtin_ffsl:
8267   case Builtin::BI__builtin_ffsll: {
8268     APSInt Val;
8269     if (!EvaluateInteger(E->getArg(0), Val, Info))
8270       return false;
8271 
8272     unsigned N = Val.countTrailingZeros();
8273     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8274   }
8275 
8276   case Builtin::BI__builtin_fpclassify: {
8277     APFloat Val(0.0);
8278     if (!EvaluateFloat(E->getArg(5), Val, Info))
8279       return false;
8280     unsigned Arg;
8281     switch (Val.getCategory()) {
8282     case APFloat::fcNaN: Arg = 0; break;
8283     case APFloat::fcInfinity: Arg = 1; break;
8284     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8285     case APFloat::fcZero: Arg = 4; break;
8286     }
8287     return Visit(E->getArg(Arg));
8288   }
8289 
8290   case Builtin::BI__builtin_isinf_sign: {
8291     APFloat Val(0.0);
8292     return EvaluateFloat(E->getArg(0), Val, Info) &&
8293            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8294   }
8295 
8296   case Builtin::BI__builtin_isinf: {
8297     APFloat Val(0.0);
8298     return EvaluateFloat(E->getArg(0), Val, Info) &&
8299            Success(Val.isInfinity() ? 1 : 0, E);
8300   }
8301 
8302   case Builtin::BI__builtin_isfinite: {
8303     APFloat Val(0.0);
8304     return EvaluateFloat(E->getArg(0), Val, Info) &&
8305            Success(Val.isFinite() ? 1 : 0, E);
8306   }
8307 
8308   case Builtin::BI__builtin_isnan: {
8309     APFloat Val(0.0);
8310     return EvaluateFloat(E->getArg(0), Val, Info) &&
8311            Success(Val.isNaN() ? 1 : 0, E);
8312   }
8313 
8314   case Builtin::BI__builtin_isnormal: {
8315     APFloat Val(0.0);
8316     return EvaluateFloat(E->getArg(0), Val, Info) &&
8317            Success(Val.isNormal() ? 1 : 0, E);
8318   }
8319 
8320   case Builtin::BI__builtin_parity:
8321   case Builtin::BI__builtin_parityl:
8322   case Builtin::BI__builtin_parityll: {
8323     APSInt Val;
8324     if (!EvaluateInteger(E->getArg(0), Val, Info))
8325       return false;
8326 
8327     return Success(Val.countPopulation() % 2, E);
8328   }
8329 
8330   case Builtin::BI__builtin_popcount:
8331   case Builtin::BI__builtin_popcountl:
8332   case Builtin::BI__builtin_popcountll: {
8333     APSInt Val;
8334     if (!EvaluateInteger(E->getArg(0), Val, Info))
8335       return false;
8336 
8337     return Success(Val.countPopulation(), E);
8338   }
8339 
8340   case Builtin::BIstrlen:
8341   case Builtin::BIwcslen:
8342     // A call to strlen is not a constant expression.
8343     if (Info.getLangOpts().CPlusPlus11)
8344       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8345         << /*isConstexpr*/0 << /*isConstructor*/0
8346         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8347     else
8348       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8349     LLVM_FALLTHROUGH;
8350   case Builtin::BI__builtin_strlen:
8351   case Builtin::BI__builtin_wcslen: {
8352     // As an extension, we support __builtin_strlen() as a constant expression,
8353     // and support folding strlen() to a constant.
8354     LValue String;
8355     if (!EvaluatePointer(E->getArg(0), String, Info))
8356       return false;
8357 
8358     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8359 
8360     // Fast path: if it's a string literal, search the string value.
8361     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8362             String.getLValueBase().dyn_cast<const Expr *>())) {
8363       // The string literal may have embedded null characters. Find the first
8364       // one and truncate there.
8365       StringRef Str = S->getBytes();
8366       int64_t Off = String.Offset.getQuantity();
8367       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8368           S->getCharByteWidth() == 1 &&
8369           // FIXME: Add fast-path for wchar_t too.
8370           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8371         Str = Str.substr(Off);
8372 
8373         StringRef::size_type Pos = Str.find(0);
8374         if (Pos != StringRef::npos)
8375           Str = Str.substr(0, Pos);
8376 
8377         return Success(Str.size(), E);
8378       }
8379 
8380       // Fall through to slow path to issue appropriate diagnostic.
8381     }
8382 
8383     // Slow path: scan the bytes of the string looking for the terminating 0.
8384     for (uint64_t Strlen = 0; /**/; ++Strlen) {
8385       APValue Char;
8386       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8387           !Char.isInt())
8388         return false;
8389       if (!Char.getInt())
8390         return Success(Strlen, E);
8391       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8392         return false;
8393     }
8394   }
8395 
8396   case Builtin::BIstrcmp:
8397   case Builtin::BIwcscmp:
8398   case Builtin::BIstrncmp:
8399   case Builtin::BIwcsncmp:
8400   case Builtin::BImemcmp:
8401   case Builtin::BIwmemcmp:
8402     // A call to strlen is not a constant expression.
8403     if (Info.getLangOpts().CPlusPlus11)
8404       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8405         << /*isConstexpr*/0 << /*isConstructor*/0
8406         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8407     else
8408       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8409     LLVM_FALLTHROUGH;
8410   case Builtin::BI__builtin_strcmp:
8411   case Builtin::BI__builtin_wcscmp:
8412   case Builtin::BI__builtin_strncmp:
8413   case Builtin::BI__builtin_wcsncmp:
8414   case Builtin::BI__builtin_memcmp:
8415   case Builtin::BI__builtin_wmemcmp: {
8416     LValue String1, String2;
8417     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8418         !EvaluatePointer(E->getArg(1), String2, Info))
8419       return false;
8420 
8421     uint64_t MaxLength = uint64_t(-1);
8422     if (BuiltinOp != Builtin::BIstrcmp &&
8423         BuiltinOp != Builtin::BIwcscmp &&
8424         BuiltinOp != Builtin::BI__builtin_strcmp &&
8425         BuiltinOp != Builtin::BI__builtin_wcscmp) {
8426       APSInt N;
8427       if (!EvaluateInteger(E->getArg(2), N, Info))
8428         return false;
8429       MaxLength = N.getExtValue();
8430     }
8431 
8432     // Empty substrings compare equal by definition.
8433     if (MaxLength == 0u)
8434       return Success(0, E);
8435 
8436     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8437         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8438         String1.Designator.Invalid || String2.Designator.Invalid)
8439       return false;
8440 
8441     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8442     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8443 
8444     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
8445                      BuiltinOp == Builtin::BI__builtin_memcmp;
8446 
8447     assert(IsRawByte ||
8448            (Info.Ctx.hasSameUnqualifiedType(
8449                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8450             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8451 
8452     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8453       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8454              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8455              Char1.isInt() && Char2.isInt();
8456     };
8457     const auto &AdvanceElems = [&] {
8458       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8459              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8460     };
8461 
8462     if (IsRawByte) {
8463       uint64_t BytesRemaining = MaxLength;
8464       // Pointers to const void may point to objects of incomplete type.
8465       if (CharTy1->isIncompleteType()) {
8466         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8467         return false;
8468       }
8469       if (CharTy2->isIncompleteType()) {
8470         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8471         return false;
8472       }
8473       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8474       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8475       // Give up on comparing between elements with disparate widths.
8476       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8477         return false;
8478       uint64_t BytesPerElement = CharTy1Size.getQuantity();
8479       assert(BytesRemaining && "BytesRemaining should not be zero: the "
8480                                "following loop considers at least one element");
8481       while (true) {
8482         APValue Char1, Char2;
8483         if (!ReadCurElems(Char1, Char2))
8484           return false;
8485         // We have compatible in-memory widths, but a possible type and
8486         // (for `bool`) internal representation mismatch.
8487         // Assuming two's complement representation, including 0 for `false` and
8488         // 1 for `true`, we can check an appropriate number of elements for
8489         // equality even if they are not byte-sized.
8490         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8491         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8492         if (Char1InMem.ne(Char2InMem)) {
8493           // If the elements are byte-sized, then we can produce a three-way
8494           // comparison result in a straightforward manner.
8495           if (BytesPerElement == 1u) {
8496             // memcmp always compares unsigned chars.
8497             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8498           }
8499           // The result is byte-order sensitive, and we have multibyte elements.
8500           // FIXME: We can compare the remaining bytes in the correct order.
8501           return false;
8502         }
8503         if (!AdvanceElems())
8504           return false;
8505         if (BytesRemaining <= BytesPerElement)
8506           break;
8507         BytesRemaining -= BytesPerElement;
8508       }
8509       // Enough elements are equal to account for the memcmp limit.
8510       return Success(0, E);
8511     }
8512 
8513     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8514                        BuiltinOp != Builtin::BIwmemcmp &&
8515                        BuiltinOp != Builtin::BI__builtin_memcmp &&
8516                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
8517     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8518                   BuiltinOp == Builtin::BIwcsncmp ||
8519                   BuiltinOp == Builtin::BIwmemcmp ||
8520                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
8521                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8522                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
8523 
8524     for (; MaxLength; --MaxLength) {
8525       APValue Char1, Char2;
8526       if (!ReadCurElems(Char1, Char2))
8527         return false;
8528       if (Char1.getInt() != Char2.getInt()) {
8529         if (IsWide) // wmemcmp compares with wchar_t signedness.
8530           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8531         // memcmp always compares unsigned chars.
8532         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8533       }
8534       if (StopAtNull && !Char1.getInt())
8535         return Success(0, E);
8536       assert(!(StopAtNull && !Char2.getInt()));
8537       if (!AdvanceElems())
8538         return false;
8539     }
8540     // We hit the strncmp / memcmp limit.
8541     return Success(0, E);
8542   }
8543 
8544   case Builtin::BI__atomic_always_lock_free:
8545   case Builtin::BI__atomic_is_lock_free:
8546   case Builtin::BI__c11_atomic_is_lock_free: {
8547     APSInt SizeVal;
8548     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8549       return false;
8550 
8551     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8552     // of two less than the maximum inline atomic width, we know it is
8553     // lock-free.  If the size isn't a power of two, or greater than the
8554     // maximum alignment where we promote atomics, we know it is not lock-free
8555     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
8556     // the answer can only be determined at runtime; for example, 16-byte
8557     // atomics have lock-free implementations on some, but not all,
8558     // x86-64 processors.
8559 
8560     // Check power-of-two.
8561     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8562     if (Size.isPowerOfTwo()) {
8563       // Check against inlining width.
8564       unsigned InlineWidthBits =
8565           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8566       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8567         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8568             Size == CharUnits::One() ||
8569             E->getArg(1)->isNullPointerConstant(Info.Ctx,
8570                                                 Expr::NPC_NeverValueDependent))
8571           // OK, we will inline appropriately-aligned operations of this size,
8572           // and _Atomic(T) is appropriately-aligned.
8573           return Success(1, E);
8574 
8575         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8576           castAs<PointerType>()->getPointeeType();
8577         if (!PointeeType->isIncompleteType() &&
8578             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8579           // OK, we will inline operations on this object.
8580           return Success(1, E);
8581         }
8582       }
8583     }
8584 
8585     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8586         Success(0, E) : Error(E);
8587   }
8588   case Builtin::BIomp_is_initial_device:
8589     // We can decide statically which value the runtime would return if called.
8590     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8591   case Builtin::BI__builtin_add_overflow:
8592   case Builtin::BI__builtin_sub_overflow:
8593   case Builtin::BI__builtin_mul_overflow:
8594   case Builtin::BI__builtin_sadd_overflow:
8595   case Builtin::BI__builtin_uadd_overflow:
8596   case Builtin::BI__builtin_uaddl_overflow:
8597   case Builtin::BI__builtin_uaddll_overflow:
8598   case Builtin::BI__builtin_usub_overflow:
8599   case Builtin::BI__builtin_usubl_overflow:
8600   case Builtin::BI__builtin_usubll_overflow:
8601   case Builtin::BI__builtin_umul_overflow:
8602   case Builtin::BI__builtin_umull_overflow:
8603   case Builtin::BI__builtin_umulll_overflow:
8604   case Builtin::BI__builtin_saddl_overflow:
8605   case Builtin::BI__builtin_saddll_overflow:
8606   case Builtin::BI__builtin_ssub_overflow:
8607   case Builtin::BI__builtin_ssubl_overflow:
8608   case Builtin::BI__builtin_ssubll_overflow:
8609   case Builtin::BI__builtin_smul_overflow:
8610   case Builtin::BI__builtin_smull_overflow:
8611   case Builtin::BI__builtin_smulll_overflow: {
8612     LValue ResultLValue;
8613     APSInt LHS, RHS;
8614 
8615     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8616     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8617         !EvaluateInteger(E->getArg(1), RHS, Info) ||
8618         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8619       return false;
8620 
8621     APSInt Result;
8622     bool DidOverflow = false;
8623 
8624     // If the types don't have to match, enlarge all 3 to the largest of them.
8625     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8626         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8627         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8628       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8629                       ResultType->isSignedIntegerOrEnumerationType();
8630       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8631                       ResultType->isSignedIntegerOrEnumerationType();
8632       uint64_t LHSSize = LHS.getBitWidth();
8633       uint64_t RHSSize = RHS.getBitWidth();
8634       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8635       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8636 
8637       // Add an additional bit if the signedness isn't uniformly agreed to. We
8638       // could do this ONLY if there is a signed and an unsigned that both have
8639       // MaxBits, but the code to check that is pretty nasty.  The issue will be
8640       // caught in the shrink-to-result later anyway.
8641       if (IsSigned && !AllSigned)
8642         ++MaxBits;
8643 
8644       LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8645                    !IsSigned);
8646       RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8647                    !IsSigned);
8648       Result = APSInt(MaxBits, !IsSigned);
8649     }
8650 
8651     // Find largest int.
8652     switch (BuiltinOp) {
8653     default:
8654       llvm_unreachable("Invalid value for BuiltinOp");
8655     case Builtin::BI__builtin_add_overflow:
8656     case Builtin::BI__builtin_sadd_overflow:
8657     case Builtin::BI__builtin_saddl_overflow:
8658     case Builtin::BI__builtin_saddll_overflow:
8659     case Builtin::BI__builtin_uadd_overflow:
8660     case Builtin::BI__builtin_uaddl_overflow:
8661     case Builtin::BI__builtin_uaddll_overflow:
8662       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8663                               : LHS.uadd_ov(RHS, DidOverflow);
8664       break;
8665     case Builtin::BI__builtin_sub_overflow:
8666     case Builtin::BI__builtin_ssub_overflow:
8667     case Builtin::BI__builtin_ssubl_overflow:
8668     case Builtin::BI__builtin_ssubll_overflow:
8669     case Builtin::BI__builtin_usub_overflow:
8670     case Builtin::BI__builtin_usubl_overflow:
8671     case Builtin::BI__builtin_usubll_overflow:
8672       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8673                               : LHS.usub_ov(RHS, DidOverflow);
8674       break;
8675     case Builtin::BI__builtin_mul_overflow:
8676     case Builtin::BI__builtin_smul_overflow:
8677     case Builtin::BI__builtin_smull_overflow:
8678     case Builtin::BI__builtin_smulll_overflow:
8679     case Builtin::BI__builtin_umul_overflow:
8680     case Builtin::BI__builtin_umull_overflow:
8681     case Builtin::BI__builtin_umulll_overflow:
8682       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8683                               : LHS.umul_ov(RHS, DidOverflow);
8684       break;
8685     }
8686 
8687     // In the case where multiple sizes are allowed, truncate and see if
8688     // the values are the same.
8689     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8690         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8691         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8692       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8693       // since it will give us the behavior of a TruncOrSelf in the case where
8694       // its parameter <= its size.  We previously set Result to be at least the
8695       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8696       // will work exactly like TruncOrSelf.
8697       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8698       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8699 
8700       if (!APSInt::isSameValue(Temp, Result))
8701         DidOverflow = true;
8702       Result = Temp;
8703     }
8704 
8705     APValue APV{Result};
8706     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8707       return false;
8708     return Success(DidOverflow, E);
8709   }
8710   }
8711 }
8712 
8713 /// Determine whether this is a pointer past the end of the complete
8714 /// object referred to by the lvalue.
8715 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8716                                             const LValue &LV) {
8717   // A null pointer can be viewed as being "past the end" but we don't
8718   // choose to look at it that way here.
8719   if (!LV.getLValueBase())
8720     return false;
8721 
8722   // If the designator is valid and refers to a subobject, we're not pointing
8723   // past the end.
8724   if (!LV.getLValueDesignator().Invalid &&
8725       !LV.getLValueDesignator().isOnePastTheEnd())
8726     return false;
8727 
8728   // A pointer to an incomplete type might be past-the-end if the type's size is
8729   // zero.  We cannot tell because the type is incomplete.
8730   QualType Ty = getType(LV.getLValueBase());
8731   if (Ty->isIncompleteType())
8732     return true;
8733 
8734   // We're a past-the-end pointer if we point to the byte after the object,
8735   // no matter what our type or path is.
8736   auto Size = Ctx.getTypeSizeInChars(Ty);
8737   return LV.getLValueOffset() == Size;
8738 }
8739 
8740 namespace {
8741 
8742 /// Data recursive integer evaluator of certain binary operators.
8743 ///
8744 /// We use a data recursive algorithm for binary operators so that we are able
8745 /// to handle extreme cases of chained binary operators without causing stack
8746 /// overflow.
8747 class DataRecursiveIntBinOpEvaluator {
8748   struct EvalResult {
8749     APValue Val;
8750     bool Failed;
8751 
8752     EvalResult() : Failed(false) { }
8753 
8754     void swap(EvalResult &RHS) {
8755       Val.swap(RHS.Val);
8756       Failed = RHS.Failed;
8757       RHS.Failed = false;
8758     }
8759   };
8760 
8761   struct Job {
8762     const Expr *E;
8763     EvalResult LHSResult; // meaningful only for binary operator expression.
8764     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8765 
8766     Job() = default;
8767     Job(Job &&) = default;
8768 
8769     void startSpeculativeEval(EvalInfo &Info) {
8770       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8771     }
8772 
8773   private:
8774     SpeculativeEvaluationRAII SpecEvalRAII;
8775   };
8776 
8777   SmallVector<Job, 16> Queue;
8778 
8779   IntExprEvaluator &IntEval;
8780   EvalInfo &Info;
8781   APValue &FinalResult;
8782 
8783 public:
8784   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8785     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8786 
8787   /// True if \param E is a binary operator that we are going to handle
8788   /// data recursively.
8789   /// We handle binary operators that are comma, logical, or that have operands
8790   /// with integral or enumeration type.
8791   static bool shouldEnqueue(const BinaryOperator *E) {
8792     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8793            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8794             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8795             E->getRHS()->getType()->isIntegralOrEnumerationType());
8796   }
8797 
8798   bool Traverse(const BinaryOperator *E) {
8799     enqueue(E);
8800     EvalResult PrevResult;
8801     while (!Queue.empty())
8802       process(PrevResult);
8803 
8804     if (PrevResult.Failed) return false;
8805 
8806     FinalResult.swap(PrevResult.Val);
8807     return true;
8808   }
8809 
8810 private:
8811   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8812     return IntEval.Success(Value, E, Result);
8813   }
8814   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8815     return IntEval.Success(Value, E, Result);
8816   }
8817   bool Error(const Expr *E) {
8818     return IntEval.Error(E);
8819   }
8820   bool Error(const Expr *E, diag::kind D) {
8821     return IntEval.Error(E, D);
8822   }
8823 
8824   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8825     return Info.CCEDiag(E, D);
8826   }
8827 
8828   // Returns true if visiting the RHS is necessary, false otherwise.
8829   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8830                          bool &SuppressRHSDiags);
8831 
8832   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8833                   const BinaryOperator *E, APValue &Result);
8834 
8835   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8836     Result.Failed = !Evaluate(Result.Val, Info, E);
8837     if (Result.Failed)
8838       Result.Val = APValue();
8839   }
8840 
8841   void process(EvalResult &Result);
8842 
8843   void enqueue(const Expr *E) {
8844     E = E->IgnoreParens();
8845     Queue.resize(Queue.size()+1);
8846     Queue.back().E = E;
8847     Queue.back().Kind = Job::AnyExprKind;
8848   }
8849 };
8850 
8851 }
8852 
8853 bool DataRecursiveIntBinOpEvaluator::
8854        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8855                          bool &SuppressRHSDiags) {
8856   if (E->getOpcode() == BO_Comma) {
8857     // Ignore LHS but note if we could not evaluate it.
8858     if (LHSResult.Failed)
8859       return Info.noteSideEffect();
8860     return true;
8861   }
8862 
8863   if (E->isLogicalOp()) {
8864     bool LHSAsBool;
8865     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8866       // We were able to evaluate the LHS, see if we can get away with not
8867       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8868       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8869         Success(LHSAsBool, E, LHSResult.Val);
8870         return false; // Ignore RHS
8871       }
8872     } else {
8873       LHSResult.Failed = true;
8874 
8875       // Since we weren't able to evaluate the left hand side, it
8876       // might have had side effects.
8877       if (!Info.noteSideEffect())
8878         return false;
8879 
8880       // We can't evaluate the LHS; however, sometimes the result
8881       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8882       // Don't ignore RHS and suppress diagnostics from this arm.
8883       SuppressRHSDiags = true;
8884     }
8885 
8886     return true;
8887   }
8888 
8889   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8890          E->getRHS()->getType()->isIntegralOrEnumerationType());
8891 
8892   if (LHSResult.Failed && !Info.noteFailure())
8893     return false; // Ignore RHS;
8894 
8895   return true;
8896 }
8897 
8898 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8899                                     bool IsSub) {
8900   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8901   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8902   // offsets.
8903   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8904   CharUnits &Offset = LVal.getLValueOffset();
8905   uint64_t Offset64 = Offset.getQuantity();
8906   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8907   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8908                                          : Offset64 + Index64);
8909 }
8910 
8911 bool DataRecursiveIntBinOpEvaluator::
8912        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8913                   const BinaryOperator *E, APValue &Result) {
8914   if (E->getOpcode() == BO_Comma) {
8915     if (RHSResult.Failed)
8916       return false;
8917     Result = RHSResult.Val;
8918     return true;
8919   }
8920 
8921   if (E->isLogicalOp()) {
8922     bool lhsResult, rhsResult;
8923     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8924     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8925 
8926     if (LHSIsOK) {
8927       if (RHSIsOK) {
8928         if (E->getOpcode() == BO_LOr)
8929           return Success(lhsResult || rhsResult, E, Result);
8930         else
8931           return Success(lhsResult && rhsResult, E, Result);
8932       }
8933     } else {
8934       if (RHSIsOK) {
8935         // We can't evaluate the LHS; however, sometimes the result
8936         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8937         if (rhsResult == (E->getOpcode() == BO_LOr))
8938           return Success(rhsResult, E, Result);
8939       }
8940     }
8941 
8942     return false;
8943   }
8944 
8945   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8946          E->getRHS()->getType()->isIntegralOrEnumerationType());
8947 
8948   if (LHSResult.Failed || RHSResult.Failed)
8949     return false;
8950 
8951   const APValue &LHSVal = LHSResult.Val;
8952   const APValue &RHSVal = RHSResult.Val;
8953 
8954   // Handle cases like (unsigned long)&a + 4.
8955   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8956     Result = LHSVal;
8957     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8958     return true;
8959   }
8960 
8961   // Handle cases like 4 + (unsigned long)&a
8962   if (E->getOpcode() == BO_Add &&
8963       RHSVal.isLValue() && LHSVal.isInt()) {
8964     Result = RHSVal;
8965     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8966     return true;
8967   }
8968 
8969   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8970     // Handle (intptr_t)&&A - (intptr_t)&&B.
8971     if (!LHSVal.getLValueOffset().isZero() ||
8972         !RHSVal.getLValueOffset().isZero())
8973       return false;
8974     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8975     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8976     if (!LHSExpr || !RHSExpr)
8977       return false;
8978     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8979     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8980     if (!LHSAddrExpr || !RHSAddrExpr)
8981       return false;
8982     // Make sure both labels come from the same function.
8983     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8984         RHSAddrExpr->getLabel()->getDeclContext())
8985       return false;
8986     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8987     return true;
8988   }
8989 
8990   // All the remaining cases expect both operands to be an integer
8991   if (!LHSVal.isInt() || !RHSVal.isInt())
8992     return Error(E);
8993 
8994   // Set up the width and signedness manually, in case it can't be deduced
8995   // from the operation we're performing.
8996   // FIXME: Don't do this in the cases where we can deduce it.
8997   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8998                E->getType()->isUnsignedIntegerOrEnumerationType());
8999   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9000                          RHSVal.getInt(), Value))
9001     return false;
9002   return Success(Value, E, Result);
9003 }
9004 
9005 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9006   Job &job = Queue.back();
9007 
9008   switch (job.Kind) {
9009     case Job::AnyExprKind: {
9010       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9011         if (shouldEnqueue(Bop)) {
9012           job.Kind = Job::BinOpKind;
9013           enqueue(Bop->getLHS());
9014           return;
9015         }
9016       }
9017 
9018       EvaluateExpr(job.E, Result);
9019       Queue.pop_back();
9020       return;
9021     }
9022 
9023     case Job::BinOpKind: {
9024       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9025       bool SuppressRHSDiags = false;
9026       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9027         Queue.pop_back();
9028         return;
9029       }
9030       if (SuppressRHSDiags)
9031         job.startSpeculativeEval(Info);
9032       job.LHSResult.swap(Result);
9033       job.Kind = Job::BinOpVisitedLHSKind;
9034       enqueue(Bop->getRHS());
9035       return;
9036     }
9037 
9038     case Job::BinOpVisitedLHSKind: {
9039       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9040       EvalResult RHS;
9041       RHS.swap(Result);
9042       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9043       Queue.pop_back();
9044       return;
9045     }
9046   }
9047 
9048   llvm_unreachable("Invalid Job::Kind!");
9049 }
9050 
9051 namespace {
9052 /// Used when we determine that we should fail, but can keep evaluating prior to
9053 /// noting that we had a failure.
9054 class DelayedNoteFailureRAII {
9055   EvalInfo &Info;
9056   bool NoteFailure;
9057 
9058 public:
9059   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9060       : Info(Info), NoteFailure(NoteFailure) {}
9061   ~DelayedNoteFailureRAII() {
9062     if (NoteFailure) {
9063       bool ContinueAfterFailure = Info.noteFailure();
9064       (void)ContinueAfterFailure;
9065       assert(ContinueAfterFailure &&
9066              "Shouldn't have kept evaluating on failure.");
9067     }
9068   }
9069 };
9070 }
9071 
9072 template <class SuccessCB, class AfterCB>
9073 static bool
9074 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9075                                  SuccessCB &&Success, AfterCB &&DoAfter) {
9076   assert(E->isComparisonOp() && "expected comparison operator");
9077   assert((E->getOpcode() == BO_Cmp ||
9078           E->getType()->isIntegralOrEnumerationType()) &&
9079          "unsupported binary expression evaluation");
9080   auto Error = [&](const Expr *E) {
9081     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9082     return false;
9083   };
9084 
9085   using CCR = ComparisonCategoryResult;
9086   bool IsRelational = E->isRelationalOp();
9087   bool IsEquality = E->isEqualityOp();
9088   if (E->getOpcode() == BO_Cmp) {
9089     const ComparisonCategoryInfo &CmpInfo =
9090         Info.Ctx.CompCategories.getInfoForType(E->getType());
9091     IsRelational = CmpInfo.isOrdered();
9092     IsEquality = CmpInfo.isEquality();
9093   }
9094 
9095   QualType LHSTy = E->getLHS()->getType();
9096   QualType RHSTy = E->getRHS()->getType();
9097 
9098   if (LHSTy->isIntegralOrEnumerationType() &&
9099       RHSTy->isIntegralOrEnumerationType()) {
9100     APSInt LHS, RHS;
9101     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9102     if (!LHSOK && !Info.noteFailure())
9103       return false;
9104     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9105       return false;
9106     if (LHS < RHS)
9107       return Success(CCR::Less, E);
9108     if (LHS > RHS)
9109       return Success(CCR::Greater, E);
9110     return Success(CCR::Equal, E);
9111   }
9112 
9113   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
9114     ComplexValue LHS, RHS;
9115     bool LHSOK;
9116     if (E->isAssignmentOp()) {
9117       LValue LV;
9118       EvaluateLValue(E->getLHS(), LV, Info);
9119       LHSOK = false;
9120     } else if (LHSTy->isRealFloatingType()) {
9121       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9122       if (LHSOK) {
9123         LHS.makeComplexFloat();
9124         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9125       }
9126     } else {
9127       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9128     }
9129     if (!LHSOK && !Info.noteFailure())
9130       return false;
9131 
9132     if (E->getRHS()->getType()->isRealFloatingType()) {
9133       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9134         return false;
9135       RHS.makeComplexFloat();
9136       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9137     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9138       return false;
9139 
9140     if (LHS.isComplexFloat()) {
9141       APFloat::cmpResult CR_r =
9142         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9143       APFloat::cmpResult CR_i =
9144         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
9145       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9146       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9147     } else {
9148       assert(IsEquality && "invalid complex comparison");
9149       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9150                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
9151       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9152     }
9153   }
9154 
9155   if (LHSTy->isRealFloatingType() &&
9156       RHSTy->isRealFloatingType()) {
9157     APFloat RHS(0.0), LHS(0.0);
9158 
9159     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
9160     if (!LHSOK && !Info.noteFailure())
9161       return false;
9162 
9163     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
9164       return false;
9165 
9166     assert(E->isComparisonOp() && "Invalid binary operator!");
9167     auto GetCmpRes = [&]() {
9168       switch (LHS.compare(RHS)) {
9169       case APFloat::cmpEqual:
9170         return CCR::Equal;
9171       case APFloat::cmpLessThan:
9172         return CCR::Less;
9173       case APFloat::cmpGreaterThan:
9174         return CCR::Greater;
9175       case APFloat::cmpUnordered:
9176         return CCR::Unordered;
9177       }
9178       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9179     };
9180     return Success(GetCmpRes(), E);
9181   }
9182 
9183   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9184     LValue LHSValue, RHSValue;
9185 
9186     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9187     if (!LHSOK && !Info.noteFailure())
9188       return false;
9189 
9190     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9191       return false;
9192 
9193     // Reject differing bases from the normal codepath; we special-case
9194     // comparisons to null.
9195     if (!HasSameBase(LHSValue, RHSValue)) {
9196       // Inequalities and subtractions between unrelated pointers have
9197       // unspecified or undefined behavior.
9198       if (!IsEquality)
9199         return Error(E);
9200       // A constant address may compare equal to the address of a symbol.
9201       // The one exception is that address of an object cannot compare equal
9202       // to a null pointer constant.
9203       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9204           (!RHSValue.Base && !RHSValue.Offset.isZero()))
9205         return Error(E);
9206       // It's implementation-defined whether distinct literals will have
9207       // distinct addresses. In clang, the result of such a comparison is
9208       // unspecified, so it is not a constant expression. However, we do know
9209       // that the address of a literal will be non-null.
9210       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9211           LHSValue.Base && RHSValue.Base)
9212         return Error(E);
9213       // We can't tell whether weak symbols will end up pointing to the same
9214       // object.
9215       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9216         return Error(E);
9217       // We can't compare the address of the start of one object with the
9218       // past-the-end address of another object, per C++ DR1652.
9219       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9220            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9221           (RHSValue.Base && RHSValue.Offset.isZero() &&
9222            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9223         return Error(E);
9224       // We can't tell whether an object is at the same address as another
9225       // zero sized object.
9226       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9227           (LHSValue.Base && isZeroSized(RHSValue)))
9228         return Error(E);
9229       return Success(CCR::Nonequal, E);
9230     }
9231 
9232     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9233     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9234 
9235     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9236     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9237 
9238     // C++11 [expr.rel]p3:
9239     //   Pointers to void (after pointer conversions) can be compared, with a
9240     //   result defined as follows: If both pointers represent the same
9241     //   address or are both the null pointer value, the result is true if the
9242     //   operator is <= or >= and false otherwise; otherwise the result is
9243     //   unspecified.
9244     // We interpret this as applying to pointers to *cv* void.
9245     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9246       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9247 
9248     // C++11 [expr.rel]p2:
9249     // - If two pointers point to non-static data members of the same object,
9250     //   or to subobjects or array elements fo such members, recursively, the
9251     //   pointer to the later declared member compares greater provided the
9252     //   two members have the same access control and provided their class is
9253     //   not a union.
9254     //   [...]
9255     // - Otherwise pointer comparisons are unspecified.
9256     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9257       bool WasArrayIndex;
9258       unsigned Mismatch = FindDesignatorMismatch(
9259           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9260       // At the point where the designators diverge, the comparison has a
9261       // specified value if:
9262       //  - we are comparing array indices
9263       //  - we are comparing fields of a union, or fields with the same access
9264       // Otherwise, the result is unspecified and thus the comparison is not a
9265       // constant expression.
9266       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9267           Mismatch < RHSDesignator.Entries.size()) {
9268         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9269         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9270         if (!LF && !RF)
9271           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9272         else if (!LF)
9273           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9274               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9275               << RF->getParent() << RF;
9276         else if (!RF)
9277           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9278               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9279               << LF->getParent() << LF;
9280         else if (!LF->getParent()->isUnion() &&
9281                  LF->getAccess() != RF->getAccess())
9282           Info.CCEDiag(E,
9283                        diag::note_constexpr_pointer_comparison_differing_access)
9284               << LF << LF->getAccess() << RF << RF->getAccess()
9285               << LF->getParent();
9286       }
9287     }
9288 
9289     // The comparison here must be unsigned, and performed with the same
9290     // width as the pointer.
9291     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9292     uint64_t CompareLHS = LHSOffset.getQuantity();
9293     uint64_t CompareRHS = RHSOffset.getQuantity();
9294     assert(PtrSize <= 64 && "Unexpected pointer width");
9295     uint64_t Mask = ~0ULL >> (64 - PtrSize);
9296     CompareLHS &= Mask;
9297     CompareRHS &= Mask;
9298 
9299     // If there is a base and this is a relational operator, we can only
9300     // compare pointers within the object in question; otherwise, the result
9301     // depends on where the object is located in memory.
9302     if (!LHSValue.Base.isNull() && IsRelational) {
9303       QualType BaseTy = getType(LHSValue.Base);
9304       if (BaseTy->isIncompleteType())
9305         return Error(E);
9306       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9307       uint64_t OffsetLimit = Size.getQuantity();
9308       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9309         return Error(E);
9310     }
9311 
9312     if (CompareLHS < CompareRHS)
9313       return Success(CCR::Less, E);
9314     if (CompareLHS > CompareRHS)
9315       return Success(CCR::Greater, E);
9316     return Success(CCR::Equal, E);
9317   }
9318 
9319   if (LHSTy->isMemberPointerType()) {
9320     assert(IsEquality && "unexpected member pointer operation");
9321     assert(RHSTy->isMemberPointerType() && "invalid comparison");
9322 
9323     MemberPtr LHSValue, RHSValue;
9324 
9325     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9326     if (!LHSOK && !Info.noteFailure())
9327       return false;
9328 
9329     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9330       return false;
9331 
9332     // C++11 [expr.eq]p2:
9333     //   If both operands are null, they compare equal. Otherwise if only one is
9334     //   null, they compare unequal.
9335     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9336       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9337       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9338     }
9339 
9340     //   Otherwise if either is a pointer to a virtual member function, the
9341     //   result is unspecified.
9342     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9343       if (MD->isVirtual())
9344         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9345     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9346       if (MD->isVirtual())
9347         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9348 
9349     //   Otherwise they compare equal if and only if they would refer to the
9350     //   same member of the same most derived object or the same subobject if
9351     //   they were dereferenced with a hypothetical object of the associated
9352     //   class type.
9353     bool Equal = LHSValue == RHSValue;
9354     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9355   }
9356 
9357   if (LHSTy->isNullPtrType()) {
9358     assert(E->isComparisonOp() && "unexpected nullptr operation");
9359     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9360     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9361     // are compared, the result is true of the operator is <=, >= or ==, and
9362     // false otherwise.
9363     return Success(CCR::Equal, E);
9364   }
9365 
9366   return DoAfter();
9367 }
9368 
9369 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9370   if (!CheckLiteralType(Info, E))
9371     return false;
9372 
9373   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9374                        const BinaryOperator *E) {
9375     // Evaluation succeeded. Lookup the information for the comparison category
9376     // type and fetch the VarDecl for the result.
9377     const ComparisonCategoryInfo &CmpInfo =
9378         Info.Ctx.CompCategories.getInfoForType(E->getType());
9379     const VarDecl *VD =
9380         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9381     // Check and evaluate the result as a constant expression.
9382     LValue LV;
9383     LV.set(VD);
9384     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9385       return false;
9386     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9387   };
9388   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9389     return ExprEvaluatorBaseTy::VisitBinCmp(E);
9390   });
9391 }
9392 
9393 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9394   // We don't call noteFailure immediately because the assignment happens after
9395   // we evaluate LHS and RHS.
9396   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9397     return Error(E);
9398 
9399   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9400   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9401     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9402 
9403   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9404           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9405          "DataRecursiveIntBinOpEvaluator should have handled integral types");
9406 
9407   if (E->isComparisonOp()) {
9408     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9409     // comparisons and then translating the result.
9410     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9411                          const BinaryOperator *E) {
9412       using CCR = ComparisonCategoryResult;
9413       bool IsEqual   = ResKind == CCR::Equal,
9414            IsLess    = ResKind == CCR::Less,
9415            IsGreater = ResKind == CCR::Greater;
9416       auto Op = E->getOpcode();
9417       switch (Op) {
9418       default:
9419         llvm_unreachable("unsupported binary operator");
9420       case BO_EQ:
9421       case BO_NE:
9422         return Success(IsEqual == (Op == BO_EQ), E);
9423       case BO_LT: return Success(IsLess, E);
9424       case BO_GT: return Success(IsGreater, E);
9425       case BO_LE: return Success(IsEqual || IsLess, E);
9426       case BO_GE: return Success(IsEqual || IsGreater, E);
9427       }
9428     };
9429     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9430       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9431     });
9432   }
9433 
9434   QualType LHSTy = E->getLHS()->getType();
9435   QualType RHSTy = E->getRHS()->getType();
9436 
9437   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9438       E->getOpcode() == BO_Sub) {
9439     LValue LHSValue, RHSValue;
9440 
9441     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9442     if (!LHSOK && !Info.noteFailure())
9443       return false;
9444 
9445     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9446       return false;
9447 
9448     // Reject differing bases from the normal codepath; we special-case
9449     // comparisons to null.
9450     if (!HasSameBase(LHSValue, RHSValue)) {
9451       // Handle &&A - &&B.
9452       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9453         return Error(E);
9454       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9455       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9456       if (!LHSExpr || !RHSExpr)
9457         return Error(E);
9458       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9459       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9460       if (!LHSAddrExpr || !RHSAddrExpr)
9461         return Error(E);
9462       // Make sure both labels come from the same function.
9463       if (LHSAddrExpr->getLabel()->getDeclContext() !=
9464           RHSAddrExpr->getLabel()->getDeclContext())
9465         return Error(E);
9466       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9467     }
9468     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9469     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9470 
9471     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9472     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9473 
9474     // C++11 [expr.add]p6:
9475     //   Unless both pointers point to elements of the same array object, or
9476     //   one past the last element of the array object, the behavior is
9477     //   undefined.
9478     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9479         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9480                                 RHSDesignator))
9481       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9482 
9483     QualType Type = E->getLHS()->getType();
9484     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9485 
9486     CharUnits ElementSize;
9487     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9488       return false;
9489 
9490     // As an extension, a type may have zero size (empty struct or union in
9491     // C, array of zero length). Pointer subtraction in such cases has
9492     // undefined behavior, so is not constant.
9493     if (ElementSize.isZero()) {
9494       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9495           << ElementType;
9496       return false;
9497     }
9498 
9499     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9500     // and produce incorrect results when it overflows. Such behavior
9501     // appears to be non-conforming, but is common, so perhaps we should
9502     // assume the standard intended for such cases to be undefined behavior
9503     // and check for them.
9504 
9505     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9506     // overflow in the final conversion to ptrdiff_t.
9507     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9508     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9509     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9510                     false);
9511     APSInt TrueResult = (LHS - RHS) / ElemSize;
9512     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9513 
9514     if (Result.extend(65) != TrueResult &&
9515         !HandleOverflow(Info, E, TrueResult, E->getType()))
9516       return false;
9517     return Success(Result, E);
9518   }
9519 
9520   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9521 }
9522 
9523 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9524 /// a result as the expression's type.
9525 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9526                                     const UnaryExprOrTypeTraitExpr *E) {
9527   switch(E->getKind()) {
9528   case UETT_PreferredAlignOf:
9529   case UETT_AlignOf: {
9530     if (E->isArgumentType())
9531       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9532                      E);
9533     else
9534       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9535                      E);
9536   }
9537 
9538   case UETT_VecStep: {
9539     QualType Ty = E->getTypeOfArgument();
9540 
9541     if (Ty->isVectorType()) {
9542       unsigned n = Ty->castAs<VectorType>()->getNumElements();
9543 
9544       // The vec_step built-in functions that take a 3-component
9545       // vector return 4. (OpenCL 1.1 spec 6.11.12)
9546       if (n == 3)
9547         n = 4;
9548 
9549       return Success(n, E);
9550     } else
9551       return Success(1, E);
9552   }
9553 
9554   case UETT_SizeOf: {
9555     QualType SrcTy = E->getTypeOfArgument();
9556     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9557     //   the result is the size of the referenced type."
9558     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9559       SrcTy = Ref->getPointeeType();
9560 
9561     CharUnits Sizeof;
9562     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9563       return false;
9564     return Success(Sizeof, E);
9565   }
9566   case UETT_OpenMPRequiredSimdAlign:
9567     assert(E->isArgumentType());
9568     return Success(
9569         Info.Ctx.toCharUnitsFromBits(
9570                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9571             .getQuantity(),
9572         E);
9573   }
9574 
9575   llvm_unreachable("unknown expr/type trait");
9576 }
9577 
9578 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9579   CharUnits Result;
9580   unsigned n = OOE->getNumComponents();
9581   if (n == 0)
9582     return Error(OOE);
9583   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9584   for (unsigned i = 0; i != n; ++i) {
9585     OffsetOfNode ON = OOE->getComponent(i);
9586     switch (ON.getKind()) {
9587     case OffsetOfNode::Array: {
9588       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9589       APSInt IdxResult;
9590       if (!EvaluateInteger(Idx, IdxResult, Info))
9591         return false;
9592       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9593       if (!AT)
9594         return Error(OOE);
9595       CurrentType = AT->getElementType();
9596       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9597       Result += IdxResult.getSExtValue() * ElementSize;
9598       break;
9599     }
9600 
9601     case OffsetOfNode::Field: {
9602       FieldDecl *MemberDecl = ON.getField();
9603       const RecordType *RT = CurrentType->getAs<RecordType>();
9604       if (!RT)
9605         return Error(OOE);
9606       RecordDecl *RD = RT->getDecl();
9607       if (RD->isInvalidDecl()) return false;
9608       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9609       unsigned i = MemberDecl->getFieldIndex();
9610       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9611       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9612       CurrentType = MemberDecl->getType().getNonReferenceType();
9613       break;
9614     }
9615 
9616     case OffsetOfNode::Identifier:
9617       llvm_unreachable("dependent __builtin_offsetof");
9618 
9619     case OffsetOfNode::Base: {
9620       CXXBaseSpecifier *BaseSpec = ON.getBase();
9621       if (BaseSpec->isVirtual())
9622         return Error(OOE);
9623 
9624       // Find the layout of the class whose base we are looking into.
9625       const RecordType *RT = CurrentType->getAs<RecordType>();
9626       if (!RT)
9627         return Error(OOE);
9628       RecordDecl *RD = RT->getDecl();
9629       if (RD->isInvalidDecl()) return false;
9630       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9631 
9632       // Find the base class itself.
9633       CurrentType = BaseSpec->getType();
9634       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9635       if (!BaseRT)
9636         return Error(OOE);
9637 
9638       // Add the offset to the base.
9639       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9640       break;
9641     }
9642     }
9643   }
9644   return Success(Result, OOE);
9645 }
9646 
9647 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9648   switch (E->getOpcode()) {
9649   default:
9650     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9651     // See C99 6.6p3.
9652     return Error(E);
9653   case UO_Extension:
9654     // FIXME: Should extension allow i-c-e extension expressions in its scope?
9655     // If so, we could clear the diagnostic ID.
9656     return Visit(E->getSubExpr());
9657   case UO_Plus:
9658     // The result is just the value.
9659     return Visit(E->getSubExpr());
9660   case UO_Minus: {
9661     if (!Visit(E->getSubExpr()))
9662       return false;
9663     if (!Result.isInt()) return Error(E);
9664     const APSInt &Value = Result.getInt();
9665     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9666         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9667                         E->getType()))
9668       return false;
9669     return Success(-Value, E);
9670   }
9671   case UO_Not: {
9672     if (!Visit(E->getSubExpr()))
9673       return false;
9674     if (!Result.isInt()) return Error(E);
9675     return Success(~Result.getInt(), E);
9676   }
9677   case UO_LNot: {
9678     bool bres;
9679     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9680       return false;
9681     return Success(!bres, E);
9682   }
9683   }
9684 }
9685 
9686 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9687 /// result type is integer.
9688 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9689   const Expr *SubExpr = E->getSubExpr();
9690   QualType DestType = E->getType();
9691   QualType SrcType = SubExpr->getType();
9692 
9693   switch (E->getCastKind()) {
9694   case CK_BaseToDerived:
9695   case CK_DerivedToBase:
9696   case CK_UncheckedDerivedToBase:
9697   case CK_Dynamic:
9698   case CK_ToUnion:
9699   case CK_ArrayToPointerDecay:
9700   case CK_FunctionToPointerDecay:
9701   case CK_NullToPointer:
9702   case CK_NullToMemberPointer:
9703   case CK_BaseToDerivedMemberPointer:
9704   case CK_DerivedToBaseMemberPointer:
9705   case CK_ReinterpretMemberPointer:
9706   case CK_ConstructorConversion:
9707   case CK_IntegralToPointer:
9708   case CK_ToVoid:
9709   case CK_VectorSplat:
9710   case CK_IntegralToFloating:
9711   case CK_FloatingCast:
9712   case CK_CPointerToObjCPointerCast:
9713   case CK_BlockPointerToObjCPointerCast:
9714   case CK_AnyPointerToBlockPointerCast:
9715   case CK_ObjCObjectLValueCast:
9716   case CK_FloatingRealToComplex:
9717   case CK_FloatingComplexToReal:
9718   case CK_FloatingComplexCast:
9719   case CK_FloatingComplexToIntegralComplex:
9720   case CK_IntegralRealToComplex:
9721   case CK_IntegralComplexCast:
9722   case CK_IntegralComplexToFloatingComplex:
9723   case CK_BuiltinFnToFnPtr:
9724   case CK_ZeroToOCLOpaqueType:
9725   case CK_NonAtomicToAtomic:
9726   case CK_AddressSpaceConversion:
9727   case CK_IntToOCLSampler:
9728   case CK_FixedPointCast:
9729     llvm_unreachable("invalid cast kind for integral value");
9730 
9731   case CK_BitCast:
9732   case CK_Dependent:
9733   case CK_LValueBitCast:
9734   case CK_ARCProduceObject:
9735   case CK_ARCConsumeObject:
9736   case CK_ARCReclaimReturnedObject:
9737   case CK_ARCExtendBlockObject:
9738   case CK_CopyAndAutoreleaseBlockObject:
9739     return Error(E);
9740 
9741   case CK_UserDefinedConversion:
9742   case CK_LValueToRValue:
9743   case CK_AtomicToNonAtomic:
9744   case CK_NoOp:
9745     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9746 
9747   case CK_MemberPointerToBoolean:
9748   case CK_PointerToBoolean:
9749   case CK_IntegralToBoolean:
9750   case CK_FloatingToBoolean:
9751   case CK_BooleanToSignedIntegral:
9752   case CK_FloatingComplexToBoolean:
9753   case CK_IntegralComplexToBoolean: {
9754     bool BoolResult;
9755     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9756       return false;
9757     uint64_t IntResult = BoolResult;
9758     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9759       IntResult = (uint64_t)-1;
9760     return Success(IntResult, E);
9761   }
9762 
9763   case CK_FixedPointToBoolean: {
9764     // Unsigned padding does not affect this.
9765     APValue Val;
9766     if (!Evaluate(Val, Info, SubExpr))
9767       return false;
9768     return Success(Val.getInt().getBoolValue(), E);
9769   }
9770 
9771   case CK_IntegralCast: {
9772     if (!Visit(SubExpr))
9773       return false;
9774 
9775     if (!Result.isInt()) {
9776       // Allow casts of address-of-label differences if they are no-ops
9777       // or narrowing.  (The narrowing case isn't actually guaranteed to
9778       // be constant-evaluatable except in some narrow cases which are hard
9779       // to detect here.  We let it through on the assumption the user knows
9780       // what they are doing.)
9781       if (Result.isAddrLabelDiff())
9782         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9783       // Only allow casts of lvalues if they are lossless.
9784       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9785     }
9786 
9787     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9788                                       Result.getInt()), E);
9789   }
9790 
9791   case CK_PointerToIntegral: {
9792     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9793 
9794     LValue LV;
9795     if (!EvaluatePointer(SubExpr, LV, Info))
9796       return false;
9797 
9798     if (LV.getLValueBase()) {
9799       // Only allow based lvalue casts if they are lossless.
9800       // FIXME: Allow a larger integer size than the pointer size, and allow
9801       // narrowing back down to pointer width in subsequent integral casts.
9802       // FIXME: Check integer type's active bits, not its type size.
9803       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9804         return Error(E);
9805 
9806       LV.Designator.setInvalid();
9807       LV.moveInto(Result);
9808       return true;
9809     }
9810 
9811     uint64_t V;
9812     if (LV.isNullPointer())
9813       V = Info.Ctx.getTargetNullPointerValue(SrcType);
9814     else
9815       V = LV.getLValueOffset().getQuantity();
9816 
9817     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9818     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9819   }
9820 
9821   case CK_IntegralComplexToReal: {
9822     ComplexValue C;
9823     if (!EvaluateComplex(SubExpr, C, Info))
9824       return false;
9825     return Success(C.getComplexIntReal(), E);
9826   }
9827 
9828   case CK_FloatingToIntegral: {
9829     APFloat F(0.0);
9830     if (!EvaluateFloat(SubExpr, F, Info))
9831       return false;
9832 
9833     APSInt Value;
9834     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9835       return false;
9836     return Success(Value, E);
9837   }
9838   }
9839 
9840   llvm_unreachable("unknown cast resulting in integral value");
9841 }
9842 
9843 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9844   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9845     ComplexValue LV;
9846     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9847       return false;
9848     if (!LV.isComplexInt())
9849       return Error(E);
9850     return Success(LV.getComplexIntReal(), E);
9851   }
9852 
9853   return Visit(E->getSubExpr());
9854 }
9855 
9856 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9857   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9858     ComplexValue LV;
9859     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9860       return false;
9861     if (!LV.isComplexInt())
9862       return Error(E);
9863     return Success(LV.getComplexIntImag(), E);
9864   }
9865 
9866   VisitIgnoredValue(E->getSubExpr());
9867   return Success(0, E);
9868 }
9869 
9870 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9871   return Success(E->getPackLength(), E);
9872 }
9873 
9874 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9875   return Success(E->getValue(), E);
9876 }
9877 
9878 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9879   switch (E->getOpcode()) {
9880     default:
9881       // Invalid unary operators
9882       return Error(E);
9883     case UO_Plus:
9884       // The result is just the value.
9885       return Visit(E->getSubExpr());
9886     case UO_Minus: {
9887       if (!Visit(E->getSubExpr())) return false;
9888       if (!Result.isInt()) return Error(E);
9889       const APSInt &Value = Result.getInt();
9890       if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9891         SmallString<64> S;
9892         FixedPointValueToString(S, Value,
9893                                 Info.Ctx.getTypeInfo(E->getType()).Width);
9894         Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9895         if (Info.noteUndefinedBehavior()) return false;
9896       }
9897       return Success(-Value, E);
9898     }
9899     case UO_LNot: {
9900       bool bres;
9901       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9902         return false;
9903       return Success(!bres, E);
9904     }
9905   }
9906 }
9907 
9908 //===----------------------------------------------------------------------===//
9909 // Float Evaluation
9910 //===----------------------------------------------------------------------===//
9911 
9912 namespace {
9913 class FloatExprEvaluator
9914   : public ExprEvaluatorBase<FloatExprEvaluator> {
9915   APFloat &Result;
9916 public:
9917   FloatExprEvaluator(EvalInfo &info, APFloat &result)
9918     : ExprEvaluatorBaseTy(info), Result(result) {}
9919 
9920   bool Success(const APValue &V, const Expr *e) {
9921     Result = V.getFloat();
9922     return true;
9923   }
9924 
9925   bool ZeroInitialization(const Expr *E) {
9926     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9927     return true;
9928   }
9929 
9930   bool VisitCallExpr(const CallExpr *E);
9931 
9932   bool VisitUnaryOperator(const UnaryOperator *E);
9933   bool VisitBinaryOperator(const BinaryOperator *E);
9934   bool VisitFloatingLiteral(const FloatingLiteral *E);
9935   bool VisitCastExpr(const CastExpr *E);
9936 
9937   bool VisitUnaryReal(const UnaryOperator *E);
9938   bool VisitUnaryImag(const UnaryOperator *E);
9939 
9940   // FIXME: Missing: array subscript of vector, member of vector
9941 };
9942 } // end anonymous namespace
9943 
9944 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9945   assert(E->isRValue() && E->getType()->isRealFloatingType());
9946   return FloatExprEvaluator(Info, Result).Visit(E);
9947 }
9948 
9949 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9950                                   QualType ResultTy,
9951                                   const Expr *Arg,
9952                                   bool SNaN,
9953                                   llvm::APFloat &Result) {
9954   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9955   if (!S) return false;
9956 
9957   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9958 
9959   llvm::APInt fill;
9960 
9961   // Treat empty strings as if they were zero.
9962   if (S->getString().empty())
9963     fill = llvm::APInt(32, 0);
9964   else if (S->getString().getAsInteger(0, fill))
9965     return false;
9966 
9967   if (Context.getTargetInfo().isNan2008()) {
9968     if (SNaN)
9969       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9970     else
9971       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9972   } else {
9973     // Prior to IEEE 754-2008, architectures were allowed to choose whether
9974     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9975     // a different encoding to what became a standard in 2008, and for pre-
9976     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9977     // sNaN. This is now known as "legacy NaN" encoding.
9978     if (SNaN)
9979       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9980     else
9981       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9982   }
9983 
9984   return true;
9985 }
9986 
9987 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9988   switch (E->getBuiltinCallee()) {
9989   default:
9990     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9991 
9992   case Builtin::BI__builtin_huge_val:
9993   case Builtin::BI__builtin_huge_valf:
9994   case Builtin::BI__builtin_huge_vall:
9995   case Builtin::BI__builtin_huge_valf128:
9996   case Builtin::BI__builtin_inf:
9997   case Builtin::BI__builtin_inff:
9998   case Builtin::BI__builtin_infl:
9999   case Builtin::BI__builtin_inff128: {
10000     const llvm::fltSemantics &Sem =
10001       Info.Ctx.getFloatTypeSemantics(E->getType());
10002     Result = llvm::APFloat::getInf(Sem);
10003     return true;
10004   }
10005 
10006   case Builtin::BI__builtin_nans:
10007   case Builtin::BI__builtin_nansf:
10008   case Builtin::BI__builtin_nansl:
10009   case Builtin::BI__builtin_nansf128:
10010     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10011                                true, Result))
10012       return Error(E);
10013     return true;
10014 
10015   case Builtin::BI__builtin_nan:
10016   case Builtin::BI__builtin_nanf:
10017   case Builtin::BI__builtin_nanl:
10018   case Builtin::BI__builtin_nanf128:
10019     // If this is __builtin_nan() turn this into a nan, otherwise we
10020     // can't constant fold it.
10021     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10022                                false, Result))
10023       return Error(E);
10024     return true;
10025 
10026   case Builtin::BI__builtin_fabs:
10027   case Builtin::BI__builtin_fabsf:
10028   case Builtin::BI__builtin_fabsl:
10029   case Builtin::BI__builtin_fabsf128:
10030     if (!EvaluateFloat(E->getArg(0), Result, Info))
10031       return false;
10032 
10033     if (Result.isNegative())
10034       Result.changeSign();
10035     return true;
10036 
10037   // FIXME: Builtin::BI__builtin_powi
10038   // FIXME: Builtin::BI__builtin_powif
10039   // FIXME: Builtin::BI__builtin_powil
10040 
10041   case Builtin::BI__builtin_copysign:
10042   case Builtin::BI__builtin_copysignf:
10043   case Builtin::BI__builtin_copysignl:
10044   case Builtin::BI__builtin_copysignf128: {
10045     APFloat RHS(0.);
10046     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10047         !EvaluateFloat(E->getArg(1), RHS, Info))
10048       return false;
10049     Result.copySign(RHS);
10050     return true;
10051   }
10052   }
10053 }
10054 
10055 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10056   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10057     ComplexValue CV;
10058     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10059       return false;
10060     Result = CV.FloatReal;
10061     return true;
10062   }
10063 
10064   return Visit(E->getSubExpr());
10065 }
10066 
10067 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10068   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10069     ComplexValue CV;
10070     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10071       return false;
10072     Result = CV.FloatImag;
10073     return true;
10074   }
10075 
10076   VisitIgnoredValue(E->getSubExpr());
10077   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10078   Result = llvm::APFloat::getZero(Sem);
10079   return true;
10080 }
10081 
10082 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10083   switch (E->getOpcode()) {
10084   default: return Error(E);
10085   case UO_Plus:
10086     return EvaluateFloat(E->getSubExpr(), Result, Info);
10087   case UO_Minus:
10088     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10089       return false;
10090     Result.changeSign();
10091     return true;
10092   }
10093 }
10094 
10095 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10096   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10097     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10098 
10099   APFloat RHS(0.0);
10100   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
10101   if (!LHSOK && !Info.noteFailure())
10102     return false;
10103   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10104          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
10105 }
10106 
10107 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10108   Result = E->getValue();
10109   return true;
10110 }
10111 
10112 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10113   const Expr* SubExpr = E->getSubExpr();
10114 
10115   switch (E->getCastKind()) {
10116   default:
10117     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10118 
10119   case CK_IntegralToFloating: {
10120     APSInt IntResult;
10121     return EvaluateInteger(SubExpr, IntResult, Info) &&
10122            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10123                                 E->getType(), Result);
10124   }
10125 
10126   case CK_FloatingCast: {
10127     if (!Visit(SubExpr))
10128       return false;
10129     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10130                                   Result);
10131   }
10132 
10133   case CK_FloatingComplexToReal: {
10134     ComplexValue V;
10135     if (!EvaluateComplex(SubExpr, V, Info))
10136       return false;
10137     Result = V.getComplexFloatReal();
10138     return true;
10139   }
10140   }
10141 }
10142 
10143 //===----------------------------------------------------------------------===//
10144 // Complex Evaluation (for float and integer)
10145 //===----------------------------------------------------------------------===//
10146 
10147 namespace {
10148 class ComplexExprEvaluator
10149   : public ExprEvaluatorBase<ComplexExprEvaluator> {
10150   ComplexValue &Result;
10151 
10152 public:
10153   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
10154     : ExprEvaluatorBaseTy(info), Result(Result) {}
10155 
10156   bool Success(const APValue &V, const Expr *e) {
10157     Result.setFrom(V);
10158     return true;
10159   }
10160 
10161   bool ZeroInitialization(const Expr *E);
10162 
10163   //===--------------------------------------------------------------------===//
10164   //                            Visitor Methods
10165   //===--------------------------------------------------------------------===//
10166 
10167   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
10168   bool VisitCastExpr(const CastExpr *E);
10169   bool VisitBinaryOperator(const BinaryOperator *E);
10170   bool VisitUnaryOperator(const UnaryOperator *E);
10171   bool VisitInitListExpr(const InitListExpr *E);
10172 };
10173 } // end anonymous namespace
10174 
10175 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10176                             EvalInfo &Info) {
10177   assert(E->isRValue() && E->getType()->isAnyComplexType());
10178   return ComplexExprEvaluator(Info, Result).Visit(E);
10179 }
10180 
10181 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10182   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10183   if (ElemTy->isRealFloatingType()) {
10184     Result.makeComplexFloat();
10185     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10186     Result.FloatReal = Zero;
10187     Result.FloatImag = Zero;
10188   } else {
10189     Result.makeComplexInt();
10190     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10191     Result.IntReal = Zero;
10192     Result.IntImag = Zero;
10193   }
10194   return true;
10195 }
10196 
10197 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10198   const Expr* SubExpr = E->getSubExpr();
10199 
10200   if (SubExpr->getType()->isRealFloatingType()) {
10201     Result.makeComplexFloat();
10202     APFloat &Imag = Result.FloatImag;
10203     if (!EvaluateFloat(SubExpr, Imag, Info))
10204       return false;
10205 
10206     Result.FloatReal = APFloat(Imag.getSemantics());
10207     return true;
10208   } else {
10209     assert(SubExpr->getType()->isIntegerType() &&
10210            "Unexpected imaginary literal.");
10211 
10212     Result.makeComplexInt();
10213     APSInt &Imag = Result.IntImag;
10214     if (!EvaluateInteger(SubExpr, Imag, Info))
10215       return false;
10216 
10217     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10218     return true;
10219   }
10220 }
10221 
10222 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10223 
10224   switch (E->getCastKind()) {
10225   case CK_BitCast:
10226   case CK_BaseToDerived:
10227   case CK_DerivedToBase:
10228   case CK_UncheckedDerivedToBase:
10229   case CK_Dynamic:
10230   case CK_ToUnion:
10231   case CK_ArrayToPointerDecay:
10232   case CK_FunctionToPointerDecay:
10233   case CK_NullToPointer:
10234   case CK_NullToMemberPointer:
10235   case CK_BaseToDerivedMemberPointer:
10236   case CK_DerivedToBaseMemberPointer:
10237   case CK_MemberPointerToBoolean:
10238   case CK_ReinterpretMemberPointer:
10239   case CK_ConstructorConversion:
10240   case CK_IntegralToPointer:
10241   case CK_PointerToIntegral:
10242   case CK_PointerToBoolean:
10243   case CK_ToVoid:
10244   case CK_VectorSplat:
10245   case CK_IntegralCast:
10246   case CK_BooleanToSignedIntegral:
10247   case CK_IntegralToBoolean:
10248   case CK_IntegralToFloating:
10249   case CK_FloatingToIntegral:
10250   case CK_FloatingToBoolean:
10251   case CK_FloatingCast:
10252   case CK_CPointerToObjCPointerCast:
10253   case CK_BlockPointerToObjCPointerCast:
10254   case CK_AnyPointerToBlockPointerCast:
10255   case CK_ObjCObjectLValueCast:
10256   case CK_FloatingComplexToReal:
10257   case CK_FloatingComplexToBoolean:
10258   case CK_IntegralComplexToReal:
10259   case CK_IntegralComplexToBoolean:
10260   case CK_ARCProduceObject:
10261   case CK_ARCConsumeObject:
10262   case CK_ARCReclaimReturnedObject:
10263   case CK_ARCExtendBlockObject:
10264   case CK_CopyAndAutoreleaseBlockObject:
10265   case CK_BuiltinFnToFnPtr:
10266   case CK_ZeroToOCLOpaqueType:
10267   case CK_NonAtomicToAtomic:
10268   case CK_AddressSpaceConversion:
10269   case CK_IntToOCLSampler:
10270   case CK_FixedPointCast:
10271   case CK_FixedPointToBoolean:
10272     llvm_unreachable("invalid cast kind for complex value");
10273 
10274   case CK_LValueToRValue:
10275   case CK_AtomicToNonAtomic:
10276   case CK_NoOp:
10277     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10278 
10279   case CK_Dependent:
10280   case CK_LValueBitCast:
10281   case CK_UserDefinedConversion:
10282     return Error(E);
10283 
10284   case CK_FloatingRealToComplex: {
10285     APFloat &Real = Result.FloatReal;
10286     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
10287       return false;
10288 
10289     Result.makeComplexFloat();
10290     Result.FloatImag = APFloat(Real.getSemantics());
10291     return true;
10292   }
10293 
10294   case CK_FloatingComplexCast: {
10295     if (!Visit(E->getSubExpr()))
10296       return false;
10297 
10298     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10299     QualType From
10300       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10301 
10302     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10303            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
10304   }
10305 
10306   case CK_FloatingComplexToIntegralComplex: {
10307     if (!Visit(E->getSubExpr()))
10308       return false;
10309 
10310     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10311     QualType From
10312       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10313     Result.makeComplexInt();
10314     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10315                                 To, Result.IntReal) &&
10316            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10317                                 To, Result.IntImag);
10318   }
10319 
10320   case CK_IntegralRealToComplex: {
10321     APSInt &Real = Result.IntReal;
10322     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10323       return false;
10324 
10325     Result.makeComplexInt();
10326     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10327     return true;
10328   }
10329 
10330   case CK_IntegralComplexCast: {
10331     if (!Visit(E->getSubExpr()))
10332       return false;
10333 
10334     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10335     QualType From
10336       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10337 
10338     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10339     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10340     return true;
10341   }
10342 
10343   case CK_IntegralComplexToFloatingComplex: {
10344     if (!Visit(E->getSubExpr()))
10345       return false;
10346 
10347     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10348     QualType From
10349       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10350     Result.makeComplexFloat();
10351     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10352                                 To, Result.FloatReal) &&
10353            HandleIntToFloatCast(Info, E, From, Result.IntImag,
10354                                 To, Result.FloatImag);
10355   }
10356   }
10357 
10358   llvm_unreachable("unknown cast resulting in complex value");
10359 }
10360 
10361 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10362   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10363     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10364 
10365   // Track whether the LHS or RHS is real at the type system level. When this is
10366   // the case we can simplify our evaluation strategy.
10367   bool LHSReal = false, RHSReal = false;
10368 
10369   bool LHSOK;
10370   if (E->getLHS()->getType()->isRealFloatingType()) {
10371     LHSReal = true;
10372     APFloat &Real = Result.FloatReal;
10373     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10374     if (LHSOK) {
10375       Result.makeComplexFloat();
10376       Result.FloatImag = APFloat(Real.getSemantics());
10377     }
10378   } else {
10379     LHSOK = Visit(E->getLHS());
10380   }
10381   if (!LHSOK && !Info.noteFailure())
10382     return false;
10383 
10384   ComplexValue RHS;
10385   if (E->getRHS()->getType()->isRealFloatingType()) {
10386     RHSReal = true;
10387     APFloat &Real = RHS.FloatReal;
10388     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10389       return false;
10390     RHS.makeComplexFloat();
10391     RHS.FloatImag = APFloat(Real.getSemantics());
10392   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10393     return false;
10394 
10395   assert(!(LHSReal && RHSReal) &&
10396          "Cannot have both operands of a complex operation be real.");
10397   switch (E->getOpcode()) {
10398   default: return Error(E);
10399   case BO_Add:
10400     if (Result.isComplexFloat()) {
10401       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10402                                        APFloat::rmNearestTiesToEven);
10403       if (LHSReal)
10404         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10405       else if (!RHSReal)
10406         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10407                                          APFloat::rmNearestTiesToEven);
10408     } else {
10409       Result.getComplexIntReal() += RHS.getComplexIntReal();
10410       Result.getComplexIntImag() += RHS.getComplexIntImag();
10411     }
10412     break;
10413   case BO_Sub:
10414     if (Result.isComplexFloat()) {
10415       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10416                                             APFloat::rmNearestTiesToEven);
10417       if (LHSReal) {
10418         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10419         Result.getComplexFloatImag().changeSign();
10420       } else if (!RHSReal) {
10421         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10422                                               APFloat::rmNearestTiesToEven);
10423       }
10424     } else {
10425       Result.getComplexIntReal() -= RHS.getComplexIntReal();
10426       Result.getComplexIntImag() -= RHS.getComplexIntImag();
10427     }
10428     break;
10429   case BO_Mul:
10430     if (Result.isComplexFloat()) {
10431       // This is an implementation of complex multiplication according to the
10432       // constraints laid out in C11 Annex G. The implementation uses the
10433       // following naming scheme:
10434       //   (a + ib) * (c + id)
10435       ComplexValue LHS = Result;
10436       APFloat &A = LHS.getComplexFloatReal();
10437       APFloat &B = LHS.getComplexFloatImag();
10438       APFloat &C = RHS.getComplexFloatReal();
10439       APFloat &D = RHS.getComplexFloatImag();
10440       APFloat &ResR = Result.getComplexFloatReal();
10441       APFloat &ResI = Result.getComplexFloatImag();
10442       if (LHSReal) {
10443         assert(!RHSReal && "Cannot have two real operands for a complex op!");
10444         ResR = A * C;
10445         ResI = A * D;
10446       } else if (RHSReal) {
10447         ResR = C * A;
10448         ResI = C * B;
10449       } else {
10450         // In the fully general case, we need to handle NaNs and infinities
10451         // robustly.
10452         APFloat AC = A * C;
10453         APFloat BD = B * D;
10454         APFloat AD = A * D;
10455         APFloat BC = B * C;
10456         ResR = AC - BD;
10457         ResI = AD + BC;
10458         if (ResR.isNaN() && ResI.isNaN()) {
10459           bool Recalc = false;
10460           if (A.isInfinity() || B.isInfinity()) {
10461             A = APFloat::copySign(
10462                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10463             B = APFloat::copySign(
10464                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10465             if (C.isNaN())
10466               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10467             if (D.isNaN())
10468               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10469             Recalc = true;
10470           }
10471           if (C.isInfinity() || D.isInfinity()) {
10472             C = APFloat::copySign(
10473                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10474             D = APFloat::copySign(
10475                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10476             if (A.isNaN())
10477               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10478             if (B.isNaN())
10479               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10480             Recalc = true;
10481           }
10482           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10483                           AD.isInfinity() || BC.isInfinity())) {
10484             if (A.isNaN())
10485               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10486             if (B.isNaN())
10487               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10488             if (C.isNaN())
10489               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10490             if (D.isNaN())
10491               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10492             Recalc = true;
10493           }
10494           if (Recalc) {
10495             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10496             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10497           }
10498         }
10499       }
10500     } else {
10501       ComplexValue LHS = Result;
10502       Result.getComplexIntReal() =
10503         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10504          LHS.getComplexIntImag() * RHS.getComplexIntImag());
10505       Result.getComplexIntImag() =
10506         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10507          LHS.getComplexIntImag() * RHS.getComplexIntReal());
10508     }
10509     break;
10510   case BO_Div:
10511     if (Result.isComplexFloat()) {
10512       // This is an implementation of complex division according to the
10513       // constraints laid out in C11 Annex G. The implementation uses the
10514       // following naming scheme:
10515       //   (a + ib) / (c + id)
10516       ComplexValue LHS = Result;
10517       APFloat &A = LHS.getComplexFloatReal();
10518       APFloat &B = LHS.getComplexFloatImag();
10519       APFloat &C = RHS.getComplexFloatReal();
10520       APFloat &D = RHS.getComplexFloatImag();
10521       APFloat &ResR = Result.getComplexFloatReal();
10522       APFloat &ResI = Result.getComplexFloatImag();
10523       if (RHSReal) {
10524         ResR = A / C;
10525         ResI = B / C;
10526       } else {
10527         if (LHSReal) {
10528           // No real optimizations we can do here, stub out with zero.
10529           B = APFloat::getZero(A.getSemantics());
10530         }
10531         int DenomLogB = 0;
10532         APFloat MaxCD = maxnum(abs(C), abs(D));
10533         if (MaxCD.isFinite()) {
10534           DenomLogB = ilogb(MaxCD);
10535           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10536           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10537         }
10538         APFloat Denom = C * C + D * D;
10539         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10540                       APFloat::rmNearestTiesToEven);
10541         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10542                       APFloat::rmNearestTiesToEven);
10543         if (ResR.isNaN() && ResI.isNaN()) {
10544           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10545             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10546             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10547           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10548                      D.isFinite()) {
10549             A = APFloat::copySign(
10550                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10551             B = APFloat::copySign(
10552                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10553             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10554             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10555           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10556             C = APFloat::copySign(
10557                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10558             D = APFloat::copySign(
10559                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10560             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10561             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10562           }
10563         }
10564       }
10565     } else {
10566       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10567         return Error(E, diag::note_expr_divide_by_zero);
10568 
10569       ComplexValue LHS = Result;
10570       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10571         RHS.getComplexIntImag() * RHS.getComplexIntImag();
10572       Result.getComplexIntReal() =
10573         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10574          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10575       Result.getComplexIntImag() =
10576         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10577          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10578     }
10579     break;
10580   }
10581 
10582   return true;
10583 }
10584 
10585 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10586   // Get the operand value into 'Result'.
10587   if (!Visit(E->getSubExpr()))
10588     return false;
10589 
10590   switch (E->getOpcode()) {
10591   default:
10592     return Error(E);
10593   case UO_Extension:
10594     return true;
10595   case UO_Plus:
10596     // The result is always just the subexpr.
10597     return true;
10598   case UO_Minus:
10599     if (Result.isComplexFloat()) {
10600       Result.getComplexFloatReal().changeSign();
10601       Result.getComplexFloatImag().changeSign();
10602     }
10603     else {
10604       Result.getComplexIntReal() = -Result.getComplexIntReal();
10605       Result.getComplexIntImag() = -Result.getComplexIntImag();
10606     }
10607     return true;
10608   case UO_Not:
10609     if (Result.isComplexFloat())
10610       Result.getComplexFloatImag().changeSign();
10611     else
10612       Result.getComplexIntImag() = -Result.getComplexIntImag();
10613     return true;
10614   }
10615 }
10616 
10617 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10618   if (E->getNumInits() == 2) {
10619     if (E->getType()->isComplexType()) {
10620       Result.makeComplexFloat();
10621       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10622         return false;
10623       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10624         return false;
10625     } else {
10626       Result.makeComplexInt();
10627       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10628         return false;
10629       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10630         return false;
10631     }
10632     return true;
10633   }
10634   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10635 }
10636 
10637 //===----------------------------------------------------------------------===//
10638 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10639 // implicit conversion.
10640 //===----------------------------------------------------------------------===//
10641 
10642 namespace {
10643 class AtomicExprEvaluator :
10644     public ExprEvaluatorBase<AtomicExprEvaluator> {
10645   const LValue *This;
10646   APValue &Result;
10647 public:
10648   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10649       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10650 
10651   bool Success(const APValue &V, const Expr *E) {
10652     Result = V;
10653     return true;
10654   }
10655 
10656   bool ZeroInitialization(const Expr *E) {
10657     ImplicitValueInitExpr VIE(
10658         E->getType()->castAs<AtomicType>()->getValueType());
10659     // For atomic-qualified class (and array) types in C++, initialize the
10660     // _Atomic-wrapped subobject directly, in-place.
10661     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10662                 : Evaluate(Result, Info, &VIE);
10663   }
10664 
10665   bool VisitCastExpr(const CastExpr *E) {
10666     switch (E->getCastKind()) {
10667     default:
10668       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10669     case CK_NonAtomicToAtomic:
10670       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10671                   : Evaluate(Result, Info, E->getSubExpr());
10672     }
10673   }
10674 };
10675 } // end anonymous namespace
10676 
10677 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10678                            EvalInfo &Info) {
10679   assert(E->isRValue() && E->getType()->isAtomicType());
10680   return AtomicExprEvaluator(Info, This, Result).Visit(E);
10681 }
10682 
10683 //===----------------------------------------------------------------------===//
10684 // Void expression evaluation, primarily for a cast to void on the LHS of a
10685 // comma operator
10686 //===----------------------------------------------------------------------===//
10687 
10688 namespace {
10689 class VoidExprEvaluator
10690   : public ExprEvaluatorBase<VoidExprEvaluator> {
10691 public:
10692   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10693 
10694   bool Success(const APValue &V, const Expr *e) { return true; }
10695 
10696   bool ZeroInitialization(const Expr *E) { return true; }
10697 
10698   bool VisitCastExpr(const CastExpr *E) {
10699     switch (E->getCastKind()) {
10700     default:
10701       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10702     case CK_ToVoid:
10703       VisitIgnoredValue(E->getSubExpr());
10704       return true;
10705     }
10706   }
10707 
10708   bool VisitCallExpr(const CallExpr *E) {
10709     switch (E->getBuiltinCallee()) {
10710     default:
10711       return ExprEvaluatorBaseTy::VisitCallExpr(E);
10712     case Builtin::BI__assume:
10713     case Builtin::BI__builtin_assume:
10714       // The argument is not evaluated!
10715       return true;
10716     }
10717   }
10718 };
10719 } // end anonymous namespace
10720 
10721 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10722   assert(E->isRValue() && E->getType()->isVoidType());
10723   return VoidExprEvaluator(Info).Visit(E);
10724 }
10725 
10726 //===----------------------------------------------------------------------===//
10727 // Top level Expr::EvaluateAsRValue method.
10728 //===----------------------------------------------------------------------===//
10729 
10730 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10731   // In C, function designators are not lvalues, but we evaluate them as if they
10732   // are.
10733   QualType T = E->getType();
10734   if (E->isGLValue() || T->isFunctionType()) {
10735     LValue LV;
10736     if (!EvaluateLValue(E, LV, Info))
10737       return false;
10738     LV.moveInto(Result);
10739   } else if (T->isVectorType()) {
10740     if (!EvaluateVector(E, Result, Info))
10741       return false;
10742   } else if (T->isIntegralOrEnumerationType()) {
10743     if (!IntExprEvaluator(Info, Result).Visit(E))
10744       return false;
10745   } else if (T->hasPointerRepresentation()) {
10746     LValue LV;
10747     if (!EvaluatePointer(E, LV, Info))
10748       return false;
10749     LV.moveInto(Result);
10750   } else if (T->isRealFloatingType()) {
10751     llvm::APFloat F(0.0);
10752     if (!EvaluateFloat(E, F, Info))
10753       return false;
10754     Result = APValue(F);
10755   } else if (T->isAnyComplexType()) {
10756     ComplexValue C;
10757     if (!EvaluateComplex(E, C, Info))
10758       return false;
10759     C.moveInto(Result);
10760   } else if (T->isFixedPointType()) {
10761     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10762   } else if (T->isMemberPointerType()) {
10763     MemberPtr P;
10764     if (!EvaluateMemberPointer(E, P, Info))
10765       return false;
10766     P.moveInto(Result);
10767     return true;
10768   } else if (T->isArrayType()) {
10769     LValue LV;
10770     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10771     if (!EvaluateArray(E, LV, Value, Info))
10772       return false;
10773     Result = Value;
10774   } else if (T->isRecordType()) {
10775     LValue LV;
10776     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10777     if (!EvaluateRecord(E, LV, Value, Info))
10778       return false;
10779     Result = Value;
10780   } else if (T->isVoidType()) {
10781     if (!Info.getLangOpts().CPlusPlus11)
10782       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10783         << E->getType();
10784     if (!EvaluateVoid(E, Info))
10785       return false;
10786   } else if (T->isAtomicType()) {
10787     QualType Unqual = T.getAtomicUnqualifiedType();
10788     if (Unqual->isArrayType() || Unqual->isRecordType()) {
10789       LValue LV;
10790       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10791       if (!EvaluateAtomic(E, &LV, Value, Info))
10792         return false;
10793     } else {
10794       if (!EvaluateAtomic(E, nullptr, Result, Info))
10795         return false;
10796     }
10797   } else if (Info.getLangOpts().CPlusPlus11) {
10798     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10799     return false;
10800   } else {
10801     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10802     return false;
10803   }
10804 
10805   return true;
10806 }
10807 
10808 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10809 /// cases, the in-place evaluation is essential, since later initializers for
10810 /// an object can indirectly refer to subobjects which were initialized earlier.
10811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10812                             const Expr *E, bool AllowNonLiteralTypes) {
10813   assert(!E->isValueDependent());
10814 
10815   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10816     return false;
10817 
10818   if (E->isRValue()) {
10819     // Evaluate arrays and record types in-place, so that later initializers can
10820     // refer to earlier-initialized members of the object.
10821     QualType T = E->getType();
10822     if (T->isArrayType())
10823       return EvaluateArray(E, This, Result, Info);
10824     else if (T->isRecordType())
10825       return EvaluateRecord(E, This, Result, Info);
10826     else if (T->isAtomicType()) {
10827       QualType Unqual = T.getAtomicUnqualifiedType();
10828       if (Unqual->isArrayType() || Unqual->isRecordType())
10829         return EvaluateAtomic(E, &This, Result, Info);
10830     }
10831   }
10832 
10833   // For any other type, in-place evaluation is unimportant.
10834   return Evaluate(Result, Info, E);
10835 }
10836 
10837 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10838 /// lvalue-to-rvalue cast if it is an lvalue.
10839 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10840   if (E->getType().isNull())
10841     return false;
10842 
10843   if (!CheckLiteralType(Info, E))
10844     return false;
10845 
10846   if (!::Evaluate(Result, Info, E))
10847     return false;
10848 
10849   if (E->isGLValue()) {
10850     LValue LV;
10851     LV.setFrom(Info.Ctx, Result);
10852     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10853       return false;
10854   }
10855 
10856   // Check this core constant expression is a constant expression.
10857   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10858 }
10859 
10860 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10861                                  const ASTContext &Ctx, bool &IsConst) {
10862   // Fast-path evaluations of integer literals, since we sometimes see files
10863   // containing vast quantities of these.
10864   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10865     Result.Val = APValue(APSInt(L->getValue(),
10866                                 L->getType()->isUnsignedIntegerType()));
10867     IsConst = true;
10868     return true;
10869   }
10870 
10871   // This case should be rare, but we need to check it before we check on
10872   // the type below.
10873   if (Exp->getType().isNull()) {
10874     IsConst = false;
10875     return true;
10876   }
10877 
10878   // FIXME: Evaluating values of large array and record types can cause
10879   // performance problems. Only do so in C++11 for now.
10880   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10881                           Exp->getType()->isRecordType()) &&
10882       !Ctx.getLangOpts().CPlusPlus11) {
10883     IsConst = false;
10884     return true;
10885   }
10886   return false;
10887 }
10888 
10889 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10890                                       Expr::SideEffectsKind SEK) {
10891   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10892          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10893 }
10894 
10895 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10896                              const ASTContext &Ctx, EvalInfo &Info) {
10897   bool IsConst;
10898   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10899     return IsConst;
10900 
10901   return EvaluateAsRValue(Info, E, Result.Val);
10902 }
10903 
10904 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10905                           const ASTContext &Ctx,
10906                           Expr::SideEffectsKind AllowSideEffects,
10907                           EvalInfo &Info) {
10908   if (!E->getType()->isIntegralOrEnumerationType())
10909     return false;
10910 
10911   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
10912       !ExprResult.Val.isInt() ||
10913       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10914     return false;
10915 
10916   return true;
10917 }
10918 
10919 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10920 /// any crazy technique (that has nothing to do with language standards) that
10921 /// we want to.  If this function returns true, it returns the folded constant
10922 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10923 /// will be applied to the result.
10924 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
10925                             bool InConstantContext) const {
10926   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10927   Info.InConstantContext = InConstantContext;
10928   return ::EvaluateAsRValue(this, Result, Ctx, Info);
10929 }
10930 
10931 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10932                                       const ASTContext &Ctx) const {
10933   EvalResult Scratch;
10934   return EvaluateAsRValue(Scratch, Ctx) &&
10935          HandleConversionToBool(Scratch.Val, Result);
10936 }
10937 
10938 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
10939                          SideEffectsKind AllowSideEffects) const {
10940   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10941   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
10942 }
10943 
10944 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10945                            SideEffectsKind AllowSideEffects) const {
10946   if (!getType()->isRealFloatingType())
10947     return false;
10948 
10949   EvalResult ExprResult;
10950   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10951       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10952     return false;
10953 
10954   Result = ExprResult.Val.getFloat();
10955   return true;
10956 }
10957 
10958 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10959   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10960 
10961   LValue LV;
10962   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10963       !CheckLValueConstantExpression(Info, getExprLoc(),
10964                                      Ctx.getLValueReferenceType(getType()), LV,
10965                                      Expr::EvaluateForCodeGen))
10966     return false;
10967 
10968   LV.moveInto(Result.Val);
10969   return true;
10970 }
10971 
10972 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10973                                   const ASTContext &Ctx) const {
10974   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10975   EvalInfo Info(Ctx, Result, EM);
10976   if (!::Evaluate(Result.Val, Info, this))
10977     return false;
10978 
10979   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10980                                  Usage);
10981 }
10982 
10983 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10984                                  const VarDecl *VD,
10985                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10986   // FIXME: Evaluating initializers for large array and record types can cause
10987   // performance problems. Only do so in C++11 for now.
10988   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10989       !Ctx.getLangOpts().CPlusPlus11)
10990     return false;
10991 
10992   Expr::EvalStatus EStatus;
10993   EStatus.Diag = &Notes;
10994 
10995   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10996                                       ? EvalInfo::EM_ConstantExpression
10997                                       : EvalInfo::EM_ConstantFold);
10998   InitInfo.setEvaluatingDecl(VD, Value);
10999   InitInfo.InConstantContext = true;
11000 
11001   LValue LVal;
11002   LVal.set(VD);
11003 
11004   // C++11 [basic.start.init]p2:
11005   //  Variables with static storage duration or thread storage duration shall be
11006   //  zero-initialized before any other initialization takes place.
11007   // This behavior is not present in C.
11008   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
11009       !VD->getType()->isReferenceType()) {
11010     ImplicitValueInitExpr VIE(VD->getType());
11011     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
11012                          /*AllowNonLiteralTypes=*/true))
11013       return false;
11014   }
11015 
11016   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11017                        /*AllowNonLiteralTypes=*/true) ||
11018       EStatus.HasSideEffects)
11019     return false;
11020 
11021   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11022                                  Value);
11023 }
11024 
11025 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11026 /// constant folded, but discard the result.
11027 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
11028   EvalResult Result;
11029   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
11030          !hasUnacceptableSideEffect(Result, SEK);
11031 }
11032 
11033 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
11034                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11035   EvalResult EVResult;
11036   EVResult.Diag = Diag;
11037   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11038   Info.InConstantContext = true;
11039 
11040   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
11041   (void)Result;
11042   assert(Result && "Could not evaluate expression");
11043   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11044 
11045   return EVResult.Val.getInt();
11046 }
11047 
11048 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11049     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11050   EvalResult EVResult;
11051   EVResult.Diag = Diag;
11052   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11053   Info.InConstantContext = true;
11054 
11055   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
11056   (void)Result;
11057   assert(Result && "Could not evaluate expression");
11058   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11059 
11060   return EVResult.Val.getInt();
11061 }
11062 
11063 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
11064   bool IsConst;
11065   EvalResult EVResult;
11066   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11067     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11068     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
11069   }
11070 }
11071 
11072 bool Expr::EvalResult::isGlobalLValue() const {
11073   assert(Val.isLValue());
11074   return IsGlobalLValue(Val.getLValueBase());
11075 }
11076 
11077 
11078 /// isIntegerConstantExpr - this recursive routine will test if an expression is
11079 /// an integer constant expression.
11080 
11081 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11082 /// comma, etc
11083 
11084 // CheckICE - This function does the fundamental ICE checking: the returned
11085 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11086 // and a (possibly null) SourceLocation indicating the location of the problem.
11087 //
11088 // Note that to reduce code duplication, this helper does no evaluation
11089 // itself; the caller checks whether the expression is evaluatable, and
11090 // in the rare cases where CheckICE actually cares about the evaluated
11091 // value, it calls into Evaluate.
11092 
11093 namespace {
11094 
11095 enum ICEKind {
11096   /// This expression is an ICE.
11097   IK_ICE,
11098   /// This expression is not an ICE, but if it isn't evaluated, it's
11099   /// a legal subexpression for an ICE. This return value is used to handle
11100   /// the comma operator in C99 mode, and non-constant subexpressions.
11101   IK_ICEIfUnevaluated,
11102   /// This expression is not an ICE, and is not a legal subexpression for one.
11103   IK_NotICE
11104 };
11105 
11106 struct ICEDiag {
11107   ICEKind Kind;
11108   SourceLocation Loc;
11109 
11110   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
11111 };
11112 
11113 }
11114 
11115 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11116 
11117 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
11118 
11119 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
11120   Expr::EvalResult EVResult;
11121   Expr::EvalStatus Status;
11122   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11123 
11124   Info.InConstantContext = true;
11125   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
11126       !EVResult.Val.isInt())
11127     return ICEDiag(IK_NotICE, E->getBeginLoc());
11128 
11129   return NoDiag();
11130 }
11131 
11132 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
11133   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
11134   if (!E->getType()->isIntegralOrEnumerationType())
11135     return ICEDiag(IK_NotICE, E->getBeginLoc());
11136 
11137   switch (E->getStmtClass()) {
11138 #define ABSTRACT_STMT(Node)
11139 #define STMT(Node, Base) case Expr::Node##Class:
11140 #define EXPR(Node, Base)
11141 #include "clang/AST/StmtNodes.inc"
11142   case Expr::PredefinedExprClass:
11143   case Expr::FloatingLiteralClass:
11144   case Expr::ImaginaryLiteralClass:
11145   case Expr::StringLiteralClass:
11146   case Expr::ArraySubscriptExprClass:
11147   case Expr::OMPArraySectionExprClass:
11148   case Expr::MemberExprClass:
11149   case Expr::CompoundAssignOperatorClass:
11150   case Expr::CompoundLiteralExprClass:
11151   case Expr::ExtVectorElementExprClass:
11152   case Expr::DesignatedInitExprClass:
11153   case Expr::ArrayInitLoopExprClass:
11154   case Expr::ArrayInitIndexExprClass:
11155   case Expr::NoInitExprClass:
11156   case Expr::DesignatedInitUpdateExprClass:
11157   case Expr::ImplicitValueInitExprClass:
11158   case Expr::ParenListExprClass:
11159   case Expr::VAArgExprClass:
11160   case Expr::AddrLabelExprClass:
11161   case Expr::StmtExprClass:
11162   case Expr::CXXMemberCallExprClass:
11163   case Expr::CUDAKernelCallExprClass:
11164   case Expr::CXXDynamicCastExprClass:
11165   case Expr::CXXTypeidExprClass:
11166   case Expr::CXXUuidofExprClass:
11167   case Expr::MSPropertyRefExprClass:
11168   case Expr::MSPropertySubscriptExprClass:
11169   case Expr::CXXNullPtrLiteralExprClass:
11170   case Expr::UserDefinedLiteralClass:
11171   case Expr::CXXThisExprClass:
11172   case Expr::CXXThrowExprClass:
11173   case Expr::CXXNewExprClass:
11174   case Expr::CXXDeleteExprClass:
11175   case Expr::CXXPseudoDestructorExprClass:
11176   case Expr::UnresolvedLookupExprClass:
11177   case Expr::TypoExprClass:
11178   case Expr::DependentScopeDeclRefExprClass:
11179   case Expr::CXXConstructExprClass:
11180   case Expr::CXXInheritedCtorInitExprClass:
11181   case Expr::CXXStdInitializerListExprClass:
11182   case Expr::CXXBindTemporaryExprClass:
11183   case Expr::ExprWithCleanupsClass:
11184   case Expr::CXXTemporaryObjectExprClass:
11185   case Expr::CXXUnresolvedConstructExprClass:
11186   case Expr::CXXDependentScopeMemberExprClass:
11187   case Expr::UnresolvedMemberExprClass:
11188   case Expr::ObjCStringLiteralClass:
11189   case Expr::ObjCBoxedExprClass:
11190   case Expr::ObjCArrayLiteralClass:
11191   case Expr::ObjCDictionaryLiteralClass:
11192   case Expr::ObjCEncodeExprClass:
11193   case Expr::ObjCMessageExprClass:
11194   case Expr::ObjCSelectorExprClass:
11195   case Expr::ObjCProtocolExprClass:
11196   case Expr::ObjCIvarRefExprClass:
11197   case Expr::ObjCPropertyRefExprClass:
11198   case Expr::ObjCSubscriptRefExprClass:
11199   case Expr::ObjCIsaExprClass:
11200   case Expr::ObjCAvailabilityCheckExprClass:
11201   case Expr::ShuffleVectorExprClass:
11202   case Expr::ConvertVectorExprClass:
11203   case Expr::BlockExprClass:
11204   case Expr::NoStmtClass:
11205   case Expr::OpaqueValueExprClass:
11206   case Expr::PackExpansionExprClass:
11207   case Expr::SubstNonTypeTemplateParmPackExprClass:
11208   case Expr::FunctionParmPackExprClass:
11209   case Expr::AsTypeExprClass:
11210   case Expr::ObjCIndirectCopyRestoreExprClass:
11211   case Expr::MaterializeTemporaryExprClass:
11212   case Expr::PseudoObjectExprClass:
11213   case Expr::AtomicExprClass:
11214   case Expr::LambdaExprClass:
11215   case Expr::CXXFoldExprClass:
11216   case Expr::CoawaitExprClass:
11217   case Expr::DependentCoawaitExprClass:
11218   case Expr::CoyieldExprClass:
11219     return ICEDiag(IK_NotICE, E->getBeginLoc());
11220 
11221   case Expr::InitListExprClass: {
11222     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11223     // form "T x = { a };" is equivalent to "T x = a;".
11224     // Unless we're initializing a reference, T is a scalar as it is known to be
11225     // of integral or enumeration type.
11226     if (E->isRValue())
11227       if (cast<InitListExpr>(E)->getNumInits() == 1)
11228         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
11229     return ICEDiag(IK_NotICE, E->getBeginLoc());
11230   }
11231 
11232   case Expr::SizeOfPackExprClass:
11233   case Expr::GNUNullExprClass:
11234     // GCC considers the GNU __null value to be an integral constant expression.
11235     return NoDiag();
11236 
11237   case Expr::SubstNonTypeTemplateParmExprClass:
11238     return
11239       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11240 
11241   case Expr::ConstantExprClass:
11242     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11243 
11244   case Expr::ParenExprClass:
11245     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
11246   case Expr::GenericSelectionExprClass:
11247     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
11248   case Expr::IntegerLiteralClass:
11249   case Expr::FixedPointLiteralClass:
11250   case Expr::CharacterLiteralClass:
11251   case Expr::ObjCBoolLiteralExprClass:
11252   case Expr::CXXBoolLiteralExprClass:
11253   case Expr::CXXScalarValueInitExprClass:
11254   case Expr::TypeTraitExprClass:
11255   case Expr::ArrayTypeTraitExprClass:
11256   case Expr::ExpressionTraitExprClass:
11257   case Expr::CXXNoexceptExprClass:
11258     return NoDiag();
11259   case Expr::CallExprClass:
11260   case Expr::CXXOperatorCallExprClass: {
11261     // C99 6.6/3 allows function calls within unevaluated subexpressions of
11262     // constant expressions, but they can never be ICEs because an ICE cannot
11263     // contain an operand of (pointer to) function type.
11264     const CallExpr *CE = cast<CallExpr>(E);
11265     if (CE->getBuiltinCallee())
11266       return CheckEvalInICE(E, Ctx);
11267     return ICEDiag(IK_NotICE, E->getBeginLoc());
11268   }
11269   case Expr::DeclRefExprClass: {
11270     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11271       return NoDiag();
11272     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
11273     if (Ctx.getLangOpts().CPlusPlus &&
11274         D && IsConstNonVolatile(D->getType())) {
11275       // Parameter variables are never constants.  Without this check,
11276       // getAnyInitializer() can find a default argument, which leads
11277       // to chaos.
11278       if (isa<ParmVarDecl>(D))
11279         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11280 
11281       // C++ 7.1.5.1p2
11282       //   A variable of non-volatile const-qualified integral or enumeration
11283       //   type initialized by an ICE can be used in ICEs.
11284       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
11285         if (!Dcl->getType()->isIntegralOrEnumerationType())
11286           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11287 
11288         const VarDecl *VD;
11289         // Look for a declaration of this variable that has an initializer, and
11290         // check whether it is an ICE.
11291         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11292           return NoDiag();
11293         else
11294           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11295       }
11296     }
11297     return ICEDiag(IK_NotICE, E->getBeginLoc());
11298   }
11299   case Expr::UnaryOperatorClass: {
11300     const UnaryOperator *Exp = cast<UnaryOperator>(E);
11301     switch (Exp->getOpcode()) {
11302     case UO_PostInc:
11303     case UO_PostDec:
11304     case UO_PreInc:
11305     case UO_PreDec:
11306     case UO_AddrOf:
11307     case UO_Deref:
11308     case UO_Coawait:
11309       // C99 6.6/3 allows increment and decrement within unevaluated
11310       // subexpressions of constant expressions, but they can never be ICEs
11311       // because an ICE cannot contain an lvalue operand.
11312       return ICEDiag(IK_NotICE, E->getBeginLoc());
11313     case UO_Extension:
11314     case UO_LNot:
11315     case UO_Plus:
11316     case UO_Minus:
11317     case UO_Not:
11318     case UO_Real:
11319     case UO_Imag:
11320       return CheckICE(Exp->getSubExpr(), Ctx);
11321     }
11322     llvm_unreachable("invalid unary operator class");
11323   }
11324   case Expr::OffsetOfExprClass: {
11325     // Note that per C99, offsetof must be an ICE. And AFAIK, using
11326     // EvaluateAsRValue matches the proposed gcc behavior for cases like
11327     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
11328     // compliance: we should warn earlier for offsetof expressions with
11329     // array subscripts that aren't ICEs, and if the array subscripts
11330     // are ICEs, the value of the offsetof must be an integer constant.
11331     return CheckEvalInICE(E, Ctx);
11332   }
11333   case Expr::UnaryExprOrTypeTraitExprClass: {
11334     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11335     if ((Exp->getKind() ==  UETT_SizeOf) &&
11336         Exp->getTypeOfArgument()->isVariableArrayType())
11337       return ICEDiag(IK_NotICE, E->getBeginLoc());
11338     return NoDiag();
11339   }
11340   case Expr::BinaryOperatorClass: {
11341     const BinaryOperator *Exp = cast<BinaryOperator>(E);
11342     switch (Exp->getOpcode()) {
11343     case BO_PtrMemD:
11344     case BO_PtrMemI:
11345     case BO_Assign:
11346     case BO_MulAssign:
11347     case BO_DivAssign:
11348     case BO_RemAssign:
11349     case BO_AddAssign:
11350     case BO_SubAssign:
11351     case BO_ShlAssign:
11352     case BO_ShrAssign:
11353     case BO_AndAssign:
11354     case BO_XorAssign:
11355     case BO_OrAssign:
11356       // C99 6.6/3 allows assignments within unevaluated subexpressions of
11357       // constant expressions, but they can never be ICEs because an ICE cannot
11358       // contain an lvalue operand.
11359       return ICEDiag(IK_NotICE, E->getBeginLoc());
11360 
11361     case BO_Mul:
11362     case BO_Div:
11363     case BO_Rem:
11364     case BO_Add:
11365     case BO_Sub:
11366     case BO_Shl:
11367     case BO_Shr:
11368     case BO_LT:
11369     case BO_GT:
11370     case BO_LE:
11371     case BO_GE:
11372     case BO_EQ:
11373     case BO_NE:
11374     case BO_And:
11375     case BO_Xor:
11376     case BO_Or:
11377     case BO_Comma:
11378     case BO_Cmp: {
11379       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11380       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11381       if (Exp->getOpcode() == BO_Div ||
11382           Exp->getOpcode() == BO_Rem) {
11383         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11384         // we don't evaluate one.
11385         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11386           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11387           if (REval == 0)
11388             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11389           if (REval.isSigned() && REval.isAllOnesValue()) {
11390             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11391             if (LEval.isMinSignedValue())
11392               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11393           }
11394         }
11395       }
11396       if (Exp->getOpcode() == BO_Comma) {
11397         if (Ctx.getLangOpts().C99) {
11398           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11399           // if it isn't evaluated.
11400           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11401             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11402         } else {
11403           // In both C89 and C++, commas in ICEs are illegal.
11404           return ICEDiag(IK_NotICE, E->getBeginLoc());
11405         }
11406       }
11407       return Worst(LHSResult, RHSResult);
11408     }
11409     case BO_LAnd:
11410     case BO_LOr: {
11411       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11412       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11413       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11414         // Rare case where the RHS has a comma "side-effect"; we need
11415         // to actually check the condition to see whether the side
11416         // with the comma is evaluated.
11417         if ((Exp->getOpcode() == BO_LAnd) !=
11418             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11419           return RHSResult;
11420         return NoDiag();
11421       }
11422 
11423       return Worst(LHSResult, RHSResult);
11424     }
11425     }
11426     llvm_unreachable("invalid binary operator kind");
11427   }
11428   case Expr::ImplicitCastExprClass:
11429   case Expr::CStyleCastExprClass:
11430   case Expr::CXXFunctionalCastExprClass:
11431   case Expr::CXXStaticCastExprClass:
11432   case Expr::CXXReinterpretCastExprClass:
11433   case Expr::CXXConstCastExprClass:
11434   case Expr::ObjCBridgedCastExprClass: {
11435     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11436     if (isa<ExplicitCastExpr>(E)) {
11437       if (const FloatingLiteral *FL
11438             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11439         unsigned DestWidth = Ctx.getIntWidth(E->getType());
11440         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11441         APSInt IgnoredVal(DestWidth, !DestSigned);
11442         bool Ignored;
11443         // If the value does not fit in the destination type, the behavior is
11444         // undefined, so we are not required to treat it as a constant
11445         // expression.
11446         if (FL->getValue().convertToInteger(IgnoredVal,
11447                                             llvm::APFloat::rmTowardZero,
11448                                             &Ignored) & APFloat::opInvalidOp)
11449           return ICEDiag(IK_NotICE, E->getBeginLoc());
11450         return NoDiag();
11451       }
11452     }
11453     switch (cast<CastExpr>(E)->getCastKind()) {
11454     case CK_LValueToRValue:
11455     case CK_AtomicToNonAtomic:
11456     case CK_NonAtomicToAtomic:
11457     case CK_NoOp:
11458     case CK_IntegralToBoolean:
11459     case CK_IntegralCast:
11460       return CheckICE(SubExpr, Ctx);
11461     default:
11462       return ICEDiag(IK_NotICE, E->getBeginLoc());
11463     }
11464   }
11465   case Expr::BinaryConditionalOperatorClass: {
11466     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11467     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11468     if (CommonResult.Kind == IK_NotICE) return CommonResult;
11469     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11470     if (FalseResult.Kind == IK_NotICE) return FalseResult;
11471     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11472     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11473         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11474     return FalseResult;
11475   }
11476   case Expr::ConditionalOperatorClass: {
11477     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11478     // If the condition (ignoring parens) is a __builtin_constant_p call,
11479     // then only the true side is actually considered in an integer constant
11480     // expression, and it is fully evaluated.  This is an important GNU
11481     // extension.  See GCC PR38377 for discussion.
11482     if (const CallExpr *CallCE
11483         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11484       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11485         return CheckEvalInICE(E, Ctx);
11486     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11487     if (CondResult.Kind == IK_NotICE)
11488       return CondResult;
11489 
11490     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11491     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11492 
11493     if (TrueResult.Kind == IK_NotICE)
11494       return TrueResult;
11495     if (FalseResult.Kind == IK_NotICE)
11496       return FalseResult;
11497     if (CondResult.Kind == IK_ICEIfUnevaluated)
11498       return CondResult;
11499     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11500       return NoDiag();
11501     // Rare case where the diagnostics depend on which side is evaluated
11502     // Note that if we get here, CondResult is 0, and at least one of
11503     // TrueResult and FalseResult is non-zero.
11504     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11505       return FalseResult;
11506     return TrueResult;
11507   }
11508   case Expr::CXXDefaultArgExprClass:
11509     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11510   case Expr::CXXDefaultInitExprClass:
11511     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11512   case Expr::ChooseExprClass: {
11513     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11514   }
11515   }
11516 
11517   llvm_unreachable("Invalid StmtClass!");
11518 }
11519 
11520 /// Evaluate an expression as a C++11 integral constant expression.
11521 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11522                                                     const Expr *E,
11523                                                     llvm::APSInt *Value,
11524                                                     SourceLocation *Loc) {
11525   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11526     if (Loc) *Loc = E->getExprLoc();
11527     return false;
11528   }
11529 
11530   APValue Result;
11531   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11532     return false;
11533 
11534   if (!Result.isInt()) {
11535     if (Loc) *Loc = E->getExprLoc();
11536     return false;
11537   }
11538 
11539   if (Value) *Value = Result.getInt();
11540   return true;
11541 }
11542 
11543 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11544                                  SourceLocation *Loc) const {
11545   if (Ctx.getLangOpts().CPlusPlus11)
11546     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11547 
11548   ICEDiag D = CheckICE(this, Ctx);
11549   if (D.Kind != IK_ICE) {
11550     if (Loc) *Loc = D.Loc;
11551     return false;
11552   }
11553   return true;
11554 }
11555 
11556 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11557                                  SourceLocation *Loc, bool isEvaluated) const {
11558   if (Ctx.getLangOpts().CPlusPlus11)
11559     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11560 
11561   if (!isIntegerConstantExpr(Ctx, Loc))
11562     return false;
11563 
11564   // The only possible side-effects here are due to UB discovered in the
11565   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11566   // required to treat the expression as an ICE, so we produce the folded
11567   // value.
11568   EvalResult ExprResult;
11569   Expr::EvalStatus Status;
11570   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11571   Info.InConstantContext = true;
11572 
11573   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
11574     llvm_unreachable("ICE cannot be evaluated!");
11575 
11576   Value = ExprResult.Val.getInt();
11577   return true;
11578 }
11579 
11580 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11581   return CheckICE(this, Ctx).Kind == IK_ICE;
11582 }
11583 
11584 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11585                                SourceLocation *Loc) const {
11586   // We support this checking in C++98 mode in order to diagnose compatibility
11587   // issues.
11588   assert(Ctx.getLangOpts().CPlusPlus);
11589 
11590   // Build evaluation settings.
11591   Expr::EvalStatus Status;
11592   SmallVector<PartialDiagnosticAt, 8> Diags;
11593   Status.Diag = &Diags;
11594   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11595 
11596   APValue Scratch;
11597   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11598 
11599   if (!Diags.empty()) {
11600     IsConstExpr = false;
11601     if (Loc) *Loc = Diags[0].first;
11602   } else if (!IsConstExpr) {
11603     // FIXME: This shouldn't happen.
11604     if (Loc) *Loc = getExprLoc();
11605   }
11606 
11607   return IsConstExpr;
11608 }
11609 
11610 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11611                                     const FunctionDecl *Callee,
11612                                     ArrayRef<const Expr*> Args,
11613                                     const Expr *This) const {
11614   Expr::EvalStatus Status;
11615   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11616 
11617   LValue ThisVal;
11618   const LValue *ThisPtr = nullptr;
11619   if (This) {
11620 #ifndef NDEBUG
11621     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11622     assert(MD && "Don't provide `this` for non-methods.");
11623     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11624 #endif
11625     if (EvaluateObjectArgument(Info, This, ThisVal))
11626       ThisPtr = &ThisVal;
11627     if (Info.EvalStatus.HasSideEffects)
11628       return false;
11629   }
11630 
11631   ArgVector ArgValues(Args.size());
11632   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11633        I != E; ++I) {
11634     if ((*I)->isValueDependent() ||
11635         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11636       // If evaluation fails, throw away the argument entirely.
11637       ArgValues[I - Args.begin()] = APValue();
11638     if (Info.EvalStatus.HasSideEffects)
11639       return false;
11640   }
11641 
11642   // Build fake call to Callee.
11643   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11644                        ArgValues.data());
11645   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11646 }
11647 
11648 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11649                                    SmallVectorImpl<
11650                                      PartialDiagnosticAt> &Diags) {
11651   // FIXME: It would be useful to check constexpr function templates, but at the
11652   // moment the constant expression evaluator cannot cope with the non-rigorous
11653   // ASTs which we build for dependent expressions.
11654   if (FD->isDependentContext())
11655     return true;
11656 
11657   Expr::EvalStatus Status;
11658   Status.Diag = &Diags;
11659 
11660   EvalInfo Info(FD->getASTContext(), Status,
11661                 EvalInfo::EM_PotentialConstantExpression);
11662   Info.InConstantContext = true;
11663 
11664   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11665   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11666 
11667   // Fabricate an arbitrary expression on the stack and pretend that it
11668   // is a temporary being used as the 'this' pointer.
11669   LValue This;
11670   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11671   This.set({&VIE, Info.CurrentCall->Index});
11672 
11673   ArrayRef<const Expr*> Args;
11674 
11675   APValue Scratch;
11676   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11677     // Evaluate the call as a constant initializer, to allow the construction
11678     // of objects of non-literal types.
11679     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11680     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11681   } else {
11682     SourceLocation Loc = FD->getLocation();
11683     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11684                        Args, FD->getBody(), Info, Scratch, nullptr);
11685   }
11686 
11687   return Diags.empty();
11688 }
11689 
11690 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11691                                               const FunctionDecl *FD,
11692                                               SmallVectorImpl<
11693                                                 PartialDiagnosticAt> &Diags) {
11694   Expr::EvalStatus Status;
11695   Status.Diag = &Diags;
11696 
11697   EvalInfo Info(FD->getASTContext(), Status,
11698                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11699 
11700   // Fabricate a call stack frame to give the arguments a plausible cover story.
11701   ArrayRef<const Expr*> Args;
11702   ArgVector ArgValues(0);
11703   bool Success = EvaluateArgs(Args, ArgValues, Info);
11704   (void)Success;
11705   assert(Success &&
11706          "Failed to set up arguments for potential constant evaluation");
11707   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11708 
11709   APValue ResultScratch;
11710   Evaluate(ResultScratch, Info, E);
11711   return Diags.empty();
11712 }
11713 
11714 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11715                                  unsigned Type) const {
11716   if (!getType()->isPointerType())
11717     return false;
11718 
11719   Expr::EvalStatus Status;
11720   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11721   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
11722 }
11723