1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTDiagnostic.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/OSLog.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/FixedPoint.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     OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
618       if (Diag) {
619         SmallVector<char, 32> Buffer;
620         FX.toString(Buffer);
621         *Diag << StringRef(Buffer.data(), Buffer.size());
622       }
623       return *this;
624     }
625   };
626 
627   /// A cleanup, and a flag indicating whether it is lifetime-extended.
628   class Cleanup {
629     llvm::PointerIntPair<APValue*, 1, bool> Value;
630 
631   public:
632     Cleanup(APValue *Val, bool IsLifetimeExtended)
633         : Value(Val, IsLifetimeExtended) {}
634 
635     bool isLifetimeExtended() const { return Value.getInt(); }
636     void endLifetime() {
637       *Value.getPointer() = APValue();
638     }
639   };
640 
641   /// EvalInfo - This is a private struct used by the evaluator to capture
642   /// information about a subexpression as it is folded.  It retains information
643   /// about the AST context, but also maintains information about the folded
644   /// expression.
645   ///
646   /// If an expression could be evaluated, it is still possible it is not a C
647   /// "integer constant expression" or constant expression.  If not, this struct
648   /// captures information about how and why not.
649   ///
650   /// One bit of information passed *into* the request for constant folding
651   /// indicates whether the subexpression is "evaluated" or not according to C
652   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
653   /// evaluate the expression regardless of what the RHS is, but C only allows
654   /// certain things in certain situations.
655   struct EvalInfo {
656     ASTContext &Ctx;
657 
658     /// EvalStatus - Contains information about the evaluation.
659     Expr::EvalStatus &EvalStatus;
660 
661     /// CurrentCall - The top of the constexpr call stack.
662     CallStackFrame *CurrentCall;
663 
664     /// CallStackDepth - The number of calls in the call stack right now.
665     unsigned CallStackDepth;
666 
667     /// NextCallIndex - The next call index to assign.
668     unsigned NextCallIndex;
669 
670     /// StepsLeft - The remaining number of evaluation steps we're permitted
671     /// to perform. This is essentially a limit for the number of statements
672     /// we will evaluate.
673     unsigned StepsLeft;
674 
675     /// BottomFrame - The frame in which evaluation started. This must be
676     /// initialized after CurrentCall and CallStackDepth.
677     CallStackFrame BottomFrame;
678 
679     /// A stack of values whose lifetimes end at the end of some surrounding
680     /// evaluation frame.
681     llvm::SmallVector<Cleanup, 16> CleanupStack;
682 
683     /// EvaluatingDecl - This is the declaration whose initializer is being
684     /// evaluated, if any.
685     APValue::LValueBase EvaluatingDecl;
686 
687     /// EvaluatingDeclValue - This is the value being constructed for the
688     /// declaration whose initializer is being evaluated, if any.
689     APValue *EvaluatingDeclValue;
690 
691     /// EvaluatingObject - Pair of the AST node that an lvalue represents and
692     /// the call index that that lvalue was allocated in.
693     typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
694         EvaluatingObject;
695 
696     /// EvaluatingConstructors - Set of objects that are currently being
697     /// constructed.
698     llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
699 
700     struct EvaluatingConstructorRAII {
701       EvalInfo &EI;
702       EvaluatingObject Object;
703       bool DidInsert;
704       EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
705           : EI(EI), Object(Object) {
706         DidInsert = EI.EvaluatingConstructors.insert(Object).second;
707       }
708       ~EvaluatingConstructorRAII() {
709         if (DidInsert) EI.EvaluatingConstructors.erase(Object);
710       }
711     };
712 
713     bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
714                                  unsigned Version) {
715       return EvaluatingConstructors.count(
716           EvaluatingObject(Decl, {CallIndex, Version}));
717     }
718 
719     /// The current array initialization index, if we're performing array
720     /// initialization.
721     uint64_t ArrayInitIndex = -1;
722 
723     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
724     /// notes attached to it will also be stored, otherwise they will not be.
725     bool HasActiveDiagnostic;
726 
727     /// Have we emitted a diagnostic explaining why we couldn't constant
728     /// fold (not just why it's not strictly a constant expression)?
729     bool HasFoldFailureDiagnostic;
730 
731     /// Whether or not we're currently speculatively evaluating.
732     bool IsSpeculativelyEvaluating;
733 
734     /// Whether or not we're in a context where the front end requires a
735     /// constant value.
736     bool InConstantContext;
737 
738     enum EvaluationMode {
739       /// Evaluate as a constant expression. Stop if we find that the expression
740       /// is not a constant expression.
741       EM_ConstantExpression,
742 
743       /// Evaluate as a potential constant expression. Keep going if we hit a
744       /// construct that we can't evaluate yet (because we don't yet know the
745       /// value of something) but stop if we hit something that could never be
746       /// a constant expression.
747       EM_PotentialConstantExpression,
748 
749       /// Fold the expression to a constant. Stop if we hit a side-effect that
750       /// we can't model.
751       EM_ConstantFold,
752 
753       /// Evaluate the expression looking for integer overflow and similar
754       /// issues. Don't worry about side-effects, and try to visit all
755       /// subexpressions.
756       EM_EvaluateForOverflow,
757 
758       /// Evaluate in any way we know how. Don't worry about side-effects that
759       /// can't be modeled.
760       EM_IgnoreSideEffects,
761 
762       /// Evaluate as a constant expression. Stop if we find that the expression
763       /// is not 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_ConstantExpressionUnevaluated,
768 
769       /// Evaluate as a potential constant expression. Keep going if we hit a
770       /// construct that we can't evaluate yet (because we don't yet know the
771       /// value of something) but stop if we hit something that could never be
772       /// a constant expression. Some expressions can be retried in the
773       /// optimizer if we don't constant fold them here, but in an unevaluated
774       /// context we try to fold them immediately since the optimizer never
775       /// gets a chance to look at it.
776       EM_PotentialConstantExpressionUnevaluated,
777     } EvalMode;
778 
779     /// Are we checking whether the expression is a potential constant
780     /// expression?
781     bool checkingPotentialConstantExpression() const {
782       return EvalMode == EM_PotentialConstantExpression ||
783              EvalMode == EM_PotentialConstantExpressionUnevaluated;
784     }
785 
786     /// Are we checking an expression for overflow?
787     // FIXME: We should check for any kind of undefined or suspicious behavior
788     // in such constructs, not just overflow.
789     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
790 
791     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
792       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
793         CallStackDepth(0), NextCallIndex(1),
794         StepsLeft(getLangOpts().ConstexprStepLimit),
795         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
796         EvaluatingDecl((const ValueDecl *)nullptr),
797         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
798         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
799         InConstantContext(false), EvalMode(Mode) {}
800 
801     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
802       EvaluatingDecl = Base;
803       EvaluatingDeclValue = &Value;
804       EvaluatingConstructors.insert({Base, {0, 0}});
805     }
806 
807     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
808 
809     bool CheckCallLimit(SourceLocation Loc) {
810       // Don't perform any constexpr calls (other than the call we're checking)
811       // when checking a potential constant expression.
812       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
813         return false;
814       if (NextCallIndex == 0) {
815         // NextCallIndex has wrapped around.
816         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
817         return false;
818       }
819       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
820         return true;
821       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
822         << getLangOpts().ConstexprCallDepth;
823       return false;
824     }
825 
826     CallStackFrame *getCallFrame(unsigned CallIndex) {
827       assert(CallIndex && "no call index in getCallFrame");
828       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
829       // be null in this loop.
830       CallStackFrame *Frame = CurrentCall;
831       while (Frame->Index > CallIndex)
832         Frame = Frame->Caller;
833       return (Frame->Index == CallIndex) ? Frame : nullptr;
834     }
835 
836     bool nextStep(const Stmt *S) {
837       if (!StepsLeft) {
838         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
839         return false;
840       }
841       --StepsLeft;
842       return true;
843     }
844 
845   private:
846     /// Add a diagnostic to the diagnostics list.
847     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
848       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
849       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
850       return EvalStatus.Diag->back().second;
851     }
852 
853     /// Add notes containing a call stack to the current point of evaluation.
854     void addCallStack(unsigned Limit);
855 
856   private:
857     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
858                             unsigned ExtraNotes, bool IsCCEDiag) {
859 
860       if (EvalStatus.Diag) {
861         // If we have a prior diagnostic, it will be noting that the expression
862         // isn't a constant expression. This diagnostic is more important,
863         // unless we require this evaluation to produce a constant expression.
864         //
865         // FIXME: We might want to show both diagnostics to the user in
866         // EM_ConstantFold mode.
867         if (!EvalStatus.Diag->empty()) {
868           switch (EvalMode) {
869           case EM_ConstantFold:
870           case EM_IgnoreSideEffects:
871           case EM_EvaluateForOverflow:
872             if (!HasFoldFailureDiagnostic)
873               break;
874             // We've already failed to fold something. Keep that diagnostic.
875             LLVM_FALLTHROUGH;
876           case EM_ConstantExpression:
877           case EM_PotentialConstantExpression:
878           case EM_ConstantExpressionUnevaluated:
879           case EM_PotentialConstantExpressionUnevaluated:
880             HasActiveDiagnostic = false;
881             return OptionalDiagnostic();
882           }
883         }
884 
885         unsigned CallStackNotes = CallStackDepth - 1;
886         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
887         if (Limit)
888           CallStackNotes = std::min(CallStackNotes, Limit + 1);
889         if (checkingPotentialConstantExpression())
890           CallStackNotes = 0;
891 
892         HasActiveDiagnostic = true;
893         HasFoldFailureDiagnostic = !IsCCEDiag;
894         EvalStatus.Diag->clear();
895         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
896         addDiag(Loc, DiagId);
897         if (!checkingPotentialConstantExpression())
898           addCallStack(Limit);
899         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
900       }
901       HasActiveDiagnostic = false;
902       return OptionalDiagnostic();
903     }
904   public:
905     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
906     OptionalDiagnostic
907     FFDiag(SourceLocation Loc,
908           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
909           unsigned ExtraNotes = 0) {
910       return Diag(Loc, DiagId, ExtraNotes, false);
911     }
912 
913     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
914                               = diag::note_invalid_subexpr_in_const_expr,
915                             unsigned ExtraNotes = 0) {
916       if (EvalStatus.Diag)
917         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
918       HasActiveDiagnostic = false;
919       return OptionalDiagnostic();
920     }
921 
922     /// Diagnose that the evaluation does not produce a C++11 core constant
923     /// expression.
924     ///
925     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
926     /// EM_PotentialConstantExpression mode and we produce one of these.
927     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
928                                  = diag::note_invalid_subexpr_in_const_expr,
929                                unsigned ExtraNotes = 0) {
930       // Don't override a previous diagnostic. Don't bother collecting
931       // diagnostics if we're evaluating for overflow.
932       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
933         HasActiveDiagnostic = false;
934         return OptionalDiagnostic();
935       }
936       return Diag(Loc, DiagId, ExtraNotes, true);
937     }
938     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
939                                  = diag::note_invalid_subexpr_in_const_expr,
940                                unsigned ExtraNotes = 0) {
941       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
942     }
943     /// Add a note to a prior diagnostic.
944     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
945       if (!HasActiveDiagnostic)
946         return OptionalDiagnostic();
947       return OptionalDiagnostic(&addDiag(Loc, DiagId));
948     }
949 
950     /// Add a stack of notes to a prior diagnostic.
951     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
952       if (HasActiveDiagnostic) {
953         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
954                                 Diags.begin(), Diags.end());
955       }
956     }
957 
958     /// Should we continue evaluation after encountering a side-effect that we
959     /// couldn't model?
960     bool keepEvaluatingAfterSideEffect() {
961       switch (EvalMode) {
962       case EM_PotentialConstantExpression:
963       case EM_PotentialConstantExpressionUnevaluated:
964       case EM_EvaluateForOverflow:
965       case EM_IgnoreSideEffects:
966         return true;
967 
968       case EM_ConstantExpression:
969       case EM_ConstantExpressionUnevaluated:
970       case EM_ConstantFold:
971         return false;
972       }
973       llvm_unreachable("Missed EvalMode case");
974     }
975 
976     /// Note that we have had a side-effect, and determine whether we should
977     /// keep evaluating.
978     bool noteSideEffect() {
979       EvalStatus.HasSideEffects = true;
980       return keepEvaluatingAfterSideEffect();
981     }
982 
983     /// Should we continue evaluation after encountering undefined behavior?
984     bool keepEvaluatingAfterUndefinedBehavior() {
985       switch (EvalMode) {
986       case EM_EvaluateForOverflow:
987       case EM_IgnoreSideEffects:
988       case EM_ConstantFold:
989         return true;
990 
991       case EM_PotentialConstantExpression:
992       case EM_PotentialConstantExpressionUnevaluated:
993       case EM_ConstantExpression:
994       case EM_ConstantExpressionUnevaluated:
995         return false;
996       }
997       llvm_unreachable("Missed EvalMode case");
998     }
999 
1000     /// Note that we hit something that was technically undefined behavior, but
1001     /// that we can evaluate past it (such as signed overflow or floating-point
1002     /// division by zero.)
1003     bool noteUndefinedBehavior() {
1004       EvalStatus.HasUndefinedBehavior = true;
1005       return keepEvaluatingAfterUndefinedBehavior();
1006     }
1007 
1008     /// Should we continue evaluation as much as possible after encountering a
1009     /// construct which can't be reduced to a value?
1010     bool keepEvaluatingAfterFailure() {
1011       if (!StepsLeft)
1012         return false;
1013 
1014       switch (EvalMode) {
1015       case EM_PotentialConstantExpression:
1016       case EM_PotentialConstantExpressionUnevaluated:
1017       case EM_EvaluateForOverflow:
1018         return true;
1019 
1020       case EM_ConstantExpression:
1021       case EM_ConstantExpressionUnevaluated:
1022       case EM_ConstantFold:
1023       case EM_IgnoreSideEffects:
1024         return false;
1025       }
1026       llvm_unreachable("Missed EvalMode case");
1027     }
1028 
1029     /// Notes that we failed to evaluate an expression that other expressions
1030     /// directly depend on, and determine if we should keep evaluating. This
1031     /// should only be called if we actually intend to keep evaluating.
1032     ///
1033     /// Call noteSideEffect() instead if we may be able to ignore the value that
1034     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1035     ///
1036     /// (Foo(), 1)      // use noteSideEffect
1037     /// (Foo() || true) // use noteSideEffect
1038     /// Foo() + 1       // use noteFailure
1039     LLVM_NODISCARD bool noteFailure() {
1040       // Failure when evaluating some expression often means there is some
1041       // subexpression whose evaluation was skipped. Therefore, (because we
1042       // don't track whether we skipped an expression when unwinding after an
1043       // evaluation failure) every evaluation failure that bubbles up from a
1044       // subexpression implies that a side-effect has potentially happened. We
1045       // skip setting the HasSideEffects flag to true until we decide to
1046       // continue evaluating after that point, which happens here.
1047       bool KeepGoing = keepEvaluatingAfterFailure();
1048       EvalStatus.HasSideEffects |= KeepGoing;
1049       return KeepGoing;
1050     }
1051 
1052     class ArrayInitLoopIndex {
1053       EvalInfo &Info;
1054       uint64_t OuterIndex;
1055 
1056     public:
1057       ArrayInitLoopIndex(EvalInfo &Info)
1058           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1059         Info.ArrayInitIndex = 0;
1060       }
1061       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1062 
1063       operator uint64_t&() { return Info.ArrayInitIndex; }
1064     };
1065   };
1066 
1067   /// Object used to treat all foldable expressions as constant expressions.
1068   struct FoldConstant {
1069     EvalInfo &Info;
1070     bool Enabled;
1071     bool HadNoPriorDiags;
1072     EvalInfo::EvaluationMode OldMode;
1073 
1074     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1075       : Info(Info),
1076         Enabled(Enabled),
1077         HadNoPriorDiags(Info.EvalStatus.Diag &&
1078                         Info.EvalStatus.Diag->empty() &&
1079                         !Info.EvalStatus.HasSideEffects),
1080         OldMode(Info.EvalMode) {
1081       if (Enabled &&
1082           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1083            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1084         Info.EvalMode = EvalInfo::EM_ConstantFold;
1085     }
1086     void keepDiagnostics() { Enabled = false; }
1087     ~FoldConstant() {
1088       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1089           !Info.EvalStatus.HasSideEffects)
1090         Info.EvalStatus.Diag->clear();
1091       Info.EvalMode = OldMode;
1092     }
1093   };
1094 
1095   /// RAII object used to set the current evaluation mode to ignore
1096   /// side-effects.
1097   struct IgnoreSideEffectsRAII {
1098     EvalInfo &Info;
1099     EvalInfo::EvaluationMode OldMode;
1100     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1101         : Info(Info), OldMode(Info.EvalMode) {
1102       if (!Info.checkingPotentialConstantExpression())
1103         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1104     }
1105 
1106     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1107   };
1108 
1109   /// RAII object used to optionally suppress diagnostics and side-effects from
1110   /// a speculative evaluation.
1111   class SpeculativeEvaluationRAII {
1112     EvalInfo *Info = nullptr;
1113     Expr::EvalStatus OldStatus;
1114     bool OldIsSpeculativelyEvaluating;
1115 
1116     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1117       Info = Other.Info;
1118       OldStatus = Other.OldStatus;
1119       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1120       Other.Info = nullptr;
1121     }
1122 
1123     void maybeRestoreState() {
1124       if (!Info)
1125         return;
1126 
1127       Info->EvalStatus = OldStatus;
1128       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1129     }
1130 
1131   public:
1132     SpeculativeEvaluationRAII() = default;
1133 
1134     SpeculativeEvaluationRAII(
1135         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1136         : Info(&Info), OldStatus(Info.EvalStatus),
1137           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1138       Info.EvalStatus.Diag = NewDiag;
1139       Info.IsSpeculativelyEvaluating = true;
1140     }
1141 
1142     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1143     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1144       moveFromAndCancel(std::move(Other));
1145     }
1146 
1147     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1148       maybeRestoreState();
1149       moveFromAndCancel(std::move(Other));
1150       return *this;
1151     }
1152 
1153     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1154   };
1155 
1156   /// RAII object wrapping a full-expression or block scope, and handling
1157   /// the ending of the lifetime of temporaries created within it.
1158   template<bool IsFullExpression>
1159   class ScopeRAII {
1160     EvalInfo &Info;
1161     unsigned OldStackSize;
1162   public:
1163     ScopeRAII(EvalInfo &Info)
1164         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1165       // Push a new temporary version. This is needed to distinguish between
1166       // temporaries created in different iterations of a loop.
1167       Info.CurrentCall->pushTempVersion();
1168     }
1169     ~ScopeRAII() {
1170       // Body moved to a static method to encourage the compiler to inline away
1171       // instances of this class.
1172       cleanup(Info, OldStackSize);
1173       Info.CurrentCall->popTempVersion();
1174     }
1175   private:
1176     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1177       unsigned NewEnd = OldStackSize;
1178       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1179            I != N; ++I) {
1180         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1181           // Full-expression cleanup of a lifetime-extended temporary: nothing
1182           // to do, just move this cleanup to the right place in the stack.
1183           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1184           ++NewEnd;
1185         } else {
1186           // End the lifetime of the object.
1187           Info.CleanupStack[I].endLifetime();
1188         }
1189       }
1190       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1191                               Info.CleanupStack.end());
1192     }
1193   };
1194   typedef ScopeRAII<false> BlockScopeRAII;
1195   typedef ScopeRAII<true> FullExpressionRAII;
1196 }
1197 
1198 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1199                                          CheckSubobjectKind CSK) {
1200   if (Invalid)
1201     return false;
1202   if (isOnePastTheEnd()) {
1203     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1204       << CSK;
1205     setInvalid();
1206     return false;
1207   }
1208   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1209   // must actually be at least one array element; even a VLA cannot have a
1210   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1211   return true;
1212 }
1213 
1214 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1215                                                                 const Expr *E) {
1216   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1217   // Do not set the designator as invalid: we can represent this situation,
1218   // and correct handling of __builtin_object_size requires us to do so.
1219 }
1220 
1221 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1222                                                     const Expr *E,
1223                                                     const APSInt &N) {
1224   // If we're complaining, we must be able to statically determine the size of
1225   // the most derived array.
1226   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1227     Info.CCEDiag(E, diag::note_constexpr_array_index)
1228       << N << /*array*/ 0
1229       << static_cast<unsigned>(getMostDerivedArraySize());
1230   else
1231     Info.CCEDiag(E, diag::note_constexpr_array_index)
1232       << N << /*non-array*/ 1;
1233   setInvalid();
1234 }
1235 
1236 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1237                                const FunctionDecl *Callee, const LValue *This,
1238                                APValue *Arguments)
1239     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1240       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1241   Info.CurrentCall = this;
1242   ++Info.CallStackDepth;
1243 }
1244 
1245 CallStackFrame::~CallStackFrame() {
1246   assert(Info.CurrentCall == this && "calls retired out of order");
1247   --Info.CallStackDepth;
1248   Info.CurrentCall = Caller;
1249 }
1250 
1251 APValue &CallStackFrame::createTemporary(const void *Key,
1252                                          bool IsLifetimeExtended) {
1253   unsigned Version = Info.CurrentCall->getTempVersion();
1254   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1255   assert(Result.isUninit() && "temporary created multiple times");
1256   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1257   return Result;
1258 }
1259 
1260 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1261 
1262 void EvalInfo::addCallStack(unsigned Limit) {
1263   // Determine which calls to skip, if any.
1264   unsigned ActiveCalls = CallStackDepth - 1;
1265   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1266   if (Limit && Limit < ActiveCalls) {
1267     SkipStart = Limit / 2 + Limit % 2;
1268     SkipEnd = ActiveCalls - Limit / 2;
1269   }
1270 
1271   // Walk the call stack and add the diagnostics.
1272   unsigned CallIdx = 0;
1273   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1274        Frame = Frame->Caller, ++CallIdx) {
1275     // Skip this call?
1276     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1277       if (CallIdx == SkipStart) {
1278         // Note that we're skipping calls.
1279         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1280           << unsigned(ActiveCalls - Limit);
1281       }
1282       continue;
1283     }
1284 
1285     // Use a different note for an inheriting constructor, because from the
1286     // user's perspective it's not really a function at all.
1287     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1288       if (CD->isInheritingConstructor()) {
1289         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1290           << CD->getParent();
1291         continue;
1292       }
1293     }
1294 
1295     SmallVector<char, 128> Buffer;
1296     llvm::raw_svector_ostream Out(Buffer);
1297     describeCall(Frame, Out);
1298     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1299   }
1300 }
1301 
1302 /// Kinds of access we can perform on an object, for diagnostics.
1303 enum AccessKinds {
1304   AK_Read,
1305   AK_Assign,
1306   AK_Increment,
1307   AK_Decrement
1308 };
1309 
1310 namespace {
1311   struct ComplexValue {
1312   private:
1313     bool IsInt;
1314 
1315   public:
1316     APSInt IntReal, IntImag;
1317     APFloat FloatReal, FloatImag;
1318 
1319     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1320 
1321     void makeComplexFloat() { IsInt = false; }
1322     bool isComplexFloat() const { return !IsInt; }
1323     APFloat &getComplexFloatReal() { return FloatReal; }
1324     APFloat &getComplexFloatImag() { return FloatImag; }
1325 
1326     void makeComplexInt() { IsInt = true; }
1327     bool isComplexInt() const { return IsInt; }
1328     APSInt &getComplexIntReal() { return IntReal; }
1329     APSInt &getComplexIntImag() { return IntImag; }
1330 
1331     void moveInto(APValue &v) const {
1332       if (isComplexFloat())
1333         v = APValue(FloatReal, FloatImag);
1334       else
1335         v = APValue(IntReal, IntImag);
1336     }
1337     void setFrom(const APValue &v) {
1338       assert(v.isComplexFloat() || v.isComplexInt());
1339       if (v.isComplexFloat()) {
1340         makeComplexFloat();
1341         FloatReal = v.getComplexFloatReal();
1342         FloatImag = v.getComplexFloatImag();
1343       } else {
1344         makeComplexInt();
1345         IntReal = v.getComplexIntReal();
1346         IntImag = v.getComplexIntImag();
1347       }
1348     }
1349   };
1350 
1351   struct LValue {
1352     APValue::LValueBase Base;
1353     CharUnits Offset;
1354     SubobjectDesignator Designator;
1355     bool IsNullPtr : 1;
1356     bool InvalidBase : 1;
1357 
1358     const APValue::LValueBase getLValueBase() const { return Base; }
1359     CharUnits &getLValueOffset() { return Offset; }
1360     const CharUnits &getLValueOffset() const { return Offset; }
1361     SubobjectDesignator &getLValueDesignator() { return Designator; }
1362     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1363     bool isNullPointer() const { return IsNullPtr;}
1364 
1365     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1366     unsigned getLValueVersion() const { return Base.getVersion(); }
1367 
1368     void moveInto(APValue &V) const {
1369       if (Designator.Invalid)
1370         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1371       else {
1372         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1373         V = APValue(Base, Offset, Designator.Entries,
1374                     Designator.IsOnePastTheEnd, IsNullPtr);
1375       }
1376     }
1377     void setFrom(ASTContext &Ctx, const APValue &V) {
1378       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1379       Base = V.getLValueBase();
1380       Offset = V.getLValueOffset();
1381       InvalidBase = false;
1382       Designator = SubobjectDesignator(Ctx, V);
1383       IsNullPtr = V.isNullPointer();
1384     }
1385 
1386     void set(APValue::LValueBase B, bool BInvalid = false) {
1387 #ifndef NDEBUG
1388       // We only allow a few types of invalid bases. Enforce that here.
1389       if (BInvalid) {
1390         const auto *E = B.get<const Expr *>();
1391         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1392                "Unexpected type of invalid base");
1393       }
1394 #endif
1395 
1396       Base = B;
1397       Offset = CharUnits::fromQuantity(0);
1398       InvalidBase = BInvalid;
1399       Designator = SubobjectDesignator(getType(B));
1400       IsNullPtr = false;
1401     }
1402 
1403     void setNull(QualType PointerTy, uint64_t TargetVal) {
1404       Base = (Expr *)nullptr;
1405       Offset = CharUnits::fromQuantity(TargetVal);
1406       InvalidBase = false;
1407       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1408       IsNullPtr = true;
1409     }
1410 
1411     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1412       set(B, true);
1413     }
1414 
1415   private:
1416     // Check that this LValue is not based on a null pointer. If it is, produce
1417     // a diagnostic and mark the designator as invalid.
1418     template <typename GenDiagType>
1419     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1420       if (Designator.Invalid)
1421         return false;
1422       if (IsNullPtr) {
1423         GenDiag();
1424         Designator.setInvalid();
1425         return false;
1426       }
1427       return true;
1428     }
1429 
1430   public:
1431     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1432                           CheckSubobjectKind CSK) {
1433       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1434         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1435       });
1436     }
1437 
1438     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1439                                        AccessKinds AK) {
1440       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1441         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1442       });
1443     }
1444 
1445     // Check this LValue refers to an object. If not, set the designator to be
1446     // invalid and emit a diagnostic.
1447     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1448       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1449              Designator.checkSubobject(Info, E, CSK);
1450     }
1451 
1452     void addDecl(EvalInfo &Info, const Expr *E,
1453                  const Decl *D, bool Virtual = false) {
1454       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1455         Designator.addDeclUnchecked(D, Virtual);
1456     }
1457     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1458       if (!Designator.Entries.empty()) {
1459         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1460         Designator.setInvalid();
1461         return;
1462       }
1463       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1464         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1465         Designator.FirstEntryIsAnUnsizedArray = true;
1466         Designator.addUnsizedArrayUnchecked(ElemTy);
1467       }
1468     }
1469     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1470       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1471         Designator.addArrayUnchecked(CAT);
1472     }
1473     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1474       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1475         Designator.addComplexUnchecked(EltTy, Imag);
1476     }
1477     void clearIsNullPointer() {
1478       IsNullPtr = false;
1479     }
1480     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1481                               const APSInt &Index, CharUnits ElementSize) {
1482       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1483       // but we're not required to diagnose it and it's valid in C++.)
1484       if (!Index)
1485         return;
1486 
1487       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1488       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1489       // offsets.
1490       uint64_t Offset64 = Offset.getQuantity();
1491       uint64_t ElemSize64 = ElementSize.getQuantity();
1492       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1493       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1494 
1495       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1496         Designator.adjustIndex(Info, E, Index);
1497       clearIsNullPointer();
1498     }
1499     void adjustOffset(CharUnits N) {
1500       Offset += N;
1501       if (N.getQuantity())
1502         clearIsNullPointer();
1503     }
1504   };
1505 
1506   struct MemberPtr {
1507     MemberPtr() {}
1508     explicit MemberPtr(const ValueDecl *Decl) :
1509       DeclAndIsDerivedMember(Decl, false), Path() {}
1510 
1511     /// The member or (direct or indirect) field referred to by this member
1512     /// pointer, or 0 if this is a null member pointer.
1513     const ValueDecl *getDecl() const {
1514       return DeclAndIsDerivedMember.getPointer();
1515     }
1516     /// Is this actually a member of some type derived from the relevant class?
1517     bool isDerivedMember() const {
1518       return DeclAndIsDerivedMember.getInt();
1519     }
1520     /// Get the class which the declaration actually lives in.
1521     const CXXRecordDecl *getContainingRecord() const {
1522       return cast<CXXRecordDecl>(
1523           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1524     }
1525 
1526     void moveInto(APValue &V) const {
1527       V = APValue(getDecl(), isDerivedMember(), Path);
1528     }
1529     void setFrom(const APValue &V) {
1530       assert(V.isMemberPointer());
1531       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1532       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1533       Path.clear();
1534       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1535       Path.insert(Path.end(), P.begin(), P.end());
1536     }
1537 
1538     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1539     /// whether the member is a member of some class derived from the class type
1540     /// of the member pointer.
1541     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1542     /// Path - The path of base/derived classes from the member declaration's
1543     /// class (exclusive) to the class type of the member pointer (inclusive).
1544     SmallVector<const CXXRecordDecl*, 4> Path;
1545 
1546     /// Perform a cast towards the class of the Decl (either up or down the
1547     /// hierarchy).
1548     bool castBack(const CXXRecordDecl *Class) {
1549       assert(!Path.empty());
1550       const CXXRecordDecl *Expected;
1551       if (Path.size() >= 2)
1552         Expected = Path[Path.size() - 2];
1553       else
1554         Expected = getContainingRecord();
1555       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1556         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1557         // if B does not contain the original member and is not a base or
1558         // derived class of the class containing the original member, the result
1559         // of the cast is undefined.
1560         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1561         // (D::*). We consider that to be a language defect.
1562         return false;
1563       }
1564       Path.pop_back();
1565       return true;
1566     }
1567     /// Perform a base-to-derived member pointer cast.
1568     bool castToDerived(const CXXRecordDecl *Derived) {
1569       if (!getDecl())
1570         return true;
1571       if (!isDerivedMember()) {
1572         Path.push_back(Derived);
1573         return true;
1574       }
1575       if (!castBack(Derived))
1576         return false;
1577       if (Path.empty())
1578         DeclAndIsDerivedMember.setInt(false);
1579       return true;
1580     }
1581     /// Perform a derived-to-base member pointer cast.
1582     bool castToBase(const CXXRecordDecl *Base) {
1583       if (!getDecl())
1584         return true;
1585       if (Path.empty())
1586         DeclAndIsDerivedMember.setInt(true);
1587       if (isDerivedMember()) {
1588         Path.push_back(Base);
1589         return true;
1590       }
1591       return castBack(Base);
1592     }
1593   };
1594 
1595   /// Compare two member pointers, which are assumed to be of the same type.
1596   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1597     if (!LHS.getDecl() || !RHS.getDecl())
1598       return !LHS.getDecl() && !RHS.getDecl();
1599     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1600       return false;
1601     return LHS.Path == RHS.Path;
1602   }
1603 }
1604 
1605 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1606 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1607                             const LValue &This, const Expr *E,
1608                             bool AllowNonLiteralTypes = false);
1609 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1610                            bool InvalidBaseOK = false);
1611 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1612                             bool InvalidBaseOK = false);
1613 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1614                                   EvalInfo &Info);
1615 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1616 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1617 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1618                                     EvalInfo &Info);
1619 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1620 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1621 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1622                            EvalInfo &Info);
1623 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1624 
1625 /// Evaluate an integer or fixed point expression into an APResult.
1626 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1627                                         EvalInfo &Info);
1628 
1629 /// Evaluate only a fixed point expression into an APResult.
1630 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1631                                EvalInfo &Info);
1632 
1633 //===----------------------------------------------------------------------===//
1634 // Misc utilities
1635 //===----------------------------------------------------------------------===//
1636 
1637 /// A helper function to create a temporary and set an LValue.
1638 template <class KeyTy>
1639 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1640                                 LValue &LV, CallStackFrame &Frame) {
1641   LV.set({Key, Frame.Info.CurrentCall->Index,
1642           Frame.Info.CurrentCall->getTempVersion()});
1643   return Frame.createTemporary(Key, IsLifetimeExtended);
1644 }
1645 
1646 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1647 /// preserving its value (by extending by up to one bit as needed).
1648 static void negateAsSigned(APSInt &Int) {
1649   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1650     Int = Int.extend(Int.getBitWidth() + 1);
1651     Int.setIsSigned(true);
1652   }
1653   Int = -Int;
1654 }
1655 
1656 /// Produce a string describing the given constexpr call.
1657 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1658   unsigned ArgIndex = 0;
1659   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1660                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1661                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1662 
1663   if (!IsMemberCall)
1664     Out << *Frame->Callee << '(';
1665 
1666   if (Frame->This && IsMemberCall) {
1667     APValue Val;
1668     Frame->This->moveInto(Val);
1669     Val.printPretty(Out, Frame->Info.Ctx,
1670                     Frame->This->Designator.MostDerivedType);
1671     // FIXME: Add parens around Val if needed.
1672     Out << "->" << *Frame->Callee << '(';
1673     IsMemberCall = false;
1674   }
1675 
1676   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1677        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1678     if (ArgIndex > (unsigned)IsMemberCall)
1679       Out << ", ";
1680 
1681     const ParmVarDecl *Param = *I;
1682     const APValue &Arg = Frame->Arguments[ArgIndex];
1683     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1684 
1685     if (ArgIndex == 0 && IsMemberCall)
1686       Out << "->" << *Frame->Callee << '(';
1687   }
1688 
1689   Out << ')';
1690 }
1691 
1692 /// Evaluate an expression to see if it had side-effects, and discard its
1693 /// result.
1694 /// \return \c true if the caller should keep evaluating.
1695 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1696   APValue Scratch;
1697   if (!Evaluate(Scratch, Info, E))
1698     // We don't need the value, but we might have skipped a side effect here.
1699     return Info.noteSideEffect();
1700   return true;
1701 }
1702 
1703 /// Should this call expression be treated as a string literal?
1704 static bool IsStringLiteralCall(const CallExpr *E) {
1705   unsigned Builtin = E->getBuiltinCallee();
1706   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1707           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1708 }
1709 
1710 static bool IsGlobalLValue(APValue::LValueBase B) {
1711   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1712   // constant expression of pointer type that evaluates to...
1713 
1714   // ... a null pointer value, or a prvalue core constant expression of type
1715   // std::nullptr_t.
1716   if (!B) return true;
1717 
1718   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1719     // ... the address of an object with static storage duration,
1720     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1721       return VD->hasGlobalStorage();
1722     // ... the address of a function,
1723     return isa<FunctionDecl>(D);
1724   }
1725 
1726   const Expr *E = B.get<const Expr*>();
1727   switch (E->getStmtClass()) {
1728   default:
1729     return false;
1730   case Expr::CompoundLiteralExprClass: {
1731     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1732     return CLE->isFileScope() && CLE->isLValue();
1733   }
1734   case Expr::MaterializeTemporaryExprClass:
1735     // A materialized temporary might have been lifetime-extended to static
1736     // storage duration.
1737     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1738   // A string literal has static storage duration.
1739   case Expr::StringLiteralClass:
1740   case Expr::PredefinedExprClass:
1741   case Expr::ObjCStringLiteralClass:
1742   case Expr::ObjCEncodeExprClass:
1743   case Expr::CXXTypeidExprClass:
1744   case Expr::CXXUuidofExprClass:
1745     return true;
1746   case Expr::CallExprClass:
1747     return IsStringLiteralCall(cast<CallExpr>(E));
1748   // For GCC compatibility, &&label has static storage duration.
1749   case Expr::AddrLabelExprClass:
1750     return true;
1751   // A Block literal expression may be used as the initialization value for
1752   // Block variables at global or local static scope.
1753   case Expr::BlockExprClass:
1754     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1755   case Expr::ImplicitValueInitExprClass:
1756     // FIXME:
1757     // We can never form an lvalue with an implicit value initialization as its
1758     // base through expression evaluation, so these only appear in one case: the
1759     // implicit variable declaration we invent when checking whether a constexpr
1760     // constructor can produce a constant expression. We must assume that such
1761     // an expression might be a global lvalue.
1762     return true;
1763   }
1764 }
1765 
1766 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1767   return LVal.Base.dyn_cast<const ValueDecl*>();
1768 }
1769 
1770 static bool IsLiteralLValue(const LValue &Value) {
1771   if (Value.getLValueCallIndex())
1772     return false;
1773   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1774   return E && !isa<MaterializeTemporaryExpr>(E);
1775 }
1776 
1777 static bool IsWeakLValue(const LValue &Value) {
1778   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1779   return Decl && Decl->isWeak();
1780 }
1781 
1782 static bool isZeroSized(const LValue &Value) {
1783   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1784   if (Decl && isa<VarDecl>(Decl)) {
1785     QualType Ty = Decl->getType();
1786     if (Ty->isArrayType())
1787       return Ty->isIncompleteType() ||
1788              Decl->getASTContext().getTypeSize(Ty) == 0;
1789   }
1790   return false;
1791 }
1792 
1793 static bool HasSameBase(const LValue &A, const LValue &B) {
1794   if (!A.getLValueBase())
1795     return !B.getLValueBase();
1796   if (!B.getLValueBase())
1797     return false;
1798 
1799   if (A.getLValueBase().getOpaqueValue() !=
1800       B.getLValueBase().getOpaqueValue()) {
1801     const Decl *ADecl = GetLValueBaseDecl(A);
1802     if (!ADecl)
1803       return false;
1804     const Decl *BDecl = GetLValueBaseDecl(B);
1805     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1806       return false;
1807   }
1808 
1809   return IsGlobalLValue(A.getLValueBase()) ||
1810          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1811           A.getLValueVersion() == B.getLValueVersion());
1812 }
1813 
1814 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1815   assert(Base && "no location for a null lvalue");
1816   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1817   if (VD)
1818     Info.Note(VD->getLocation(), diag::note_declared_at);
1819   else
1820     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1821               diag::note_constexpr_temporary_here);
1822 }
1823 
1824 /// Check that this reference or pointer core constant expression is a valid
1825 /// value for an address or reference constant expression. Return true if we
1826 /// can fold this expression, whether or not it's a constant expression.
1827 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1828                                           QualType Type, const LValue &LVal,
1829                                           Expr::ConstExprUsage Usage) {
1830   bool IsReferenceType = Type->isReferenceType();
1831 
1832   APValue::LValueBase Base = LVal.getLValueBase();
1833   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1834 
1835   // Check that the object is a global. Note that the fake 'this' object we
1836   // manufacture when checking potential constant expressions is conservatively
1837   // assumed to be global here.
1838   if (!IsGlobalLValue(Base)) {
1839     if (Info.getLangOpts().CPlusPlus11) {
1840       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1841       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1842         << IsReferenceType << !Designator.Entries.empty()
1843         << !!VD << VD;
1844       NoteLValueLocation(Info, Base);
1845     } else {
1846       Info.FFDiag(Loc);
1847     }
1848     // Don't allow references to temporaries to escape.
1849     return false;
1850   }
1851   assert((Info.checkingPotentialConstantExpression() ||
1852           LVal.getLValueCallIndex() == 0) &&
1853          "have call index for global lvalue");
1854 
1855   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1856     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1857       // Check if this is a thread-local variable.
1858       if (Var->getTLSKind())
1859         return false;
1860 
1861       // A dllimport variable never acts like a constant.
1862       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1863         return false;
1864     }
1865     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1866       // __declspec(dllimport) must be handled very carefully:
1867       // We must never initialize an expression with the thunk in C++.
1868       // Doing otherwise would allow the same id-expression to yield
1869       // different addresses for the same function in different translation
1870       // units.  However, this means that we must dynamically initialize the
1871       // expression with the contents of the import address table at runtime.
1872       //
1873       // The C language has no notion of ODR; furthermore, it has no notion of
1874       // dynamic initialization.  This means that we are permitted to
1875       // perform initialization with the address of the thunk.
1876       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1877           FD->hasAttr<DLLImportAttr>())
1878         return false;
1879     }
1880   }
1881 
1882   // Allow address constant expressions to be past-the-end pointers. This is
1883   // an extension: the standard requires them to point to an object.
1884   if (!IsReferenceType)
1885     return true;
1886 
1887   // A reference constant expression must refer to an object.
1888   if (!Base) {
1889     // FIXME: diagnostic
1890     Info.CCEDiag(Loc);
1891     return true;
1892   }
1893 
1894   // Does this refer one past the end of some object?
1895   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1896     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1897     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1898       << !Designator.Entries.empty() << !!VD << VD;
1899     NoteLValueLocation(Info, Base);
1900   }
1901 
1902   return true;
1903 }
1904 
1905 /// Member pointers are constant expressions unless they point to a
1906 /// non-virtual dllimport member function.
1907 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1908                                                  SourceLocation Loc,
1909                                                  QualType Type,
1910                                                  const APValue &Value,
1911                                                  Expr::ConstExprUsage Usage) {
1912   const ValueDecl *Member = Value.getMemberPointerDecl();
1913   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1914   if (!FD)
1915     return true;
1916   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1917          !FD->hasAttr<DLLImportAttr>();
1918 }
1919 
1920 /// Check that this core constant expression is of literal type, and if not,
1921 /// produce an appropriate diagnostic.
1922 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1923                              const LValue *This = nullptr) {
1924   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1925     return true;
1926 
1927   // C++1y: A constant initializer for an object o [...] may also invoke
1928   // constexpr constructors for o and its subobjects even if those objects
1929   // are of non-literal class types.
1930   //
1931   // C++11 missed this detail for aggregates, so classes like this:
1932   //   struct foo_t { union { int i; volatile int j; } u; };
1933   // are not (obviously) initializable like so:
1934   //   __attribute__((__require_constant_initialization__))
1935   //   static const foo_t x = {{0}};
1936   // because "i" is a subobject with non-literal initialization (due to the
1937   // volatile member of the union). See:
1938   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1939   // Therefore, we use the C++1y behavior.
1940   if (This && Info.EvaluatingDecl == This->getLValueBase())
1941     return true;
1942 
1943   // Prvalue constant expressions must be of literal types.
1944   if (Info.getLangOpts().CPlusPlus11)
1945     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1946       << E->getType();
1947   else
1948     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1949   return false;
1950 }
1951 
1952 /// Check that this core constant expression value is a valid value for a
1953 /// constant expression. If not, report an appropriate diagnostic. Does not
1954 /// check that the expression is of literal type.
1955 static bool
1956 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1957                         const APValue &Value,
1958                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1959   if (Value.isUninit()) {
1960     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1961       << true << Type;
1962     return false;
1963   }
1964 
1965   // We allow _Atomic(T) to be initialized from anything that T can be
1966   // initialized from.
1967   if (const AtomicType *AT = Type->getAs<AtomicType>())
1968     Type = AT->getValueType();
1969 
1970   // Core issue 1454: For a literal constant expression of array or class type,
1971   // each subobject of its value shall have been initialized by a constant
1972   // expression.
1973   if (Value.isArray()) {
1974     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1975     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1976       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1977                                    Value.getArrayInitializedElt(I), Usage))
1978         return false;
1979     }
1980     if (!Value.hasArrayFiller())
1981       return true;
1982     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1983                                    Usage);
1984   }
1985   if (Value.isUnion() && Value.getUnionField()) {
1986     return CheckConstantExpression(Info, DiagLoc,
1987                                    Value.getUnionField()->getType(),
1988                                    Value.getUnionValue(), Usage);
1989   }
1990   if (Value.isStruct()) {
1991     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1992     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1993       unsigned BaseIndex = 0;
1994       for (const CXXBaseSpecifier &BS : CD->bases()) {
1995         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1996                                      Value.getStructBase(BaseIndex), Usage))
1997           return false;
1998         ++BaseIndex;
1999       }
2000     }
2001     for (const auto *I : RD->fields()) {
2002       if (I->isUnnamedBitfield())
2003         continue;
2004 
2005       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2006                                    Value.getStructField(I->getFieldIndex()),
2007                                    Usage))
2008         return false;
2009     }
2010   }
2011 
2012   if (Value.isLValue()) {
2013     LValue LVal;
2014     LVal.setFrom(Info.Ctx, Value);
2015     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2016   }
2017 
2018   if (Value.isMemberPointer())
2019     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2020 
2021   // Everything else is fine.
2022   return true;
2023 }
2024 
2025 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2026   // A null base expression indicates a null pointer.  These are always
2027   // evaluatable, and they are false unless the offset is zero.
2028   if (!Value.getLValueBase()) {
2029     Result = !Value.getLValueOffset().isZero();
2030     return true;
2031   }
2032 
2033   // We have a non-null base.  These are generally known to be true, but if it's
2034   // a weak declaration it can be null at runtime.
2035   Result = true;
2036   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2037   return !Decl || !Decl->isWeak();
2038 }
2039 
2040 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2041   switch (Val.getKind()) {
2042   case APValue::Uninitialized:
2043     return false;
2044   case APValue::Int:
2045     Result = Val.getInt().getBoolValue();
2046     return true;
2047   case APValue::FixedPoint:
2048     Result = Val.getFixedPoint().getBoolValue();
2049     return true;
2050   case APValue::Float:
2051     Result = !Val.getFloat().isZero();
2052     return true;
2053   case APValue::ComplexInt:
2054     Result = Val.getComplexIntReal().getBoolValue() ||
2055              Val.getComplexIntImag().getBoolValue();
2056     return true;
2057   case APValue::ComplexFloat:
2058     Result = !Val.getComplexFloatReal().isZero() ||
2059              !Val.getComplexFloatImag().isZero();
2060     return true;
2061   case APValue::LValue:
2062     return EvalPointerValueAsBool(Val, Result);
2063   case APValue::MemberPointer:
2064     Result = Val.getMemberPointerDecl();
2065     return true;
2066   case APValue::Vector:
2067   case APValue::Array:
2068   case APValue::Struct:
2069   case APValue::Union:
2070   case APValue::AddrLabelDiff:
2071     return false;
2072   }
2073 
2074   llvm_unreachable("unknown APValue kind");
2075 }
2076 
2077 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2078                                        EvalInfo &Info) {
2079   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2080   APValue Val;
2081   if (!Evaluate(Val, Info, E))
2082     return false;
2083   return HandleConversionToBool(Val, Result);
2084 }
2085 
2086 template<typename T>
2087 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2088                            const T &SrcValue, QualType DestType) {
2089   Info.CCEDiag(E, diag::note_constexpr_overflow)
2090     << SrcValue << DestType;
2091   return Info.noteUndefinedBehavior();
2092 }
2093 
2094 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2095                                  QualType SrcType, const APFloat &Value,
2096                                  QualType DestType, APSInt &Result) {
2097   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2098   // Determine whether we are converting to unsigned or signed.
2099   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2100 
2101   Result = APSInt(DestWidth, !DestSigned);
2102   bool ignored;
2103   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2104       & APFloat::opInvalidOp)
2105     return HandleOverflow(Info, E, Value, DestType);
2106   return true;
2107 }
2108 
2109 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2110                                    QualType SrcType, QualType DestType,
2111                                    APFloat &Result) {
2112   APFloat Value = Result;
2113   bool ignored;
2114   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2115                      APFloat::rmNearestTiesToEven, &ignored)
2116       & APFloat::opOverflow)
2117     return HandleOverflow(Info, E, Value, DestType);
2118   return true;
2119 }
2120 
2121 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2122                                  QualType DestType, QualType SrcType,
2123                                  const APSInt &Value) {
2124   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2125   // Figure out if this is a truncate, extend or noop cast.
2126   // If the input is signed, do a sign extend, noop, or truncate.
2127   APSInt Result = Value.extOrTrunc(DestWidth);
2128   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2129   if (DestType->isBooleanType())
2130     Result = Value.getBoolValue();
2131   return Result;
2132 }
2133 
2134 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2135                                  QualType SrcType, const APSInt &Value,
2136                                  QualType DestType, APFloat &Result) {
2137   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2138   if (Result.convertFromAPInt(Value, Value.isSigned(),
2139                               APFloat::rmNearestTiesToEven)
2140       & APFloat::opOverflow)
2141     return HandleOverflow(Info, E, Value, DestType);
2142   return true;
2143 }
2144 
2145 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2146                                   APValue &Value, const FieldDecl *FD) {
2147   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2148 
2149   if (!Value.isInt()) {
2150     // Trying to store a pointer-cast-to-integer into a bitfield.
2151     // FIXME: In this case, we should provide the diagnostic for casting
2152     // a pointer to an integer.
2153     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2154     Info.FFDiag(E);
2155     return false;
2156   }
2157 
2158   APSInt &Int = Value.getInt();
2159   unsigned OldBitWidth = Int.getBitWidth();
2160   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2161   if (NewBitWidth < OldBitWidth)
2162     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2163   return true;
2164 }
2165 
2166 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2167                                   llvm::APInt &Res) {
2168   APValue SVal;
2169   if (!Evaluate(SVal, Info, E))
2170     return false;
2171   if (SVal.isInt()) {
2172     Res = SVal.getInt();
2173     return true;
2174   }
2175   if (SVal.isFloat()) {
2176     Res = SVal.getFloat().bitcastToAPInt();
2177     return true;
2178   }
2179   if (SVal.isVector()) {
2180     QualType VecTy = E->getType();
2181     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2182     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2183     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2184     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2185     Res = llvm::APInt::getNullValue(VecSize);
2186     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2187       APValue &Elt = SVal.getVectorElt(i);
2188       llvm::APInt EltAsInt;
2189       if (Elt.isInt()) {
2190         EltAsInt = Elt.getInt();
2191       } else if (Elt.isFloat()) {
2192         EltAsInt = Elt.getFloat().bitcastToAPInt();
2193       } else {
2194         // Don't try to handle vectors of anything other than int or float
2195         // (not sure if it's possible to hit this case).
2196         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2197         return false;
2198       }
2199       unsigned BaseEltSize = EltAsInt.getBitWidth();
2200       if (BigEndian)
2201         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2202       else
2203         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2204     }
2205     return true;
2206   }
2207   // Give up if the input isn't an int, float, or vector.  For example, we
2208   // reject "(v4i16)(intptr_t)&a".
2209   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2210   return false;
2211 }
2212 
2213 /// Perform the given integer operation, which is known to need at most BitWidth
2214 /// bits, and check for overflow in the original type (if that type was not an
2215 /// unsigned type).
2216 template<typename Operation>
2217 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2218                                  const APSInt &LHS, const APSInt &RHS,
2219                                  unsigned BitWidth, Operation Op,
2220                                  APSInt &Result) {
2221   if (LHS.isUnsigned()) {
2222     Result = Op(LHS, RHS);
2223     return true;
2224   }
2225 
2226   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2227   Result = Value.trunc(LHS.getBitWidth());
2228   if (Result.extend(BitWidth) != Value) {
2229     if (Info.checkingForOverflow())
2230       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2231                                        diag::warn_integer_constant_overflow)
2232           << Result.toString(10) << E->getType();
2233     else
2234       return HandleOverflow(Info, E, Value, E->getType());
2235   }
2236   return true;
2237 }
2238 
2239 /// Perform the given binary integer operation.
2240 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2241                               BinaryOperatorKind Opcode, APSInt RHS,
2242                               APSInt &Result) {
2243   switch (Opcode) {
2244   default:
2245     Info.FFDiag(E);
2246     return false;
2247   case BO_Mul:
2248     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2249                                 std::multiplies<APSInt>(), Result);
2250   case BO_Add:
2251     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2252                                 std::plus<APSInt>(), Result);
2253   case BO_Sub:
2254     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2255                                 std::minus<APSInt>(), Result);
2256   case BO_And: Result = LHS & RHS; return true;
2257   case BO_Xor: Result = LHS ^ RHS; return true;
2258   case BO_Or:  Result = LHS | RHS; return true;
2259   case BO_Div:
2260   case BO_Rem:
2261     if (RHS == 0) {
2262       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2263       return false;
2264     }
2265     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2266     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2267     // this operation and gives the two's complement result.
2268     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2269         LHS.isSigned() && LHS.isMinSignedValue())
2270       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2271                             E->getType());
2272     return true;
2273   case BO_Shl: {
2274     if (Info.getLangOpts().OpenCL)
2275       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2276       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2277                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2278                     RHS.isUnsigned());
2279     else if (RHS.isSigned() && RHS.isNegative()) {
2280       // During constant-folding, a negative shift is an opposite shift. Such
2281       // a shift is not a constant expression.
2282       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2283       RHS = -RHS;
2284       goto shift_right;
2285     }
2286   shift_left:
2287     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2288     // the shifted type.
2289     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2290     if (SA != RHS) {
2291       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2292         << RHS << E->getType() << LHS.getBitWidth();
2293     } else if (LHS.isSigned()) {
2294       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2295       // operand, and must not overflow the corresponding unsigned type.
2296       if (LHS.isNegative())
2297         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2298       else if (LHS.countLeadingZeros() < SA)
2299         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2300     }
2301     Result = LHS << SA;
2302     return true;
2303   }
2304   case BO_Shr: {
2305     if (Info.getLangOpts().OpenCL)
2306       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2307       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2308                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2309                     RHS.isUnsigned());
2310     else if (RHS.isSigned() && RHS.isNegative()) {
2311       // During constant-folding, a negative shift is an opposite shift. Such a
2312       // shift is not a constant expression.
2313       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2314       RHS = -RHS;
2315       goto shift_left;
2316     }
2317   shift_right:
2318     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2319     // shifted type.
2320     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2321     if (SA != RHS)
2322       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2323         << RHS << E->getType() << LHS.getBitWidth();
2324     Result = LHS >> SA;
2325     return true;
2326   }
2327 
2328   case BO_LT: Result = LHS < RHS; return true;
2329   case BO_GT: Result = LHS > RHS; return true;
2330   case BO_LE: Result = LHS <= RHS; return true;
2331   case BO_GE: Result = LHS >= RHS; return true;
2332   case BO_EQ: Result = LHS == RHS; return true;
2333   case BO_NE: Result = LHS != RHS; return true;
2334   case BO_Cmp:
2335     llvm_unreachable("BO_Cmp should be handled elsewhere");
2336   }
2337 }
2338 
2339 /// Perform the given binary floating-point operation, in-place, on LHS.
2340 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2341                                   APFloat &LHS, BinaryOperatorKind Opcode,
2342                                   const APFloat &RHS) {
2343   switch (Opcode) {
2344   default:
2345     Info.FFDiag(E);
2346     return false;
2347   case BO_Mul:
2348     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2349     break;
2350   case BO_Add:
2351     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2352     break;
2353   case BO_Sub:
2354     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2355     break;
2356   case BO_Div:
2357     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2358     break;
2359   }
2360 
2361   if (LHS.isInfinity() || LHS.isNaN()) {
2362     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2363     return Info.noteUndefinedBehavior();
2364   }
2365   return true;
2366 }
2367 
2368 /// Cast an lvalue referring to a base subobject to a derived class, by
2369 /// truncating the lvalue's path to the given length.
2370 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2371                                const RecordDecl *TruncatedType,
2372                                unsigned TruncatedElements) {
2373   SubobjectDesignator &D = Result.Designator;
2374 
2375   // Check we actually point to a derived class object.
2376   if (TruncatedElements == D.Entries.size())
2377     return true;
2378   assert(TruncatedElements >= D.MostDerivedPathLength &&
2379          "not casting to a derived class");
2380   if (!Result.checkSubobject(Info, E, CSK_Derived))
2381     return false;
2382 
2383   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2384   const RecordDecl *RD = TruncatedType;
2385   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2386     if (RD->isInvalidDecl()) return false;
2387     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2388     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2389     if (isVirtualBaseClass(D.Entries[I]))
2390       Result.Offset -= Layout.getVBaseClassOffset(Base);
2391     else
2392       Result.Offset -= Layout.getBaseClassOffset(Base);
2393     RD = Base;
2394   }
2395   D.Entries.resize(TruncatedElements);
2396   return true;
2397 }
2398 
2399 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2400                                    const CXXRecordDecl *Derived,
2401                                    const CXXRecordDecl *Base,
2402                                    const ASTRecordLayout *RL = nullptr) {
2403   if (!RL) {
2404     if (Derived->isInvalidDecl()) return false;
2405     RL = &Info.Ctx.getASTRecordLayout(Derived);
2406   }
2407 
2408   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2409   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2410   return true;
2411 }
2412 
2413 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2414                              const CXXRecordDecl *DerivedDecl,
2415                              const CXXBaseSpecifier *Base) {
2416   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2417 
2418   if (!Base->isVirtual())
2419     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2420 
2421   SubobjectDesignator &D = Obj.Designator;
2422   if (D.Invalid)
2423     return false;
2424 
2425   // Extract most-derived object and corresponding type.
2426   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2427   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2428     return false;
2429 
2430   // Find the virtual base class.
2431   if (DerivedDecl->isInvalidDecl()) return false;
2432   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2433   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2434   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2435   return true;
2436 }
2437 
2438 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2439                                  QualType Type, LValue &Result) {
2440   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2441                                      PathE = E->path_end();
2442        PathI != PathE; ++PathI) {
2443     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2444                           *PathI))
2445       return false;
2446     Type = (*PathI)->getType();
2447   }
2448   return true;
2449 }
2450 
2451 /// Update LVal to refer to the given field, which must be a member of the type
2452 /// currently described by LVal.
2453 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2454                                const FieldDecl *FD,
2455                                const ASTRecordLayout *RL = nullptr) {
2456   if (!RL) {
2457     if (FD->getParent()->isInvalidDecl()) return false;
2458     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2459   }
2460 
2461   unsigned I = FD->getFieldIndex();
2462   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2463   LVal.addDecl(Info, E, FD);
2464   return true;
2465 }
2466 
2467 /// Update LVal to refer to the given indirect field.
2468 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2469                                        LValue &LVal,
2470                                        const IndirectFieldDecl *IFD) {
2471   for (const auto *C : IFD->chain())
2472     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2473       return false;
2474   return true;
2475 }
2476 
2477 /// Get the size of the given type in char units.
2478 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2479                          QualType Type, CharUnits &Size) {
2480   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2481   // extension.
2482   if (Type->isVoidType() || Type->isFunctionType()) {
2483     Size = CharUnits::One();
2484     return true;
2485   }
2486 
2487   if (Type->isDependentType()) {
2488     Info.FFDiag(Loc);
2489     return false;
2490   }
2491 
2492   if (!Type->isConstantSizeType()) {
2493     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2494     // FIXME: Better diagnostic.
2495     Info.FFDiag(Loc);
2496     return false;
2497   }
2498 
2499   Size = Info.Ctx.getTypeSizeInChars(Type);
2500   return true;
2501 }
2502 
2503 /// Update a pointer value to model pointer arithmetic.
2504 /// \param Info - Information about the ongoing evaluation.
2505 /// \param E - The expression being evaluated, for diagnostic purposes.
2506 /// \param LVal - The pointer value to be updated.
2507 /// \param EltTy - The pointee type represented by LVal.
2508 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2509 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2510                                         LValue &LVal, QualType EltTy,
2511                                         APSInt Adjustment) {
2512   CharUnits SizeOfPointee;
2513   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2514     return false;
2515 
2516   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2517   return true;
2518 }
2519 
2520 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2521                                         LValue &LVal, QualType EltTy,
2522                                         int64_t Adjustment) {
2523   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2524                                      APSInt::get(Adjustment));
2525 }
2526 
2527 /// Update an lvalue to refer to a component of a complex number.
2528 /// \param Info - Information about the ongoing evaluation.
2529 /// \param LVal - The lvalue to be updated.
2530 /// \param EltTy - The complex number's component type.
2531 /// \param Imag - False for the real component, true for the imaginary.
2532 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2533                                        LValue &LVal, QualType EltTy,
2534                                        bool Imag) {
2535   if (Imag) {
2536     CharUnits SizeOfComponent;
2537     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2538       return false;
2539     LVal.Offset += SizeOfComponent;
2540   }
2541   LVal.addComplex(Info, E, EltTy, Imag);
2542   return true;
2543 }
2544 
2545 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2546                                            QualType Type, const LValue &LVal,
2547                                            APValue &RVal);
2548 
2549 /// Try to evaluate the initializer for a variable declaration.
2550 ///
2551 /// \param Info   Information about the ongoing evaluation.
2552 /// \param E      An expression to be used when printing diagnostics.
2553 /// \param VD     The variable whose initializer should be obtained.
2554 /// \param Frame  The frame in which the variable was created. Must be null
2555 ///               if this variable is not local to the evaluation.
2556 /// \param Result Filled in with a pointer to the value of the variable.
2557 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2558                                 const VarDecl *VD, CallStackFrame *Frame,
2559                                 APValue *&Result, const LValue *LVal) {
2560 
2561   // If this is a parameter to an active constexpr function call, perform
2562   // argument substitution.
2563   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2564     // Assume arguments of a potential constant expression are unknown
2565     // constant expressions.
2566     if (Info.checkingPotentialConstantExpression())
2567       return false;
2568     if (!Frame || !Frame->Arguments) {
2569       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2570       return false;
2571     }
2572     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2573     return true;
2574   }
2575 
2576   // If this is a local variable, dig out its value.
2577   if (Frame) {
2578     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2579                   : Frame->getCurrentTemporary(VD);
2580     if (!Result) {
2581       // Assume variables referenced within a lambda's call operator that were
2582       // not declared within the call operator are captures and during checking
2583       // of a potential constant expression, assume they are unknown constant
2584       // expressions.
2585       assert(isLambdaCallOperator(Frame->Callee) &&
2586              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2587              "missing value for local variable");
2588       if (Info.checkingPotentialConstantExpression())
2589         return false;
2590       // FIXME: implement capture evaluation during constant expr evaluation.
2591       Info.FFDiag(E->getBeginLoc(),
2592                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2593           << "captures not currently allowed";
2594       return false;
2595     }
2596     return true;
2597   }
2598 
2599   // Dig out the initializer, and use the declaration which it's attached to.
2600   const Expr *Init = VD->getAnyInitializer(VD);
2601   if (!Init || Init->isValueDependent()) {
2602     // If we're checking a potential constant expression, the variable could be
2603     // initialized later.
2604     if (!Info.checkingPotentialConstantExpression())
2605       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2606     return false;
2607   }
2608 
2609   // If we're currently evaluating the initializer of this declaration, use that
2610   // in-flight value.
2611   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2612     Result = Info.EvaluatingDeclValue;
2613     return true;
2614   }
2615 
2616   // Never evaluate the initializer of a weak variable. We can't be sure that
2617   // this is the definition which will be used.
2618   if (VD->isWeak()) {
2619     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2620     return false;
2621   }
2622 
2623   // Check that we can fold the initializer. In C++, we will have already done
2624   // this in the cases where it matters for conformance.
2625   SmallVector<PartialDiagnosticAt, 8> Notes;
2626   if (!VD->evaluateValue(Notes)) {
2627     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2628               Notes.size() + 1) << VD;
2629     Info.Note(VD->getLocation(), diag::note_declared_at);
2630     Info.addNotes(Notes);
2631     return false;
2632   } else if (!VD->checkInitIsICE()) {
2633     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2634                  Notes.size() + 1) << VD;
2635     Info.Note(VD->getLocation(), diag::note_declared_at);
2636     Info.addNotes(Notes);
2637   }
2638 
2639   Result = VD->getEvaluatedValue();
2640   return true;
2641 }
2642 
2643 static bool IsConstNonVolatile(QualType T) {
2644   Qualifiers Quals = T.getQualifiers();
2645   return Quals.hasConst() && !Quals.hasVolatile();
2646 }
2647 
2648 /// Get the base index of the given base class within an APValue representing
2649 /// the given derived class.
2650 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2651                              const CXXRecordDecl *Base) {
2652   Base = Base->getCanonicalDecl();
2653   unsigned Index = 0;
2654   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2655          E = Derived->bases_end(); I != E; ++I, ++Index) {
2656     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2657       return Index;
2658   }
2659 
2660   llvm_unreachable("base class missing from derived class's bases list");
2661 }
2662 
2663 /// Extract the value of a character from a string literal.
2664 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2665                                             uint64_t Index) {
2666   // FIXME: Support MakeStringConstant
2667   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2668     std::string Str;
2669     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2670     assert(Index <= Str.size() && "Index too large");
2671     return APSInt::getUnsigned(Str.c_str()[Index]);
2672   }
2673 
2674   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2675     Lit = PE->getFunctionName();
2676   const StringLiteral *S = cast<StringLiteral>(Lit);
2677   const ConstantArrayType *CAT =
2678       Info.Ctx.getAsConstantArrayType(S->getType());
2679   assert(CAT && "string literal isn't an array");
2680   QualType CharType = CAT->getElementType();
2681   assert(CharType->isIntegerType() && "unexpected character type");
2682 
2683   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2684                CharType->isUnsignedIntegerType());
2685   if (Index < S->getLength())
2686     Value = S->getCodeUnit(Index);
2687   return Value;
2688 }
2689 
2690 // Expand a string literal into an array of characters.
2691 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2692                                 APValue &Result) {
2693   const StringLiteral *S = cast<StringLiteral>(Lit);
2694   const ConstantArrayType *CAT =
2695       Info.Ctx.getAsConstantArrayType(S->getType());
2696   assert(CAT && "string literal isn't an array");
2697   QualType CharType = CAT->getElementType();
2698   assert(CharType->isIntegerType() && "unexpected character type");
2699 
2700   unsigned Elts = CAT->getSize().getZExtValue();
2701   Result = APValue(APValue::UninitArray(),
2702                    std::min(S->getLength(), Elts), Elts);
2703   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2704                CharType->isUnsignedIntegerType());
2705   if (Result.hasArrayFiller())
2706     Result.getArrayFiller() = APValue(Value);
2707   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2708     Value = S->getCodeUnit(I);
2709     Result.getArrayInitializedElt(I) = APValue(Value);
2710   }
2711 }
2712 
2713 // Expand an array so that it has more than Index filled elements.
2714 static void expandArray(APValue &Array, unsigned Index) {
2715   unsigned Size = Array.getArraySize();
2716   assert(Index < Size);
2717 
2718   // Always at least double the number of elements for which we store a value.
2719   unsigned OldElts = Array.getArrayInitializedElts();
2720   unsigned NewElts = std::max(Index+1, OldElts * 2);
2721   NewElts = std::min(Size, std::max(NewElts, 8u));
2722 
2723   // Copy the data across.
2724   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2725   for (unsigned I = 0; I != OldElts; ++I)
2726     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2727   for (unsigned I = OldElts; I != NewElts; ++I)
2728     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2729   if (NewValue.hasArrayFiller())
2730     NewValue.getArrayFiller() = Array.getArrayFiller();
2731   Array.swap(NewValue);
2732 }
2733 
2734 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2735 /// conversion. If it's of class type, we may assume that the copy operation
2736 /// is trivial. Note that this is never true for a union type with fields
2737 /// (because the copy always "reads" the active member) and always true for
2738 /// a non-class type.
2739 static bool isReadByLvalueToRvalueConversion(QualType T) {
2740   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2741   if (!RD || (RD->isUnion() && !RD->field_empty()))
2742     return true;
2743   if (RD->isEmpty())
2744     return false;
2745 
2746   for (auto *Field : RD->fields())
2747     if (isReadByLvalueToRvalueConversion(Field->getType()))
2748       return true;
2749 
2750   for (auto &BaseSpec : RD->bases())
2751     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2752       return true;
2753 
2754   return false;
2755 }
2756 
2757 /// Diagnose an attempt to read from any unreadable field within the specified
2758 /// type, which might be a class type.
2759 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2760                                      QualType T) {
2761   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2762   if (!RD)
2763     return false;
2764 
2765   if (!RD->hasMutableFields())
2766     return false;
2767 
2768   for (auto *Field : RD->fields()) {
2769     // If we're actually going to read this field in some way, then it can't
2770     // be mutable. If we're in a union, then assigning to a mutable field
2771     // (even an empty one) can change the active member, so that's not OK.
2772     // FIXME: Add core issue number for the union case.
2773     if (Field->isMutable() &&
2774         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2775       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2776       Info.Note(Field->getLocation(), diag::note_declared_at);
2777       return true;
2778     }
2779 
2780     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2781       return true;
2782   }
2783 
2784   for (auto &BaseSpec : RD->bases())
2785     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2786       return true;
2787 
2788   // All mutable fields were empty, and thus not actually read.
2789   return false;
2790 }
2791 
2792 namespace {
2793 /// A handle to a complete object (an object that is not a subobject of
2794 /// another object).
2795 struct CompleteObject {
2796   /// The value of the complete object.
2797   APValue *Value;
2798   /// The type of the complete object.
2799   QualType Type;
2800   bool LifetimeStartedInEvaluation;
2801 
2802   CompleteObject() : Value(nullptr) {}
2803   CompleteObject(APValue *Value, QualType Type,
2804                  bool LifetimeStartedInEvaluation)
2805       : Value(Value), Type(Type),
2806         LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2807     assert(Value && "missing value for complete object");
2808   }
2809 
2810   explicit operator bool() const { return Value; }
2811 };
2812 } // end anonymous namespace
2813 
2814 /// Find the designated sub-object of an rvalue.
2815 template<typename SubobjectHandler>
2816 typename SubobjectHandler::result_type
2817 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2818               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2819   if (Sub.Invalid)
2820     // A diagnostic will have already been produced.
2821     return handler.failed();
2822   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2823     if (Info.getLangOpts().CPlusPlus11)
2824       Info.FFDiag(E, Sub.isOnePastTheEnd()
2825                          ? diag::note_constexpr_access_past_end
2826                          : diag::note_constexpr_access_unsized_array)
2827           << handler.AccessKind;
2828     else
2829       Info.FFDiag(E);
2830     return handler.failed();
2831   }
2832 
2833   APValue *O = Obj.Value;
2834   QualType ObjType = Obj.Type;
2835   const FieldDecl *LastField = nullptr;
2836   const bool MayReadMutableMembers =
2837       Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2838 
2839   // Walk the designator's path to find the subobject.
2840   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2841     if (O->isUninit()) {
2842       if (!Info.checkingPotentialConstantExpression())
2843         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2844       return handler.failed();
2845     }
2846 
2847     if (I == N) {
2848       // If we are reading an object of class type, there may still be more
2849       // things we need to check: if there are any mutable subobjects, we
2850       // cannot perform this read. (This only happens when performing a trivial
2851       // copy or assignment.)
2852       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2853           !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2854         return handler.failed();
2855 
2856       if (!handler.found(*O, ObjType))
2857         return false;
2858 
2859       // If we modified a bit-field, truncate it to the right width.
2860       if (handler.AccessKind != AK_Read &&
2861           LastField && LastField->isBitField() &&
2862           !truncateBitfieldValue(Info, E, *O, LastField))
2863         return false;
2864 
2865       return true;
2866     }
2867 
2868     LastField = nullptr;
2869     if (ObjType->isArrayType()) {
2870       // Next subobject is an array element.
2871       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2872       assert(CAT && "vla in literal type?");
2873       uint64_t Index = Sub.Entries[I].ArrayIndex;
2874       if (CAT->getSize().ule(Index)) {
2875         // Note, it should not be possible to form a pointer with a valid
2876         // designator which points more than one past the end of the array.
2877         if (Info.getLangOpts().CPlusPlus11)
2878           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2879             << handler.AccessKind;
2880         else
2881           Info.FFDiag(E);
2882         return handler.failed();
2883       }
2884 
2885       ObjType = CAT->getElementType();
2886 
2887       // An array object is represented as either an Array APValue or as an
2888       // LValue which refers to a string literal.
2889       if (O->isLValue()) {
2890         assert(I == N - 1 && "extracting subobject of character?");
2891         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2892         if (handler.AccessKind != AK_Read)
2893           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2894                               *O);
2895         else
2896           return handler.foundString(*O, ObjType, Index);
2897       }
2898 
2899       if (O->getArrayInitializedElts() > Index)
2900         O = &O->getArrayInitializedElt(Index);
2901       else if (handler.AccessKind != AK_Read) {
2902         expandArray(*O, Index);
2903         O = &O->getArrayInitializedElt(Index);
2904       } else
2905         O = &O->getArrayFiller();
2906     } else if (ObjType->isAnyComplexType()) {
2907       // Next subobject is a complex number.
2908       uint64_t Index = Sub.Entries[I].ArrayIndex;
2909       if (Index > 1) {
2910         if (Info.getLangOpts().CPlusPlus11)
2911           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2912             << handler.AccessKind;
2913         else
2914           Info.FFDiag(E);
2915         return handler.failed();
2916       }
2917 
2918       bool WasConstQualified = ObjType.isConstQualified();
2919       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2920       if (WasConstQualified)
2921         ObjType.addConst();
2922 
2923       assert(I == N - 1 && "extracting subobject of scalar?");
2924       if (O->isComplexInt()) {
2925         return handler.found(Index ? O->getComplexIntImag()
2926                                    : O->getComplexIntReal(), ObjType);
2927       } else {
2928         assert(O->isComplexFloat());
2929         return handler.found(Index ? O->getComplexFloatImag()
2930                                    : O->getComplexFloatReal(), ObjType);
2931       }
2932     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2933       // In C++14 onwards, it is permitted to read a mutable member whose
2934       // lifetime began within the evaluation.
2935       // FIXME: Should we also allow this in C++11?
2936       if (Field->isMutable() && handler.AccessKind == AK_Read &&
2937           !MayReadMutableMembers) {
2938         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2939           << Field;
2940         Info.Note(Field->getLocation(), diag::note_declared_at);
2941         return handler.failed();
2942       }
2943 
2944       // Next subobject is a class, struct or union field.
2945       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2946       if (RD->isUnion()) {
2947         const FieldDecl *UnionField = O->getUnionField();
2948         if (!UnionField ||
2949             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2950           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2951             << handler.AccessKind << Field << !UnionField << UnionField;
2952           return handler.failed();
2953         }
2954         O = &O->getUnionValue();
2955       } else
2956         O = &O->getStructField(Field->getFieldIndex());
2957 
2958       bool WasConstQualified = ObjType.isConstQualified();
2959       ObjType = Field->getType();
2960       if (WasConstQualified && !Field->isMutable())
2961         ObjType.addConst();
2962 
2963       if (ObjType.isVolatileQualified()) {
2964         if (Info.getLangOpts().CPlusPlus) {
2965           // FIXME: Include a description of the path to the volatile subobject.
2966           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2967             << handler.AccessKind << 2 << Field;
2968           Info.Note(Field->getLocation(), diag::note_declared_at);
2969         } else {
2970           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2971         }
2972         return handler.failed();
2973       }
2974 
2975       LastField = Field;
2976     } else {
2977       // Next subobject is a base class.
2978       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2979       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2980       O = &O->getStructBase(getBaseIndex(Derived, Base));
2981 
2982       bool WasConstQualified = ObjType.isConstQualified();
2983       ObjType = Info.Ctx.getRecordType(Base);
2984       if (WasConstQualified)
2985         ObjType.addConst();
2986     }
2987   }
2988 }
2989 
2990 namespace {
2991 struct ExtractSubobjectHandler {
2992   EvalInfo &Info;
2993   APValue &Result;
2994 
2995   static const AccessKinds AccessKind = AK_Read;
2996 
2997   typedef bool result_type;
2998   bool failed() { return false; }
2999   bool found(APValue &Subobj, QualType SubobjType) {
3000     Result = Subobj;
3001     return true;
3002   }
3003   bool found(APSInt &Value, QualType SubobjType) {
3004     Result = APValue(Value);
3005     return true;
3006   }
3007   bool found(APFloat &Value, QualType SubobjType) {
3008     Result = APValue(Value);
3009     return true;
3010   }
3011   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3012     Result = APValue(extractStringLiteralCharacter(
3013         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
3014     return true;
3015   }
3016 };
3017 } // end anonymous namespace
3018 
3019 const AccessKinds ExtractSubobjectHandler::AccessKind;
3020 
3021 /// Extract the designated sub-object of an rvalue.
3022 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3023                              const CompleteObject &Obj,
3024                              const SubobjectDesignator &Sub,
3025                              APValue &Result) {
3026   ExtractSubobjectHandler Handler = { Info, Result };
3027   return findSubobject(Info, E, Obj, Sub, Handler);
3028 }
3029 
3030 namespace {
3031 struct ModifySubobjectHandler {
3032   EvalInfo &Info;
3033   APValue &NewVal;
3034   const Expr *E;
3035 
3036   typedef bool result_type;
3037   static const AccessKinds AccessKind = AK_Assign;
3038 
3039   bool checkConst(QualType QT) {
3040     // Assigning to a const object has undefined behavior.
3041     if (QT.isConstQualified()) {
3042       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3043       return false;
3044     }
3045     return true;
3046   }
3047 
3048   bool failed() { return false; }
3049   bool found(APValue &Subobj, QualType SubobjType) {
3050     if (!checkConst(SubobjType))
3051       return false;
3052     // We've been given ownership of NewVal, so just swap it in.
3053     Subobj.swap(NewVal);
3054     return true;
3055   }
3056   bool found(APSInt &Value, QualType SubobjType) {
3057     if (!checkConst(SubobjType))
3058       return false;
3059     if (!NewVal.isInt()) {
3060       // Maybe trying to write a cast pointer value into a complex?
3061       Info.FFDiag(E);
3062       return false;
3063     }
3064     Value = NewVal.getInt();
3065     return true;
3066   }
3067   bool found(APFloat &Value, QualType SubobjType) {
3068     if (!checkConst(SubobjType))
3069       return false;
3070     Value = NewVal.getFloat();
3071     return true;
3072   }
3073   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3074     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3075   }
3076 };
3077 } // end anonymous namespace
3078 
3079 const AccessKinds ModifySubobjectHandler::AccessKind;
3080 
3081 /// Update the designated sub-object of an rvalue to the given value.
3082 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3083                             const CompleteObject &Obj,
3084                             const SubobjectDesignator &Sub,
3085                             APValue &NewVal) {
3086   ModifySubobjectHandler Handler = { Info, NewVal, E };
3087   return findSubobject(Info, E, Obj, Sub, Handler);
3088 }
3089 
3090 /// Find the position where two subobject designators diverge, or equivalently
3091 /// the length of the common initial subsequence.
3092 static unsigned FindDesignatorMismatch(QualType ObjType,
3093                                        const SubobjectDesignator &A,
3094                                        const SubobjectDesignator &B,
3095                                        bool &WasArrayIndex) {
3096   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3097   for (/**/; I != N; ++I) {
3098     if (!ObjType.isNull() &&
3099         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3100       // Next subobject is an array element.
3101       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3102         WasArrayIndex = true;
3103         return I;
3104       }
3105       if (ObjType->isAnyComplexType())
3106         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3107       else
3108         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3109     } else {
3110       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3111         WasArrayIndex = false;
3112         return I;
3113       }
3114       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3115         // Next subobject is a field.
3116         ObjType = FD->getType();
3117       else
3118         // Next subobject is a base class.
3119         ObjType = QualType();
3120     }
3121   }
3122   WasArrayIndex = false;
3123   return I;
3124 }
3125 
3126 /// Determine whether the given subobject designators refer to elements of the
3127 /// same array object.
3128 static bool AreElementsOfSameArray(QualType ObjType,
3129                                    const SubobjectDesignator &A,
3130                                    const SubobjectDesignator &B) {
3131   if (A.Entries.size() != B.Entries.size())
3132     return false;
3133 
3134   bool IsArray = A.MostDerivedIsArrayElement;
3135   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3136     // A is a subobject of the array element.
3137     return false;
3138 
3139   // If A (and B) designates an array element, the last entry will be the array
3140   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3141   // of length 1' case, and the entire path must match.
3142   bool WasArrayIndex;
3143   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3144   return CommonLength >= A.Entries.size() - IsArray;
3145 }
3146 
3147 /// Find the complete object to which an LValue refers.
3148 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3149                                          AccessKinds AK, const LValue &LVal,
3150                                          QualType LValType) {
3151   if (!LVal.Base) {
3152     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3153     return CompleteObject();
3154   }
3155 
3156   CallStackFrame *Frame = nullptr;
3157   if (LVal.getLValueCallIndex()) {
3158     Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3159     if (!Frame) {
3160       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3161         << AK << LVal.Base.is<const ValueDecl*>();
3162       NoteLValueLocation(Info, LVal.Base);
3163       return CompleteObject();
3164     }
3165   }
3166 
3167   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3168   // is not a constant expression (even if the object is non-volatile). We also
3169   // apply this rule to C++98, in order to conform to the expected 'volatile'
3170   // semantics.
3171   if (LValType.isVolatileQualified()) {
3172     if (Info.getLangOpts().CPlusPlus)
3173       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3174         << AK << LValType;
3175     else
3176       Info.FFDiag(E);
3177     return CompleteObject();
3178   }
3179 
3180   // Compute value storage location and type of base object.
3181   APValue *BaseVal = nullptr;
3182   QualType BaseType = getType(LVal.Base);
3183   bool LifetimeStartedInEvaluation = Frame;
3184 
3185   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3186     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3187     // In C++11, constexpr, non-volatile variables initialized with constant
3188     // expressions are constant expressions too. Inside constexpr functions,
3189     // parameters are constant expressions even if they're non-const.
3190     // In C++1y, objects local to a constant expression (those with a Frame) are
3191     // both readable and writable inside constant expressions.
3192     // In C, such things can also be folded, although they are not ICEs.
3193     const VarDecl *VD = dyn_cast<VarDecl>(D);
3194     if (VD) {
3195       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3196         VD = VDef;
3197     }
3198     if (!VD || VD->isInvalidDecl()) {
3199       Info.FFDiag(E);
3200       return CompleteObject();
3201     }
3202 
3203     // Accesses of volatile-qualified objects are not allowed.
3204     if (BaseType.isVolatileQualified()) {
3205       if (Info.getLangOpts().CPlusPlus) {
3206         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3207           << AK << 1 << VD;
3208         Info.Note(VD->getLocation(), diag::note_declared_at);
3209       } else {
3210         Info.FFDiag(E);
3211       }
3212       return CompleteObject();
3213     }
3214 
3215     // Unless we're looking at a local variable or argument in a constexpr call,
3216     // the variable we're reading must be const.
3217     if (!Frame) {
3218       if (Info.getLangOpts().CPlusPlus14 &&
3219           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3220         // OK, we can read and modify an object if we're in the process of
3221         // evaluating its initializer, because its lifetime began in this
3222         // evaluation.
3223       } else if (AK != AK_Read) {
3224         // All the remaining cases only permit reading.
3225         Info.FFDiag(E, diag::note_constexpr_modify_global);
3226         return CompleteObject();
3227       } else if (VD->isConstexpr()) {
3228         // OK, we can read this variable.
3229       } else if (BaseType->isIntegralOrEnumerationType()) {
3230         // In OpenCL if a variable is in constant address space it is a const value.
3231         if (!(BaseType.isConstQualified() ||
3232               (Info.getLangOpts().OpenCL &&
3233                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3234           if (Info.getLangOpts().CPlusPlus) {
3235             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3236             Info.Note(VD->getLocation(), diag::note_declared_at);
3237           } else {
3238             Info.FFDiag(E);
3239           }
3240           return CompleteObject();
3241         }
3242       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3243         // We support folding of const floating-point types, in order to make
3244         // static const data members of such types (supported as an extension)
3245         // more useful.
3246         if (Info.getLangOpts().CPlusPlus11) {
3247           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3248           Info.Note(VD->getLocation(), diag::note_declared_at);
3249         } else {
3250           Info.CCEDiag(E);
3251         }
3252       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3253         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3254         // Keep evaluating to see what we can do.
3255       } else {
3256         // FIXME: Allow folding of values of any literal type in all languages.
3257         if (Info.checkingPotentialConstantExpression() &&
3258             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3259           // The definition of this variable could be constexpr. We can't
3260           // access it right now, but may be able to in future.
3261         } else if (Info.getLangOpts().CPlusPlus11) {
3262           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3263           Info.Note(VD->getLocation(), diag::note_declared_at);
3264         } else {
3265           Info.FFDiag(E);
3266         }
3267         return CompleteObject();
3268       }
3269     }
3270 
3271     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3272       return CompleteObject();
3273   } else {
3274     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3275 
3276     if (!Frame) {
3277       if (const MaterializeTemporaryExpr *MTE =
3278               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3279         assert(MTE->getStorageDuration() == SD_Static &&
3280                "should have a frame for a non-global materialized temporary");
3281 
3282         // Per C++1y [expr.const]p2:
3283         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3284         //   - a [...] glvalue of integral or enumeration type that refers to
3285         //     a non-volatile const object [...]
3286         //   [...]
3287         //   - a [...] glvalue of literal type that refers to a non-volatile
3288         //     object whose lifetime began within the evaluation of e.
3289         //
3290         // C++11 misses the 'began within the evaluation of e' check and
3291         // instead allows all temporaries, including things like:
3292         //   int &&r = 1;
3293         //   int x = ++r;
3294         //   constexpr int k = r;
3295         // Therefore we use the C++14 rules in C++11 too.
3296         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3297         const ValueDecl *ED = MTE->getExtendingDecl();
3298         if (!(BaseType.isConstQualified() &&
3299               BaseType->isIntegralOrEnumerationType()) &&
3300             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3301           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3302           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3303           return CompleteObject();
3304         }
3305 
3306         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3307         assert(BaseVal && "got reference to unevaluated temporary");
3308         LifetimeStartedInEvaluation = true;
3309       } else {
3310         Info.FFDiag(E);
3311         return CompleteObject();
3312       }
3313     } else {
3314       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3315       assert(BaseVal && "missing value for temporary");
3316     }
3317 
3318     // Volatile temporary objects cannot be accessed in constant expressions.
3319     if (BaseType.isVolatileQualified()) {
3320       if (Info.getLangOpts().CPlusPlus) {
3321         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3322           << AK << 0;
3323         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3324       } else {
3325         Info.FFDiag(E);
3326       }
3327       return CompleteObject();
3328     }
3329   }
3330 
3331   // During the construction of an object, it is not yet 'const'.
3332   // FIXME: This doesn't do quite the right thing for const subobjects of the
3333   // object under construction.
3334   if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3335                                    LVal.getLValueCallIndex(),
3336                                    LVal.getLValueVersion())) {
3337     BaseType = Info.Ctx.getCanonicalType(BaseType);
3338     BaseType.removeLocalConst();
3339     LifetimeStartedInEvaluation = true;
3340   }
3341 
3342   // In C++14, we can't safely access any mutable state when we might be
3343   // evaluating after an unmodeled side effect.
3344   //
3345   // FIXME: Not all local state is mutable. Allow local constant subobjects
3346   // to be read here (but take care with 'mutable' fields).
3347   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3348        Info.EvalStatus.HasSideEffects) ||
3349       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3350     return CompleteObject();
3351 
3352   return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3353 }
3354 
3355 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3356 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3357 /// glvalue referred to by an entity of reference type.
3358 ///
3359 /// \param Info - Information about the ongoing evaluation.
3360 /// \param Conv - The expression for which we are performing the conversion.
3361 ///               Used for diagnostics.
3362 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3363 ///               case of a non-class type).
3364 /// \param LVal - The glvalue on which we are attempting to perform this action.
3365 /// \param RVal - The produced value will be placed here.
3366 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3367                                            QualType Type,
3368                                            const LValue &LVal, APValue &RVal) {
3369   if (LVal.Designator.Invalid)
3370     return false;
3371 
3372   // Check for special cases where there is no existing APValue to look at.
3373   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3374   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3375     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3376       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3377       // initializer until now for such expressions. Such an expression can't be
3378       // an ICE in C, so this only matters for fold.
3379       if (Type.isVolatileQualified()) {
3380         Info.FFDiag(Conv);
3381         return false;
3382       }
3383       APValue Lit;
3384       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3385         return false;
3386       CompleteObject LitObj(&Lit, Base->getType(), false);
3387       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3388     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3389       // We represent a string literal array as an lvalue pointing at the
3390       // corresponding expression, rather than building an array of chars.
3391       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3392       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3393       CompleteObject StrObj(&Str, Base->getType(), false);
3394       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3395     }
3396   }
3397 
3398   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3399   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3400 }
3401 
3402 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3403 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3404                              QualType LValType, APValue &Val) {
3405   if (LVal.Designator.Invalid)
3406     return false;
3407 
3408   if (!Info.getLangOpts().CPlusPlus14) {
3409     Info.FFDiag(E);
3410     return false;
3411   }
3412 
3413   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3414   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3415 }
3416 
3417 namespace {
3418 struct CompoundAssignSubobjectHandler {
3419   EvalInfo &Info;
3420   const Expr *E;
3421   QualType PromotedLHSType;
3422   BinaryOperatorKind Opcode;
3423   const APValue &RHS;
3424 
3425   static const AccessKinds AccessKind = AK_Assign;
3426 
3427   typedef bool result_type;
3428 
3429   bool checkConst(QualType QT) {
3430     // Assigning to a const object has undefined behavior.
3431     if (QT.isConstQualified()) {
3432       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3433       return false;
3434     }
3435     return true;
3436   }
3437 
3438   bool failed() { return false; }
3439   bool found(APValue &Subobj, QualType SubobjType) {
3440     switch (Subobj.getKind()) {
3441     case APValue::Int:
3442       return found(Subobj.getInt(), SubobjType);
3443     case APValue::Float:
3444       return found(Subobj.getFloat(), SubobjType);
3445     case APValue::ComplexInt:
3446     case APValue::ComplexFloat:
3447       // FIXME: Implement complex compound assignment.
3448       Info.FFDiag(E);
3449       return false;
3450     case APValue::LValue:
3451       return foundPointer(Subobj, SubobjType);
3452     default:
3453       // FIXME: can this happen?
3454       Info.FFDiag(E);
3455       return false;
3456     }
3457   }
3458   bool found(APSInt &Value, QualType SubobjType) {
3459     if (!checkConst(SubobjType))
3460       return false;
3461 
3462     if (!SubobjType->isIntegerType()) {
3463       // We don't support compound assignment on integer-cast-to-pointer
3464       // values.
3465       Info.FFDiag(E);
3466       return false;
3467     }
3468 
3469     if (RHS.isInt()) {
3470       APSInt LHS =
3471           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3472       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3473         return false;
3474       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3475       return true;
3476     } else if (RHS.isFloat()) {
3477       APFloat FValue(0.0);
3478       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3479                                   FValue) &&
3480              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3481              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3482                                   Value);
3483     }
3484 
3485     Info.FFDiag(E);
3486     return false;
3487   }
3488   bool found(APFloat &Value, QualType SubobjType) {
3489     return checkConst(SubobjType) &&
3490            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3491                                   Value) &&
3492            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3493            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3494   }
3495   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3496     if (!checkConst(SubobjType))
3497       return false;
3498 
3499     QualType PointeeType;
3500     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3501       PointeeType = PT->getPointeeType();
3502 
3503     if (PointeeType.isNull() || !RHS.isInt() ||
3504         (Opcode != BO_Add && Opcode != BO_Sub)) {
3505       Info.FFDiag(E);
3506       return false;
3507     }
3508 
3509     APSInt Offset = RHS.getInt();
3510     if (Opcode == BO_Sub)
3511       negateAsSigned(Offset);
3512 
3513     LValue LVal;
3514     LVal.setFrom(Info.Ctx, Subobj);
3515     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3516       return false;
3517     LVal.moveInto(Subobj);
3518     return true;
3519   }
3520   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3521     llvm_unreachable("shouldn't encounter string elements here");
3522   }
3523 };
3524 } // end anonymous namespace
3525 
3526 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3527 
3528 /// Perform a compound assignment of LVal <op>= RVal.
3529 static bool handleCompoundAssignment(
3530     EvalInfo &Info, const Expr *E,
3531     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3532     BinaryOperatorKind Opcode, const APValue &RVal) {
3533   if (LVal.Designator.Invalid)
3534     return false;
3535 
3536   if (!Info.getLangOpts().CPlusPlus14) {
3537     Info.FFDiag(E);
3538     return false;
3539   }
3540 
3541   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3542   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3543                                              RVal };
3544   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3545 }
3546 
3547 namespace {
3548 struct IncDecSubobjectHandler {
3549   EvalInfo &Info;
3550   const UnaryOperator *E;
3551   AccessKinds AccessKind;
3552   APValue *Old;
3553 
3554   typedef bool result_type;
3555 
3556   bool checkConst(QualType QT) {
3557     // Assigning to a const object has undefined behavior.
3558     if (QT.isConstQualified()) {
3559       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3560       return false;
3561     }
3562     return true;
3563   }
3564 
3565   bool failed() { return false; }
3566   bool found(APValue &Subobj, QualType SubobjType) {
3567     // Stash the old value. Also clear Old, so we don't clobber it later
3568     // if we're post-incrementing a complex.
3569     if (Old) {
3570       *Old = Subobj;
3571       Old = nullptr;
3572     }
3573 
3574     switch (Subobj.getKind()) {
3575     case APValue::Int:
3576       return found(Subobj.getInt(), SubobjType);
3577     case APValue::Float:
3578       return found(Subobj.getFloat(), SubobjType);
3579     case APValue::ComplexInt:
3580       return found(Subobj.getComplexIntReal(),
3581                    SubobjType->castAs<ComplexType>()->getElementType()
3582                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3583     case APValue::ComplexFloat:
3584       return found(Subobj.getComplexFloatReal(),
3585                    SubobjType->castAs<ComplexType>()->getElementType()
3586                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3587     case APValue::LValue:
3588       return foundPointer(Subobj, SubobjType);
3589     default:
3590       // FIXME: can this happen?
3591       Info.FFDiag(E);
3592       return false;
3593     }
3594   }
3595   bool found(APSInt &Value, QualType SubobjType) {
3596     if (!checkConst(SubobjType))
3597       return false;
3598 
3599     if (!SubobjType->isIntegerType()) {
3600       // We don't support increment / decrement on integer-cast-to-pointer
3601       // values.
3602       Info.FFDiag(E);
3603       return false;
3604     }
3605 
3606     if (Old) *Old = APValue(Value);
3607 
3608     // bool arithmetic promotes to int, and the conversion back to bool
3609     // doesn't reduce mod 2^n, so special-case it.
3610     if (SubobjType->isBooleanType()) {
3611       if (AccessKind == AK_Increment)
3612         Value = 1;
3613       else
3614         Value = !Value;
3615       return true;
3616     }
3617 
3618     bool WasNegative = Value.isNegative();
3619     if (AccessKind == AK_Increment) {
3620       ++Value;
3621 
3622       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3623         APSInt ActualValue(Value, /*IsUnsigned*/true);
3624         return HandleOverflow(Info, E, ActualValue, SubobjType);
3625       }
3626     } else {
3627       --Value;
3628 
3629       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3630         unsigned BitWidth = Value.getBitWidth();
3631         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3632         ActualValue.setBit(BitWidth);
3633         return HandleOverflow(Info, E, ActualValue, SubobjType);
3634       }
3635     }
3636     return true;
3637   }
3638   bool found(APFloat &Value, QualType SubobjType) {
3639     if (!checkConst(SubobjType))
3640       return false;
3641 
3642     if (Old) *Old = APValue(Value);
3643 
3644     APFloat One(Value.getSemantics(), 1);
3645     if (AccessKind == AK_Increment)
3646       Value.add(One, APFloat::rmNearestTiesToEven);
3647     else
3648       Value.subtract(One, APFloat::rmNearestTiesToEven);
3649     return true;
3650   }
3651   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3652     if (!checkConst(SubobjType))
3653       return false;
3654 
3655     QualType PointeeType;
3656     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3657       PointeeType = PT->getPointeeType();
3658     else {
3659       Info.FFDiag(E);
3660       return false;
3661     }
3662 
3663     LValue LVal;
3664     LVal.setFrom(Info.Ctx, Subobj);
3665     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3666                                      AccessKind == AK_Increment ? 1 : -1))
3667       return false;
3668     LVal.moveInto(Subobj);
3669     return true;
3670   }
3671   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3672     llvm_unreachable("shouldn't encounter string elements here");
3673   }
3674 };
3675 } // end anonymous namespace
3676 
3677 /// Perform an increment or decrement on LVal.
3678 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3679                          QualType LValType, bool IsIncrement, APValue *Old) {
3680   if (LVal.Designator.Invalid)
3681     return false;
3682 
3683   if (!Info.getLangOpts().CPlusPlus14) {
3684     Info.FFDiag(E);
3685     return false;
3686   }
3687 
3688   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3689   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3690   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3691   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3692 }
3693 
3694 /// Build an lvalue for the object argument of a member function call.
3695 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3696                                    LValue &This) {
3697   if (Object->getType()->isPointerType())
3698     return EvaluatePointer(Object, This, Info);
3699 
3700   if (Object->isGLValue())
3701     return EvaluateLValue(Object, This, Info);
3702 
3703   if (Object->getType()->isLiteralType(Info.Ctx))
3704     return EvaluateTemporary(Object, This, Info);
3705 
3706   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3707   return false;
3708 }
3709 
3710 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3711 /// lvalue referring to the result.
3712 ///
3713 /// \param Info - Information about the ongoing evaluation.
3714 /// \param LV - An lvalue referring to the base of the member pointer.
3715 /// \param RHS - The member pointer expression.
3716 /// \param IncludeMember - Specifies whether the member itself is included in
3717 ///        the resulting LValue subobject designator. This is not possible when
3718 ///        creating a bound member function.
3719 /// \return The field or method declaration to which the member pointer refers,
3720 ///         or 0 if evaluation fails.
3721 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3722                                                   QualType LVType,
3723                                                   LValue &LV,
3724                                                   const Expr *RHS,
3725                                                   bool IncludeMember = true) {
3726   MemberPtr MemPtr;
3727   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3728     return nullptr;
3729 
3730   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3731   // member value, the behavior is undefined.
3732   if (!MemPtr.getDecl()) {
3733     // FIXME: Specific diagnostic.
3734     Info.FFDiag(RHS);
3735     return nullptr;
3736   }
3737 
3738   if (MemPtr.isDerivedMember()) {
3739     // This is a member of some derived class. Truncate LV appropriately.
3740     // The end of the derived-to-base path for the base object must match the
3741     // derived-to-base path for the member pointer.
3742     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3743         LV.Designator.Entries.size()) {
3744       Info.FFDiag(RHS);
3745       return nullptr;
3746     }
3747     unsigned PathLengthToMember =
3748         LV.Designator.Entries.size() - MemPtr.Path.size();
3749     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3750       const CXXRecordDecl *LVDecl = getAsBaseClass(
3751           LV.Designator.Entries[PathLengthToMember + I]);
3752       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3753       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3754         Info.FFDiag(RHS);
3755         return nullptr;
3756       }
3757     }
3758 
3759     // Truncate the lvalue to the appropriate derived class.
3760     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3761                             PathLengthToMember))
3762       return nullptr;
3763   } else if (!MemPtr.Path.empty()) {
3764     // Extend the LValue path with the member pointer's path.
3765     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3766                                   MemPtr.Path.size() + IncludeMember);
3767 
3768     // Walk down to the appropriate base class.
3769     if (const PointerType *PT = LVType->getAs<PointerType>())
3770       LVType = PT->getPointeeType();
3771     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3772     assert(RD && "member pointer access on non-class-type expression");
3773     // The first class in the path is that of the lvalue.
3774     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3775       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3776       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3777         return nullptr;
3778       RD = Base;
3779     }
3780     // Finally cast to the class containing the member.
3781     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3782                                 MemPtr.getContainingRecord()))
3783       return nullptr;
3784   }
3785 
3786   // Add the member. Note that we cannot build bound member functions here.
3787   if (IncludeMember) {
3788     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3789       if (!HandleLValueMember(Info, RHS, LV, FD))
3790         return nullptr;
3791     } else if (const IndirectFieldDecl *IFD =
3792                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3793       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3794         return nullptr;
3795     } else {
3796       llvm_unreachable("can't construct reference to bound member function");
3797     }
3798   }
3799 
3800   return MemPtr.getDecl();
3801 }
3802 
3803 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3804                                                   const BinaryOperator *BO,
3805                                                   LValue &LV,
3806                                                   bool IncludeMember = true) {
3807   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3808 
3809   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3810     if (Info.noteFailure()) {
3811       MemberPtr MemPtr;
3812       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3813     }
3814     return nullptr;
3815   }
3816 
3817   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3818                                    BO->getRHS(), IncludeMember);
3819 }
3820 
3821 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3822 /// the provided lvalue, which currently refers to the base object.
3823 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3824                                     LValue &Result) {
3825   SubobjectDesignator &D = Result.Designator;
3826   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3827     return false;
3828 
3829   QualType TargetQT = E->getType();
3830   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3831     TargetQT = PT->getPointeeType();
3832 
3833   // Check this cast lands within the final derived-to-base subobject path.
3834   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3835     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3836       << D.MostDerivedType << TargetQT;
3837     return false;
3838   }
3839 
3840   // Check the type of the final cast. We don't need to check the path,
3841   // since a cast can only be formed if the path is unique.
3842   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3843   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3844   const CXXRecordDecl *FinalType;
3845   if (NewEntriesSize == D.MostDerivedPathLength)
3846     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3847   else
3848     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3849   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3850     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3851       << D.MostDerivedType << TargetQT;
3852     return false;
3853   }
3854 
3855   // Truncate the lvalue to the appropriate derived class.
3856   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3857 }
3858 
3859 namespace {
3860 enum EvalStmtResult {
3861   /// Evaluation failed.
3862   ESR_Failed,
3863   /// Hit a 'return' statement.
3864   ESR_Returned,
3865   /// Evaluation succeeded.
3866   ESR_Succeeded,
3867   /// Hit a 'continue' statement.
3868   ESR_Continue,
3869   /// Hit a 'break' statement.
3870   ESR_Break,
3871   /// Still scanning for 'case' or 'default' statement.
3872   ESR_CaseNotFound
3873 };
3874 }
3875 
3876 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3877   // We don't need to evaluate the initializer for a static local.
3878   if (!VD->hasLocalStorage())
3879     return true;
3880 
3881   LValue Result;
3882   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3883 
3884   const Expr *InitE = VD->getInit();
3885   if (!InitE) {
3886     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3887         << false << VD->getType();
3888     Val = APValue();
3889     return false;
3890   }
3891 
3892   if (InitE->isValueDependent())
3893     return false;
3894 
3895   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3896     // Wipe out any partially-computed value, to allow tracking that this
3897     // evaluation failed.
3898     Val = APValue();
3899     return false;
3900   }
3901 
3902   return true;
3903 }
3904 
3905 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3906   bool OK = true;
3907 
3908   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3909     OK &= EvaluateVarDecl(Info, VD);
3910 
3911   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3912     for (auto *BD : DD->bindings())
3913       if (auto *VD = BD->getHoldingVar())
3914         OK &= EvaluateDecl(Info, VD);
3915 
3916   return OK;
3917 }
3918 
3919 
3920 /// Evaluate a condition (either a variable declaration or an expression).
3921 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3922                          const Expr *Cond, bool &Result) {
3923   FullExpressionRAII Scope(Info);
3924   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3925     return false;
3926   return EvaluateAsBooleanCondition(Cond, Result, Info);
3927 }
3928 
3929 namespace {
3930 /// A location where the result (returned value) of evaluating a
3931 /// statement should be stored.
3932 struct StmtResult {
3933   /// The APValue that should be filled in with the returned value.
3934   APValue &Value;
3935   /// The location containing the result, if any (used to support RVO).
3936   const LValue *Slot;
3937 };
3938 
3939 struct TempVersionRAII {
3940   CallStackFrame &Frame;
3941 
3942   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3943     Frame.pushTempVersion();
3944   }
3945 
3946   ~TempVersionRAII() {
3947     Frame.popTempVersion();
3948   }
3949 };
3950 
3951 }
3952 
3953 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3954                                    const Stmt *S,
3955                                    const SwitchCase *SC = nullptr);
3956 
3957 /// Evaluate the body of a loop, and translate the result as appropriate.
3958 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3959                                        const Stmt *Body,
3960                                        const SwitchCase *Case = nullptr) {
3961   BlockScopeRAII Scope(Info);
3962   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3963   case ESR_Break:
3964     return ESR_Succeeded;
3965   case ESR_Succeeded:
3966   case ESR_Continue:
3967     return ESR_Continue;
3968   case ESR_Failed:
3969   case ESR_Returned:
3970   case ESR_CaseNotFound:
3971     return ESR;
3972   }
3973   llvm_unreachable("Invalid EvalStmtResult!");
3974 }
3975 
3976 /// Evaluate a switch statement.
3977 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3978                                      const SwitchStmt *SS) {
3979   BlockScopeRAII Scope(Info);
3980 
3981   // Evaluate the switch condition.
3982   APSInt Value;
3983   {
3984     FullExpressionRAII Scope(Info);
3985     if (const Stmt *Init = SS->getInit()) {
3986       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3987       if (ESR != ESR_Succeeded)
3988         return ESR;
3989     }
3990     if (SS->getConditionVariable() &&
3991         !EvaluateDecl(Info, SS->getConditionVariable()))
3992       return ESR_Failed;
3993     if (!EvaluateInteger(SS->getCond(), Value, Info))
3994       return ESR_Failed;
3995   }
3996 
3997   // Find the switch case corresponding to the value of the condition.
3998   // FIXME: Cache this lookup.
3999   const SwitchCase *Found = nullptr;
4000   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4001        SC = SC->getNextSwitchCase()) {
4002     if (isa<DefaultStmt>(SC)) {
4003       Found = SC;
4004       continue;
4005     }
4006 
4007     const CaseStmt *CS = cast<CaseStmt>(SC);
4008     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4009     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4010                               : LHS;
4011     if (LHS <= Value && Value <= RHS) {
4012       Found = SC;
4013       break;
4014     }
4015   }
4016 
4017   if (!Found)
4018     return ESR_Succeeded;
4019 
4020   // Search the switch body for the switch case and evaluate it from there.
4021   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4022   case ESR_Break:
4023     return ESR_Succeeded;
4024   case ESR_Succeeded:
4025   case ESR_Continue:
4026   case ESR_Failed:
4027   case ESR_Returned:
4028     return ESR;
4029   case ESR_CaseNotFound:
4030     // This can only happen if the switch case is nested within a statement
4031     // expression. We have no intention of supporting that.
4032     Info.FFDiag(Found->getBeginLoc(),
4033                 diag::note_constexpr_stmt_expr_unsupported);
4034     return ESR_Failed;
4035   }
4036   llvm_unreachable("Invalid EvalStmtResult!");
4037 }
4038 
4039 // Evaluate a statement.
4040 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4041                                    const Stmt *S, const SwitchCase *Case) {
4042   if (!Info.nextStep(S))
4043     return ESR_Failed;
4044 
4045   // If we're hunting down a 'case' or 'default' label, recurse through
4046   // substatements until we hit the label.
4047   if (Case) {
4048     // FIXME: We don't start the lifetime of objects whose initialization we
4049     // jump over. However, such objects must be of class type with a trivial
4050     // default constructor that initialize all subobjects, so must be empty,
4051     // so this almost never matters.
4052     switch (S->getStmtClass()) {
4053     case Stmt::CompoundStmtClass:
4054       // FIXME: Precompute which substatement of a compound statement we
4055       // would jump to, and go straight there rather than performing a
4056       // linear scan each time.
4057     case Stmt::LabelStmtClass:
4058     case Stmt::AttributedStmtClass:
4059     case Stmt::DoStmtClass:
4060       break;
4061 
4062     case Stmt::CaseStmtClass:
4063     case Stmt::DefaultStmtClass:
4064       if (Case == S)
4065         Case = nullptr;
4066       break;
4067 
4068     case Stmt::IfStmtClass: {
4069       // FIXME: Precompute which side of an 'if' we would jump to, and go
4070       // straight there rather than scanning both sides.
4071       const IfStmt *IS = cast<IfStmt>(S);
4072 
4073       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4074       // preceded by our switch label.
4075       BlockScopeRAII Scope(Info);
4076 
4077       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4078       if (ESR != ESR_CaseNotFound || !IS->getElse())
4079         return ESR;
4080       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4081     }
4082 
4083     case Stmt::WhileStmtClass: {
4084       EvalStmtResult ESR =
4085           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4086       if (ESR != ESR_Continue)
4087         return ESR;
4088       break;
4089     }
4090 
4091     case Stmt::ForStmtClass: {
4092       const ForStmt *FS = cast<ForStmt>(S);
4093       EvalStmtResult ESR =
4094           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4095       if (ESR != ESR_Continue)
4096         return ESR;
4097       if (FS->getInc()) {
4098         FullExpressionRAII IncScope(Info);
4099         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4100           return ESR_Failed;
4101       }
4102       break;
4103     }
4104 
4105     case Stmt::DeclStmtClass:
4106       // FIXME: If the variable has initialization that can't be jumped over,
4107       // bail out of any immediately-surrounding compound-statement too.
4108     default:
4109       return ESR_CaseNotFound;
4110     }
4111   }
4112 
4113   switch (S->getStmtClass()) {
4114   default:
4115     if (const Expr *E = dyn_cast<Expr>(S)) {
4116       // Don't bother evaluating beyond an expression-statement which couldn't
4117       // be evaluated.
4118       FullExpressionRAII Scope(Info);
4119       if (!EvaluateIgnoredValue(Info, E))
4120         return ESR_Failed;
4121       return ESR_Succeeded;
4122     }
4123 
4124     Info.FFDiag(S->getBeginLoc());
4125     return ESR_Failed;
4126 
4127   case Stmt::NullStmtClass:
4128     return ESR_Succeeded;
4129 
4130   case Stmt::DeclStmtClass: {
4131     const DeclStmt *DS = cast<DeclStmt>(S);
4132     for (const auto *DclIt : DS->decls()) {
4133       // Each declaration initialization is its own full-expression.
4134       // FIXME: This isn't quite right; if we're performing aggregate
4135       // initialization, each braced subexpression is its own full-expression.
4136       FullExpressionRAII Scope(Info);
4137       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4138         return ESR_Failed;
4139     }
4140     return ESR_Succeeded;
4141   }
4142 
4143   case Stmt::ReturnStmtClass: {
4144     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4145     FullExpressionRAII Scope(Info);
4146     if (RetExpr &&
4147         !(Result.Slot
4148               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4149               : Evaluate(Result.Value, Info, RetExpr)))
4150       return ESR_Failed;
4151     return ESR_Returned;
4152   }
4153 
4154   case Stmt::CompoundStmtClass: {
4155     BlockScopeRAII Scope(Info);
4156 
4157     const CompoundStmt *CS = cast<CompoundStmt>(S);
4158     for (const auto *BI : CS->body()) {
4159       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4160       if (ESR == ESR_Succeeded)
4161         Case = nullptr;
4162       else if (ESR != ESR_CaseNotFound)
4163         return ESR;
4164     }
4165     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4166   }
4167 
4168   case Stmt::IfStmtClass: {
4169     const IfStmt *IS = cast<IfStmt>(S);
4170 
4171     // Evaluate the condition, as either a var decl or as an expression.
4172     BlockScopeRAII Scope(Info);
4173     if (const Stmt *Init = IS->getInit()) {
4174       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4175       if (ESR != ESR_Succeeded)
4176         return ESR;
4177     }
4178     bool Cond;
4179     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4180       return ESR_Failed;
4181 
4182     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4183       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4184       if (ESR != ESR_Succeeded)
4185         return ESR;
4186     }
4187     return ESR_Succeeded;
4188   }
4189 
4190   case Stmt::WhileStmtClass: {
4191     const WhileStmt *WS = cast<WhileStmt>(S);
4192     while (true) {
4193       BlockScopeRAII Scope(Info);
4194       bool Continue;
4195       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4196                         Continue))
4197         return ESR_Failed;
4198       if (!Continue)
4199         break;
4200 
4201       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4202       if (ESR != ESR_Continue)
4203         return ESR;
4204     }
4205     return ESR_Succeeded;
4206   }
4207 
4208   case Stmt::DoStmtClass: {
4209     const DoStmt *DS = cast<DoStmt>(S);
4210     bool Continue;
4211     do {
4212       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4213       if (ESR != ESR_Continue)
4214         return ESR;
4215       Case = nullptr;
4216 
4217       FullExpressionRAII CondScope(Info);
4218       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4219         return ESR_Failed;
4220     } while (Continue);
4221     return ESR_Succeeded;
4222   }
4223 
4224   case Stmt::ForStmtClass: {
4225     const ForStmt *FS = cast<ForStmt>(S);
4226     BlockScopeRAII Scope(Info);
4227     if (FS->getInit()) {
4228       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4229       if (ESR != ESR_Succeeded)
4230         return ESR;
4231     }
4232     while (true) {
4233       BlockScopeRAII Scope(Info);
4234       bool Continue = true;
4235       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4236                                          FS->getCond(), Continue))
4237         return ESR_Failed;
4238       if (!Continue)
4239         break;
4240 
4241       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4242       if (ESR != ESR_Continue)
4243         return ESR;
4244 
4245       if (FS->getInc()) {
4246         FullExpressionRAII IncScope(Info);
4247         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4248           return ESR_Failed;
4249       }
4250     }
4251     return ESR_Succeeded;
4252   }
4253 
4254   case Stmt::CXXForRangeStmtClass: {
4255     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4256     BlockScopeRAII Scope(Info);
4257 
4258     // Evaluate the init-statement if present.
4259     if (FS->getInit()) {
4260       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4261       if (ESR != ESR_Succeeded)
4262         return ESR;
4263     }
4264 
4265     // Initialize the __range variable.
4266     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4267     if (ESR != ESR_Succeeded)
4268       return ESR;
4269 
4270     // Create the __begin and __end iterators.
4271     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4272     if (ESR != ESR_Succeeded)
4273       return ESR;
4274     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4275     if (ESR != ESR_Succeeded)
4276       return ESR;
4277 
4278     while (true) {
4279       // Condition: __begin != __end.
4280       {
4281         bool Continue = true;
4282         FullExpressionRAII CondExpr(Info);
4283         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4284           return ESR_Failed;
4285         if (!Continue)
4286           break;
4287       }
4288 
4289       // User's variable declaration, initialized by *__begin.
4290       BlockScopeRAII InnerScope(Info);
4291       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4292       if (ESR != ESR_Succeeded)
4293         return ESR;
4294 
4295       // Loop body.
4296       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4297       if (ESR != ESR_Continue)
4298         return ESR;
4299 
4300       // Increment: ++__begin
4301       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4302         return ESR_Failed;
4303     }
4304 
4305     return ESR_Succeeded;
4306   }
4307 
4308   case Stmt::SwitchStmtClass:
4309     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4310 
4311   case Stmt::ContinueStmtClass:
4312     return ESR_Continue;
4313 
4314   case Stmt::BreakStmtClass:
4315     return ESR_Break;
4316 
4317   case Stmt::LabelStmtClass:
4318     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4319 
4320   case Stmt::AttributedStmtClass:
4321     // As a general principle, C++11 attributes can be ignored without
4322     // any semantic impact.
4323     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4324                         Case);
4325 
4326   case Stmt::CaseStmtClass:
4327   case Stmt::DefaultStmtClass:
4328     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4329   case Stmt::CXXTryStmtClass:
4330     // Evaluate try blocks by evaluating all sub statements.
4331     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4332   }
4333 }
4334 
4335 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4336 /// default constructor. If so, we'll fold it whether or not it's marked as
4337 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4338 /// so we need special handling.
4339 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4340                                            const CXXConstructorDecl *CD,
4341                                            bool IsValueInitialization) {
4342   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4343     return false;
4344 
4345   // Value-initialization does not call a trivial default constructor, so such a
4346   // call is a core constant expression whether or not the constructor is
4347   // constexpr.
4348   if (!CD->isConstexpr() && !IsValueInitialization) {
4349     if (Info.getLangOpts().CPlusPlus11) {
4350       // FIXME: If DiagDecl is an implicitly-declared special member function,
4351       // we should be much more explicit about why it's not constexpr.
4352       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4353         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4354       Info.Note(CD->getLocation(), diag::note_declared_at);
4355     } else {
4356       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4357     }
4358   }
4359   return true;
4360 }
4361 
4362 /// CheckConstexprFunction - Check that a function can be called in a constant
4363 /// expression.
4364 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4365                                    const FunctionDecl *Declaration,
4366                                    const FunctionDecl *Definition,
4367                                    const Stmt *Body) {
4368   // Potential constant expressions can contain calls to declared, but not yet
4369   // defined, constexpr functions.
4370   if (Info.checkingPotentialConstantExpression() && !Definition &&
4371       Declaration->isConstexpr())
4372     return false;
4373 
4374   // Bail out if the function declaration itself is invalid.  We will
4375   // have produced a relevant diagnostic while parsing it, so just
4376   // note the problematic sub-expression.
4377   if (Declaration->isInvalidDecl()) {
4378     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4379     return false;
4380   }
4381 
4382   // Can we evaluate this function call?
4383   if (Definition && Definition->isConstexpr() &&
4384       !Definition->isInvalidDecl() && Body)
4385     return true;
4386 
4387   if (Info.getLangOpts().CPlusPlus11) {
4388     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4389 
4390     // If this function is not constexpr because it is an inherited
4391     // non-constexpr constructor, diagnose that directly.
4392     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4393     if (CD && CD->isInheritingConstructor()) {
4394       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4395       if (!Inherited->isConstexpr())
4396         DiagDecl = CD = Inherited;
4397     }
4398 
4399     // FIXME: If DiagDecl is an implicitly-declared special member function
4400     // or an inheriting constructor, we should be much more explicit about why
4401     // it's not constexpr.
4402     if (CD && CD->isInheritingConstructor())
4403       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4404         << CD->getInheritedConstructor().getConstructor()->getParent();
4405     else
4406       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4407         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4408     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4409   } else {
4410     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4411   }
4412   return false;
4413 }
4414 
4415 /// Determine if a class has any fields that might need to be copied by a
4416 /// trivial copy or move operation.
4417 static bool hasFields(const CXXRecordDecl *RD) {
4418   if (!RD || RD->isEmpty())
4419     return false;
4420   for (auto *FD : RD->fields()) {
4421     if (FD->isUnnamedBitfield())
4422       continue;
4423     return true;
4424   }
4425   for (auto &Base : RD->bases())
4426     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4427       return true;
4428   return false;
4429 }
4430 
4431 namespace {
4432 typedef SmallVector<APValue, 8> ArgVector;
4433 }
4434 
4435 /// EvaluateArgs - Evaluate the arguments to a function call.
4436 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4437                          EvalInfo &Info) {
4438   bool Success = true;
4439   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4440        I != E; ++I) {
4441     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4442       // If we're checking for a potential constant expression, evaluate all
4443       // initializers even if some of them fail.
4444       if (!Info.noteFailure())
4445         return false;
4446       Success = false;
4447     }
4448   }
4449   return Success;
4450 }
4451 
4452 /// Evaluate a function call.
4453 static bool HandleFunctionCall(SourceLocation CallLoc,
4454                                const FunctionDecl *Callee, const LValue *This,
4455                                ArrayRef<const Expr*> Args, const Stmt *Body,
4456                                EvalInfo &Info, APValue &Result,
4457                                const LValue *ResultSlot) {
4458   ArgVector ArgValues(Args.size());
4459   if (!EvaluateArgs(Args, ArgValues, Info))
4460     return false;
4461 
4462   if (!Info.CheckCallLimit(CallLoc))
4463     return false;
4464 
4465   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4466 
4467   // For a trivial copy or move assignment, perform an APValue copy. This is
4468   // essential for unions, where the operations performed by the assignment
4469   // operator cannot be represented as statements.
4470   //
4471   // Skip this for non-union classes with no fields; in that case, the defaulted
4472   // copy/move does not actually read the object.
4473   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4474   if (MD && MD->isDefaulted() &&
4475       (MD->getParent()->isUnion() ||
4476        (MD->isTrivial() && hasFields(MD->getParent())))) {
4477     assert(This &&
4478            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4479     LValue RHS;
4480     RHS.setFrom(Info.Ctx, ArgValues[0]);
4481     APValue RHSValue;
4482     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4483                                         RHS, RHSValue))
4484       return false;
4485     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
4486                           RHSValue))
4487       return false;
4488     This->moveInto(Result);
4489     return true;
4490   } else if (MD && isLambdaCallOperator(MD)) {
4491     // We're in a lambda; determine the lambda capture field maps unless we're
4492     // just constexpr checking a lambda's call operator. constexpr checking is
4493     // done before the captures have been added to the closure object (unless
4494     // we're inferring constexpr-ness), so we don't have access to them in this
4495     // case. But since we don't need the captures to constexpr check, we can
4496     // just ignore them.
4497     if (!Info.checkingPotentialConstantExpression())
4498       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4499                                         Frame.LambdaThisCaptureField);
4500   }
4501 
4502   StmtResult Ret = {Result, ResultSlot};
4503   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4504   if (ESR == ESR_Succeeded) {
4505     if (Callee->getReturnType()->isVoidType())
4506       return true;
4507     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4508   }
4509   return ESR == ESR_Returned;
4510 }
4511 
4512 /// Evaluate a constructor call.
4513 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4514                                   APValue *ArgValues,
4515                                   const CXXConstructorDecl *Definition,
4516                                   EvalInfo &Info, APValue &Result) {
4517   SourceLocation CallLoc = E->getExprLoc();
4518   if (!Info.CheckCallLimit(CallLoc))
4519     return false;
4520 
4521   const CXXRecordDecl *RD = Definition->getParent();
4522   if (RD->getNumVBases()) {
4523     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4524     return false;
4525   }
4526 
4527   EvalInfo::EvaluatingConstructorRAII EvalObj(
4528       Info, {This.getLValueBase(),
4529              {This.getLValueCallIndex(), This.getLValueVersion()}});
4530   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4531 
4532   // FIXME: Creating an APValue just to hold a nonexistent return value is
4533   // wasteful.
4534   APValue RetVal;
4535   StmtResult Ret = {RetVal, nullptr};
4536 
4537   // If it's a delegating constructor, delegate.
4538   if (Definition->isDelegatingConstructor()) {
4539     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4540     {
4541       FullExpressionRAII InitScope(Info);
4542       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4543         return false;
4544     }
4545     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4546   }
4547 
4548   // For a trivial copy or move constructor, perform an APValue copy. This is
4549   // essential for unions (or classes with anonymous union members), where the
4550   // operations performed by the constructor cannot be represented by
4551   // ctor-initializers.
4552   //
4553   // Skip this for empty non-union classes; we should not perform an
4554   // lvalue-to-rvalue conversion on them because their copy constructor does not
4555   // actually read them.
4556   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4557       (Definition->getParent()->isUnion() ||
4558        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4559     LValue RHS;
4560     RHS.setFrom(Info.Ctx, ArgValues[0]);
4561     return handleLValueToRValueConversion(
4562         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4563         RHS, Result);
4564   }
4565 
4566   // Reserve space for the struct members.
4567   if (!RD->isUnion() && Result.isUninit())
4568     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4569                      std::distance(RD->field_begin(), RD->field_end()));
4570 
4571   if (RD->isInvalidDecl()) return false;
4572   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4573 
4574   // A scope for temporaries lifetime-extended by reference members.
4575   BlockScopeRAII LifetimeExtendedScope(Info);
4576 
4577   bool Success = true;
4578   unsigned BasesSeen = 0;
4579 #ifndef NDEBUG
4580   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4581 #endif
4582   for (const auto *I : Definition->inits()) {
4583     LValue Subobject = This;
4584     LValue SubobjectParent = This;
4585     APValue *Value = &Result;
4586 
4587     // Determine the subobject to initialize.
4588     FieldDecl *FD = nullptr;
4589     if (I->isBaseInitializer()) {
4590       QualType BaseType(I->getBaseClass(), 0);
4591 #ifndef NDEBUG
4592       // Non-virtual base classes are initialized in the order in the class
4593       // definition. We have already checked for virtual base classes.
4594       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4595       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4596              "base class initializers not in expected order");
4597       ++BaseIt;
4598 #endif
4599       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4600                                   BaseType->getAsCXXRecordDecl(), &Layout))
4601         return false;
4602       Value = &Result.getStructBase(BasesSeen++);
4603     } else if ((FD = I->getMember())) {
4604       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4605         return false;
4606       if (RD->isUnion()) {
4607         Result = APValue(FD);
4608         Value = &Result.getUnionValue();
4609       } else {
4610         Value = &Result.getStructField(FD->getFieldIndex());
4611       }
4612     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4613       // Walk the indirect field decl's chain to find the object to initialize,
4614       // and make sure we've initialized every step along it.
4615       auto IndirectFieldChain = IFD->chain();
4616       for (auto *C : IndirectFieldChain) {
4617         FD = cast<FieldDecl>(C);
4618         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4619         // Switch the union field if it differs. This happens if we had
4620         // preceding zero-initialization, and we're now initializing a union
4621         // subobject other than the first.
4622         // FIXME: In this case, the values of the other subobjects are
4623         // specified, since zero-initialization sets all padding bits to zero.
4624         if (Value->isUninit() ||
4625             (Value->isUnion() && Value->getUnionField() != FD)) {
4626           if (CD->isUnion())
4627             *Value = APValue(FD);
4628           else
4629             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4630                              std::distance(CD->field_begin(), CD->field_end()));
4631         }
4632         // Store Subobject as its parent before updating it for the last element
4633         // in the chain.
4634         if (C == IndirectFieldChain.back())
4635           SubobjectParent = Subobject;
4636         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4637           return false;
4638         if (CD->isUnion())
4639           Value = &Value->getUnionValue();
4640         else
4641           Value = &Value->getStructField(FD->getFieldIndex());
4642       }
4643     } else {
4644       llvm_unreachable("unknown base initializer kind");
4645     }
4646 
4647     // Need to override This for implicit field initializers as in this case
4648     // This refers to innermost anonymous struct/union containing initializer,
4649     // not to currently constructed class.
4650     const Expr *Init = I->getInit();
4651     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4652                                   isa<CXXDefaultInitExpr>(Init));
4653     FullExpressionRAII InitScope(Info);
4654     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4655         (FD && FD->isBitField() &&
4656          !truncateBitfieldValue(Info, Init, *Value, FD))) {
4657       // If we're checking for a potential constant expression, evaluate all
4658       // initializers even if some of them fail.
4659       if (!Info.noteFailure())
4660         return false;
4661       Success = false;
4662     }
4663   }
4664 
4665   return Success &&
4666          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4667 }
4668 
4669 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4670                                   ArrayRef<const Expr*> Args,
4671                                   const CXXConstructorDecl *Definition,
4672                                   EvalInfo &Info, APValue &Result) {
4673   ArgVector ArgValues(Args.size());
4674   if (!EvaluateArgs(Args, ArgValues, Info))
4675     return false;
4676 
4677   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4678                                Info, Result);
4679 }
4680 
4681 //===----------------------------------------------------------------------===//
4682 // Generic Evaluation
4683 //===----------------------------------------------------------------------===//
4684 namespace {
4685 
4686 template <class Derived>
4687 class ExprEvaluatorBase
4688   : public ConstStmtVisitor<Derived, bool> {
4689 private:
4690   Derived &getDerived() { return static_cast<Derived&>(*this); }
4691   bool DerivedSuccess(const APValue &V, const Expr *E) {
4692     return getDerived().Success(V, E);
4693   }
4694   bool DerivedZeroInitialization(const Expr *E) {
4695     return getDerived().ZeroInitialization(E);
4696   }
4697 
4698   // Check whether a conditional operator with a non-constant condition is a
4699   // potential constant expression. If neither arm is a potential constant
4700   // expression, then the conditional operator is not either.
4701   template<typename ConditionalOperator>
4702   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4703     assert(Info.checkingPotentialConstantExpression());
4704 
4705     // Speculatively evaluate both arms.
4706     SmallVector<PartialDiagnosticAt, 8> Diag;
4707     {
4708       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4709       StmtVisitorTy::Visit(E->getFalseExpr());
4710       if (Diag.empty())
4711         return;
4712     }
4713 
4714     {
4715       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4716       Diag.clear();
4717       StmtVisitorTy::Visit(E->getTrueExpr());
4718       if (Diag.empty())
4719         return;
4720     }
4721 
4722     Error(E, diag::note_constexpr_conditional_never_const);
4723   }
4724 
4725 
4726   template<typename ConditionalOperator>
4727   bool HandleConditionalOperator(const ConditionalOperator *E) {
4728     bool BoolResult;
4729     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4730       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4731         CheckPotentialConstantConditional(E);
4732         return false;
4733       }
4734       if (Info.noteFailure()) {
4735         StmtVisitorTy::Visit(E->getTrueExpr());
4736         StmtVisitorTy::Visit(E->getFalseExpr());
4737       }
4738       return false;
4739     }
4740 
4741     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4742     return StmtVisitorTy::Visit(EvalExpr);
4743   }
4744 
4745 protected:
4746   EvalInfo &Info;
4747   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4748   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4749 
4750   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4751     return Info.CCEDiag(E, D);
4752   }
4753 
4754   bool ZeroInitialization(const Expr *E) { return Error(E); }
4755 
4756 public:
4757   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4758 
4759   EvalInfo &getEvalInfo() { return Info; }
4760 
4761   /// Report an evaluation error. This should only be called when an error is
4762   /// first discovered. When propagating an error, just return false.
4763   bool Error(const Expr *E, diag::kind D) {
4764     Info.FFDiag(E, D);
4765     return false;
4766   }
4767   bool Error(const Expr *E) {
4768     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4769   }
4770 
4771   bool VisitStmt(const Stmt *) {
4772     llvm_unreachable("Expression evaluator should not be called on stmts");
4773   }
4774   bool VisitExpr(const Expr *E) {
4775     return Error(E);
4776   }
4777 
4778   bool VisitConstantExpr(const ConstantExpr *E)
4779     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4780   bool VisitParenExpr(const ParenExpr *E)
4781     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4782   bool VisitUnaryExtension(const UnaryOperator *E)
4783     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4784   bool VisitUnaryPlus(const UnaryOperator *E)
4785     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4786   bool VisitChooseExpr(const ChooseExpr *E)
4787     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4788   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4789     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4790   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4791     { return StmtVisitorTy::Visit(E->getReplacement()); }
4792   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4793     TempVersionRAII RAII(*Info.CurrentCall);
4794     return StmtVisitorTy::Visit(E->getExpr());
4795   }
4796   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4797     TempVersionRAII RAII(*Info.CurrentCall);
4798     // The initializer may not have been parsed yet, or might be erroneous.
4799     if (!E->getExpr())
4800       return Error(E);
4801     return StmtVisitorTy::Visit(E->getExpr());
4802   }
4803   // We cannot create any objects for which cleanups are required, so there is
4804   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4805   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4806     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4807 
4808   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4809     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4810     return static_cast<Derived*>(this)->VisitCastExpr(E);
4811   }
4812   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4813     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4814     return static_cast<Derived*>(this)->VisitCastExpr(E);
4815   }
4816 
4817   bool VisitBinaryOperator(const BinaryOperator *E) {
4818     switch (E->getOpcode()) {
4819     default:
4820       return Error(E);
4821 
4822     case BO_Comma:
4823       VisitIgnoredValue(E->getLHS());
4824       return StmtVisitorTy::Visit(E->getRHS());
4825 
4826     case BO_PtrMemD:
4827     case BO_PtrMemI: {
4828       LValue Obj;
4829       if (!HandleMemberPointerAccess(Info, E, Obj))
4830         return false;
4831       APValue Result;
4832       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4833         return false;
4834       return DerivedSuccess(Result, E);
4835     }
4836     }
4837   }
4838 
4839   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4840     // Evaluate and cache the common expression. We treat it as a temporary,
4841     // even though it's not quite the same thing.
4842     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4843                   Info, E->getCommon()))
4844       return false;
4845 
4846     return HandleConditionalOperator(E);
4847   }
4848 
4849   bool VisitConditionalOperator(const ConditionalOperator *E) {
4850     bool IsBcpCall = false;
4851     // If the condition (ignoring parens) is a __builtin_constant_p call,
4852     // the result is a constant expression if it can be folded without
4853     // side-effects. This is an important GNU extension. See GCC PR38377
4854     // for discussion.
4855     if (const CallExpr *CallCE =
4856           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4857       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4858         IsBcpCall = true;
4859 
4860     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4861     // constant expression; we can't check whether it's potentially foldable.
4862     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4863       return false;
4864 
4865     FoldConstant Fold(Info, IsBcpCall);
4866     if (!HandleConditionalOperator(E)) {
4867       Fold.keepDiagnostics();
4868       return false;
4869     }
4870 
4871     return true;
4872   }
4873 
4874   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4875     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4876       return DerivedSuccess(*Value, E);
4877 
4878     const Expr *Source = E->getSourceExpr();
4879     if (!Source)
4880       return Error(E);
4881     if (Source == E) { // sanity checking.
4882       assert(0 && "OpaqueValueExpr recursively refers to itself");
4883       return Error(E);
4884     }
4885     return StmtVisitorTy::Visit(Source);
4886   }
4887 
4888   bool VisitCallExpr(const CallExpr *E) {
4889     APValue Result;
4890     if (!handleCallExpr(E, Result, nullptr))
4891       return false;
4892     return DerivedSuccess(Result, E);
4893   }
4894 
4895   bool handleCallExpr(const CallExpr *E, APValue &Result,
4896                      const LValue *ResultSlot) {
4897     const Expr *Callee = E->getCallee()->IgnoreParens();
4898     QualType CalleeType = Callee->getType();
4899 
4900     const FunctionDecl *FD = nullptr;
4901     LValue *This = nullptr, ThisVal;
4902     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4903     bool HasQualifier = false;
4904 
4905     // Extract function decl and 'this' pointer from the callee.
4906     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4907       const ValueDecl *Member = nullptr;
4908       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4909         // Explicit bound member calls, such as x.f() or p->g();
4910         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4911           return false;
4912         Member = ME->getMemberDecl();
4913         This = &ThisVal;
4914         HasQualifier = ME->hasQualifier();
4915       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4916         // Indirect bound member calls ('.*' or '->*').
4917         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4918         if (!Member) return false;
4919         This = &ThisVal;
4920       } else
4921         return Error(Callee);
4922 
4923       FD = dyn_cast<FunctionDecl>(Member);
4924       if (!FD)
4925         return Error(Callee);
4926     } else if (CalleeType->isFunctionPointerType()) {
4927       LValue Call;
4928       if (!EvaluatePointer(Callee, Call, Info))
4929         return false;
4930 
4931       if (!Call.getLValueOffset().isZero())
4932         return Error(Callee);
4933       FD = dyn_cast_or_null<FunctionDecl>(
4934                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4935       if (!FD)
4936         return Error(Callee);
4937       // Don't call function pointers which have been cast to some other type.
4938       // Per DR (no number yet), the caller and callee can differ in noexcept.
4939       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4940         CalleeType->getPointeeType(), FD->getType())) {
4941         return Error(E);
4942       }
4943 
4944       // Overloaded operator calls to member functions are represented as normal
4945       // calls with '*this' as the first argument.
4946       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4947       if (MD && !MD->isStatic()) {
4948         // FIXME: When selecting an implicit conversion for an overloaded
4949         // operator delete, we sometimes try to evaluate calls to conversion
4950         // operators without a 'this' parameter!
4951         if (Args.empty())
4952           return Error(E);
4953 
4954         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4955           return false;
4956         This = &ThisVal;
4957         Args = Args.slice(1);
4958       } else if (MD && MD->isLambdaStaticInvoker()) {
4959         // Map the static invoker for the lambda back to the call operator.
4960         // Conveniently, we don't have to slice out the 'this' argument (as is
4961         // being done for the non-static case), since a static member function
4962         // doesn't have an implicit argument passed in.
4963         const CXXRecordDecl *ClosureClass = MD->getParent();
4964         assert(
4965             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4966             "Number of captures must be zero for conversion to function-ptr");
4967 
4968         const CXXMethodDecl *LambdaCallOp =
4969             ClosureClass->getLambdaCallOperator();
4970 
4971         // Set 'FD', the function that will be called below, to the call
4972         // operator.  If the closure object represents a generic lambda, find
4973         // the corresponding specialization of the call operator.
4974 
4975         if (ClosureClass->isGenericLambda()) {
4976           assert(MD->isFunctionTemplateSpecialization() &&
4977                  "A generic lambda's static-invoker function must be a "
4978                  "template specialization");
4979           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4980           FunctionTemplateDecl *CallOpTemplate =
4981               LambdaCallOp->getDescribedFunctionTemplate();
4982           void *InsertPos = nullptr;
4983           FunctionDecl *CorrespondingCallOpSpecialization =
4984               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4985           assert(CorrespondingCallOpSpecialization &&
4986                  "We must always have a function call operator specialization "
4987                  "that corresponds to our static invoker specialization");
4988           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4989         } else
4990           FD = LambdaCallOp;
4991       }
4992 
4993 
4994     } else
4995       return Error(E);
4996 
4997     if (This && !This->checkSubobject(Info, E, CSK_This))
4998       return false;
4999 
5000     // DR1358 allows virtual constexpr functions in some cases. Don't allow
5001     // calls to such functions in constant expressions.
5002     if (This && !HasQualifier &&
5003         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
5004       return Error(E, diag::note_constexpr_virtual_call);
5005 
5006     const FunctionDecl *Definition = nullptr;
5007     Stmt *Body = FD->getBody(Definition);
5008 
5009     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5010         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
5011                             Result, ResultSlot))
5012       return false;
5013 
5014     return true;
5015   }
5016 
5017   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5018     return StmtVisitorTy::Visit(E->getInitializer());
5019   }
5020   bool VisitInitListExpr(const InitListExpr *E) {
5021     if (E->getNumInits() == 0)
5022       return DerivedZeroInitialization(E);
5023     if (E->getNumInits() == 1)
5024       return StmtVisitorTy::Visit(E->getInit(0));
5025     return Error(E);
5026   }
5027   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5028     return DerivedZeroInitialization(E);
5029   }
5030   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5031     return DerivedZeroInitialization(E);
5032   }
5033   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5034     return DerivedZeroInitialization(E);
5035   }
5036 
5037   /// A member expression where the object is a prvalue is itself a prvalue.
5038   bool VisitMemberExpr(const MemberExpr *E) {
5039     assert(!E->isArrow() && "missing call to bound member function?");
5040 
5041     APValue Val;
5042     if (!Evaluate(Val, Info, E->getBase()))
5043       return false;
5044 
5045     QualType BaseTy = E->getBase()->getType();
5046 
5047     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5048     if (!FD) return Error(E);
5049     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5050     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5051            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5052 
5053     CompleteObject Obj(&Val, BaseTy, true);
5054     SubobjectDesignator Designator(BaseTy);
5055     Designator.addDeclUnchecked(FD);
5056 
5057     APValue Result;
5058     return extractSubobject(Info, E, Obj, Designator, Result) &&
5059            DerivedSuccess(Result, E);
5060   }
5061 
5062   bool VisitCastExpr(const CastExpr *E) {
5063     switch (E->getCastKind()) {
5064     default:
5065       break;
5066 
5067     case CK_AtomicToNonAtomic: {
5068       APValue AtomicVal;
5069       // This does not need to be done in place even for class/array types:
5070       // atomic-to-non-atomic conversion implies copying the object
5071       // representation.
5072       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5073         return false;
5074       return DerivedSuccess(AtomicVal, E);
5075     }
5076 
5077     case CK_NoOp:
5078     case CK_UserDefinedConversion:
5079       return StmtVisitorTy::Visit(E->getSubExpr());
5080 
5081     case CK_LValueToRValue: {
5082       LValue LVal;
5083       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5084         return false;
5085       APValue RVal;
5086       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5087       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5088                                           LVal, RVal))
5089         return false;
5090       return DerivedSuccess(RVal, E);
5091     }
5092     }
5093 
5094     return Error(E);
5095   }
5096 
5097   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5098     return VisitUnaryPostIncDec(UO);
5099   }
5100   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5101     return VisitUnaryPostIncDec(UO);
5102   }
5103   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5104     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5105       return Error(UO);
5106 
5107     LValue LVal;
5108     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5109       return false;
5110     APValue RVal;
5111     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5112                       UO->isIncrementOp(), &RVal))
5113       return false;
5114     return DerivedSuccess(RVal, UO);
5115   }
5116 
5117   bool VisitStmtExpr(const StmtExpr *E) {
5118     // We will have checked the full-expressions inside the statement expression
5119     // when they were completed, and don't need to check them again now.
5120     if (Info.checkingForOverflow())
5121       return Error(E);
5122 
5123     BlockScopeRAII Scope(Info);
5124     const CompoundStmt *CS = E->getSubStmt();
5125     if (CS->body_empty())
5126       return true;
5127 
5128     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5129                                            BE = CS->body_end();
5130          /**/; ++BI) {
5131       if (BI + 1 == BE) {
5132         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5133         if (!FinalExpr) {
5134           Info.FFDiag((*BI)->getBeginLoc(),
5135                       diag::note_constexpr_stmt_expr_unsupported);
5136           return false;
5137         }
5138         return this->Visit(FinalExpr);
5139       }
5140 
5141       APValue ReturnValue;
5142       StmtResult Result = { ReturnValue, nullptr };
5143       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5144       if (ESR != ESR_Succeeded) {
5145         // FIXME: If the statement-expression terminated due to 'return',
5146         // 'break', or 'continue', it would be nice to propagate that to
5147         // the outer statement evaluation rather than bailing out.
5148         if (ESR != ESR_Failed)
5149           Info.FFDiag((*BI)->getBeginLoc(),
5150                       diag::note_constexpr_stmt_expr_unsupported);
5151         return false;
5152       }
5153     }
5154 
5155     llvm_unreachable("Return from function from the loop above.");
5156   }
5157 
5158   /// Visit a value which is evaluated, but whose value is ignored.
5159   void VisitIgnoredValue(const Expr *E) {
5160     EvaluateIgnoredValue(Info, E);
5161   }
5162 
5163   /// Potentially visit a MemberExpr's base expression.
5164   void VisitIgnoredBaseExpression(const Expr *E) {
5165     // While MSVC doesn't evaluate the base expression, it does diagnose the
5166     // presence of side-effecting behavior.
5167     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5168       return;
5169     VisitIgnoredValue(E);
5170   }
5171 };
5172 
5173 } // namespace
5174 
5175 //===----------------------------------------------------------------------===//
5176 // Common base class for lvalue and temporary evaluation.
5177 //===----------------------------------------------------------------------===//
5178 namespace {
5179 template<class Derived>
5180 class LValueExprEvaluatorBase
5181   : public ExprEvaluatorBase<Derived> {
5182 protected:
5183   LValue &Result;
5184   bool InvalidBaseOK;
5185   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5186   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5187 
5188   bool Success(APValue::LValueBase B) {
5189     Result.set(B);
5190     return true;
5191   }
5192 
5193   bool evaluatePointer(const Expr *E, LValue &Result) {
5194     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5195   }
5196 
5197 public:
5198   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5199       : ExprEvaluatorBaseTy(Info), Result(Result),
5200         InvalidBaseOK(InvalidBaseOK) {}
5201 
5202   bool Success(const APValue &V, const Expr *E) {
5203     Result.setFrom(this->Info.Ctx, V);
5204     return true;
5205   }
5206 
5207   bool VisitMemberExpr(const MemberExpr *E) {
5208     // Handle non-static data members.
5209     QualType BaseTy;
5210     bool EvalOK;
5211     if (E->isArrow()) {
5212       EvalOK = evaluatePointer(E->getBase(), Result);
5213       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5214     } else if (E->getBase()->isRValue()) {
5215       assert(E->getBase()->getType()->isRecordType());
5216       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5217       BaseTy = E->getBase()->getType();
5218     } else {
5219       EvalOK = this->Visit(E->getBase());
5220       BaseTy = E->getBase()->getType();
5221     }
5222     if (!EvalOK) {
5223       if (!InvalidBaseOK)
5224         return false;
5225       Result.setInvalid(E);
5226       return true;
5227     }
5228 
5229     const ValueDecl *MD = E->getMemberDecl();
5230     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5231       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5232              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5233       (void)BaseTy;
5234       if (!HandleLValueMember(this->Info, E, Result, FD))
5235         return false;
5236     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5237       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5238         return false;
5239     } else
5240       return this->Error(E);
5241 
5242     if (MD->getType()->isReferenceType()) {
5243       APValue RefValue;
5244       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5245                                           RefValue))
5246         return false;
5247       return Success(RefValue, E);
5248     }
5249     return true;
5250   }
5251 
5252   bool VisitBinaryOperator(const BinaryOperator *E) {
5253     switch (E->getOpcode()) {
5254     default:
5255       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5256 
5257     case BO_PtrMemD:
5258     case BO_PtrMemI:
5259       return HandleMemberPointerAccess(this->Info, E, Result);
5260     }
5261   }
5262 
5263   bool VisitCastExpr(const CastExpr *E) {
5264     switch (E->getCastKind()) {
5265     default:
5266       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5267 
5268     case CK_DerivedToBase:
5269     case CK_UncheckedDerivedToBase:
5270       if (!this->Visit(E->getSubExpr()))
5271         return false;
5272 
5273       // Now figure out the necessary offset to add to the base LV to get from
5274       // the derived class to the base class.
5275       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5276                                   Result);
5277     }
5278   }
5279 };
5280 }
5281 
5282 //===----------------------------------------------------------------------===//
5283 // LValue Evaluation
5284 //
5285 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5286 // function designators (in C), decl references to void objects (in C), and
5287 // temporaries (if building with -Wno-address-of-temporary).
5288 //
5289 // LValue evaluation produces values comprising a base expression of one of the
5290 // following types:
5291 // - Declarations
5292 //  * VarDecl
5293 //  * FunctionDecl
5294 // - Literals
5295 //  * CompoundLiteralExpr in C (and in global scope in C++)
5296 //  * StringLiteral
5297 //  * CXXTypeidExpr
5298 //  * PredefinedExpr
5299 //  * ObjCStringLiteralExpr
5300 //  * ObjCEncodeExpr
5301 //  * AddrLabelExpr
5302 //  * BlockExpr
5303 //  * CallExpr for a MakeStringConstant builtin
5304 // - Locals and temporaries
5305 //  * MaterializeTemporaryExpr
5306 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5307 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5308 //    from the AST (FIXME).
5309 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5310 //    CallIndex, for a lifetime-extended temporary.
5311 // plus an offset in bytes.
5312 //===----------------------------------------------------------------------===//
5313 namespace {
5314 class LValueExprEvaluator
5315   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5316 public:
5317   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5318     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5319 
5320   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5321   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5322 
5323   bool VisitDeclRefExpr(const DeclRefExpr *E);
5324   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5325   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5326   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5327   bool VisitMemberExpr(const MemberExpr *E);
5328   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5329   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5330   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5331   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5332   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5333   bool VisitUnaryDeref(const UnaryOperator *E);
5334   bool VisitUnaryReal(const UnaryOperator *E);
5335   bool VisitUnaryImag(const UnaryOperator *E);
5336   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5337     return VisitUnaryPreIncDec(UO);
5338   }
5339   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5340     return VisitUnaryPreIncDec(UO);
5341   }
5342   bool VisitBinAssign(const BinaryOperator *BO);
5343   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5344 
5345   bool VisitCastExpr(const CastExpr *E) {
5346     switch (E->getCastKind()) {
5347     default:
5348       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5349 
5350     case CK_LValueBitCast:
5351       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5352       if (!Visit(E->getSubExpr()))
5353         return false;
5354       Result.Designator.setInvalid();
5355       return true;
5356 
5357     case CK_BaseToDerived:
5358       if (!Visit(E->getSubExpr()))
5359         return false;
5360       return HandleBaseToDerivedCast(Info, E, Result);
5361     }
5362   }
5363 };
5364 } // end anonymous namespace
5365 
5366 /// Evaluate an expression as an lvalue. This can be legitimately called on
5367 /// expressions which are not glvalues, in three cases:
5368 ///  * function designators in C, and
5369 ///  * "extern void" objects
5370 ///  * @selector() expressions in Objective-C
5371 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5372                            bool InvalidBaseOK) {
5373   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5374          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5375   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5376 }
5377 
5378 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5379   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5380     return Success(FD);
5381   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5382     return VisitVarDecl(E, VD);
5383   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5384     return Visit(BD->getBinding());
5385   return Error(E);
5386 }
5387 
5388 
5389 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5390 
5391   // If we are within a lambda's call operator, check whether the 'VD' referred
5392   // to within 'E' actually represents a lambda-capture that maps to a
5393   // data-member/field within the closure object, and if so, evaluate to the
5394   // field or what the field refers to.
5395   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5396       isa<DeclRefExpr>(E) &&
5397       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5398     // We don't always have a complete capture-map when checking or inferring if
5399     // the function call operator meets the requirements of a constexpr function
5400     // - but we don't need to evaluate the captures to determine constexprness
5401     // (dcl.constexpr C++17).
5402     if (Info.checkingPotentialConstantExpression())
5403       return false;
5404 
5405     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5406       // Start with 'Result' referring to the complete closure object...
5407       Result = *Info.CurrentCall->This;
5408       // ... then update it to refer to the field of the closure object
5409       // that represents the capture.
5410       if (!HandleLValueMember(Info, E, Result, FD))
5411         return false;
5412       // And if the field is of reference type, update 'Result' to refer to what
5413       // the field refers to.
5414       if (FD->getType()->isReferenceType()) {
5415         APValue RVal;
5416         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5417                                             RVal))
5418           return false;
5419         Result.setFrom(Info.Ctx, RVal);
5420       }
5421       return true;
5422     }
5423   }
5424   CallStackFrame *Frame = nullptr;
5425   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5426     // Only if a local variable was declared in the function currently being
5427     // evaluated, do we expect to be able to find its value in the current
5428     // frame. (Otherwise it was likely declared in an enclosing context and
5429     // could either have a valid evaluatable value (for e.g. a constexpr
5430     // variable) or be ill-formed (and trigger an appropriate evaluation
5431     // diagnostic)).
5432     if (Info.CurrentCall->Callee &&
5433         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5434       Frame = Info.CurrentCall;
5435     }
5436   }
5437 
5438   if (!VD->getType()->isReferenceType()) {
5439     if (Frame) {
5440       Result.set({VD, Frame->Index,
5441                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5442       return true;
5443     }
5444     return Success(VD);
5445   }
5446 
5447   APValue *V;
5448   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5449     return false;
5450   if (V->isUninit()) {
5451     if (!Info.checkingPotentialConstantExpression())
5452       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5453     return false;
5454   }
5455   return Success(*V, E);
5456 }
5457 
5458 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5459     const MaterializeTemporaryExpr *E) {
5460   // Walk through the expression to find the materialized temporary itself.
5461   SmallVector<const Expr *, 2> CommaLHSs;
5462   SmallVector<SubobjectAdjustment, 2> Adjustments;
5463   const Expr *Inner = E->GetTemporaryExpr()->
5464       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5465 
5466   // If we passed any comma operators, evaluate their LHSs.
5467   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5468     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5469       return false;
5470 
5471   // A materialized temporary with static storage duration can appear within the
5472   // result of a constant expression evaluation, so we need to preserve its
5473   // value for use outside this evaluation.
5474   APValue *Value;
5475   if (E->getStorageDuration() == SD_Static) {
5476     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5477     *Value = APValue();
5478     Result.set(E);
5479   } else {
5480     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5481                              *Info.CurrentCall);
5482   }
5483 
5484   QualType Type = Inner->getType();
5485 
5486   // Materialize the temporary itself.
5487   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5488       (E->getStorageDuration() == SD_Static &&
5489        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5490     *Value = APValue();
5491     return false;
5492   }
5493 
5494   // Adjust our lvalue to refer to the desired subobject.
5495   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5496     --I;
5497     switch (Adjustments[I].Kind) {
5498     case SubobjectAdjustment::DerivedToBaseAdjustment:
5499       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5500                                 Type, Result))
5501         return false;
5502       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5503       break;
5504 
5505     case SubobjectAdjustment::FieldAdjustment:
5506       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5507         return false;
5508       Type = Adjustments[I].Field->getType();
5509       break;
5510 
5511     case SubobjectAdjustment::MemberPointerAdjustment:
5512       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5513                                      Adjustments[I].Ptr.RHS))
5514         return false;
5515       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5516       break;
5517     }
5518   }
5519 
5520   return true;
5521 }
5522 
5523 bool
5524 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5525   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5526          "lvalue compound literal in c++?");
5527   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5528   // only see this when folding in C, so there's no standard to follow here.
5529   return Success(E);
5530 }
5531 
5532 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5533   if (!E->isPotentiallyEvaluated())
5534     return Success(E);
5535 
5536   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5537     << E->getExprOperand()->getType()
5538     << E->getExprOperand()->getSourceRange();
5539   return false;
5540 }
5541 
5542 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5543   return Success(E);
5544 }
5545 
5546 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5547   // Handle static data members.
5548   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5549     VisitIgnoredBaseExpression(E->getBase());
5550     return VisitVarDecl(E, VD);
5551   }
5552 
5553   // Handle static member functions.
5554   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5555     if (MD->isStatic()) {
5556       VisitIgnoredBaseExpression(E->getBase());
5557       return Success(MD);
5558     }
5559   }
5560 
5561   // Handle non-static data members.
5562   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5563 }
5564 
5565 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5566   // FIXME: Deal with vectors as array subscript bases.
5567   if (E->getBase()->getType()->isVectorType())
5568     return Error(E);
5569 
5570   bool Success = true;
5571   if (!evaluatePointer(E->getBase(), Result)) {
5572     if (!Info.noteFailure())
5573       return false;
5574     Success = false;
5575   }
5576 
5577   APSInt Index;
5578   if (!EvaluateInteger(E->getIdx(), Index, Info))
5579     return false;
5580 
5581   return Success &&
5582          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5583 }
5584 
5585 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5586   return evaluatePointer(E->getSubExpr(), Result);
5587 }
5588 
5589 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5590   if (!Visit(E->getSubExpr()))
5591     return false;
5592   // __real is a no-op on scalar lvalues.
5593   if (E->getSubExpr()->getType()->isAnyComplexType())
5594     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5595   return true;
5596 }
5597 
5598 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5599   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5600          "lvalue __imag__ on scalar?");
5601   if (!Visit(E->getSubExpr()))
5602     return false;
5603   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5604   return true;
5605 }
5606 
5607 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5608   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5609     return Error(UO);
5610 
5611   if (!this->Visit(UO->getSubExpr()))
5612     return false;
5613 
5614   return handleIncDec(
5615       this->Info, UO, Result, UO->getSubExpr()->getType(),
5616       UO->isIncrementOp(), nullptr);
5617 }
5618 
5619 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5620     const CompoundAssignOperator *CAO) {
5621   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5622     return Error(CAO);
5623 
5624   APValue RHS;
5625 
5626   // The overall lvalue result is the result of evaluating the LHS.
5627   if (!this->Visit(CAO->getLHS())) {
5628     if (Info.noteFailure())
5629       Evaluate(RHS, this->Info, CAO->getRHS());
5630     return false;
5631   }
5632 
5633   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5634     return false;
5635 
5636   return handleCompoundAssignment(
5637       this->Info, CAO,
5638       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5639       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5640 }
5641 
5642 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5643   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5644     return Error(E);
5645 
5646   APValue NewVal;
5647 
5648   if (!this->Visit(E->getLHS())) {
5649     if (Info.noteFailure())
5650       Evaluate(NewVal, this->Info, E->getRHS());
5651     return false;
5652   }
5653 
5654   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5655     return false;
5656 
5657   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5658                           NewVal);
5659 }
5660 
5661 //===----------------------------------------------------------------------===//
5662 // Pointer Evaluation
5663 //===----------------------------------------------------------------------===//
5664 
5665 /// Attempts to compute the number of bytes available at the pointer
5666 /// returned by a function with the alloc_size attribute. Returns true if we
5667 /// were successful. Places an unsigned number into `Result`.
5668 ///
5669 /// This expects the given CallExpr to be a call to a function with an
5670 /// alloc_size attribute.
5671 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5672                                             const CallExpr *Call,
5673                                             llvm::APInt &Result) {
5674   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5675 
5676   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5677   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5678   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5679   if (Call->getNumArgs() <= SizeArgNo)
5680     return false;
5681 
5682   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5683     Expr::EvalResult ExprResult;
5684     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
5685       return false;
5686     Into = ExprResult.Val.getInt();
5687     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5688       return false;
5689     Into = Into.zextOrSelf(BitsInSizeT);
5690     return true;
5691   };
5692 
5693   APSInt SizeOfElem;
5694   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5695     return false;
5696 
5697   if (!AllocSize->getNumElemsParam().isValid()) {
5698     Result = std::move(SizeOfElem);
5699     return true;
5700   }
5701 
5702   APSInt NumberOfElems;
5703   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5704   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5705     return false;
5706 
5707   bool Overflow;
5708   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5709   if (Overflow)
5710     return false;
5711 
5712   Result = std::move(BytesAvailable);
5713   return true;
5714 }
5715 
5716 /// Convenience function. LVal's base must be a call to an alloc_size
5717 /// function.
5718 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5719                                             const LValue &LVal,
5720                                             llvm::APInt &Result) {
5721   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5722          "Can't get the size of a non alloc_size function");
5723   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5724   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5725   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5726 }
5727 
5728 /// Attempts to evaluate the given LValueBase as the result of a call to
5729 /// a function with the alloc_size attribute. If it was possible to do so, this
5730 /// function will return true, make Result's Base point to said function call,
5731 /// and mark Result's Base as invalid.
5732 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5733                                       LValue &Result) {
5734   if (Base.isNull())
5735     return false;
5736 
5737   // Because we do no form of static analysis, we only support const variables.
5738   //
5739   // Additionally, we can't support parameters, nor can we support static
5740   // variables (in the latter case, use-before-assign isn't UB; in the former,
5741   // we have no clue what they'll be assigned to).
5742   const auto *VD =
5743       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5744   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5745     return false;
5746 
5747   const Expr *Init = VD->getAnyInitializer();
5748   if (!Init)
5749     return false;
5750 
5751   const Expr *E = Init->IgnoreParens();
5752   if (!tryUnwrapAllocSizeCall(E))
5753     return false;
5754 
5755   // Store E instead of E unwrapped so that the type of the LValue's base is
5756   // what the user wanted.
5757   Result.setInvalid(E);
5758 
5759   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5760   Result.addUnsizedArray(Info, E, Pointee);
5761   return true;
5762 }
5763 
5764 namespace {
5765 class PointerExprEvaluator
5766   : public ExprEvaluatorBase<PointerExprEvaluator> {
5767   LValue &Result;
5768   bool InvalidBaseOK;
5769 
5770   bool Success(const Expr *E) {
5771     Result.set(E);
5772     return true;
5773   }
5774 
5775   bool evaluateLValue(const Expr *E, LValue &Result) {
5776     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5777   }
5778 
5779   bool evaluatePointer(const Expr *E, LValue &Result) {
5780     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5781   }
5782 
5783   bool visitNonBuiltinCallExpr(const CallExpr *E);
5784 public:
5785 
5786   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5787       : ExprEvaluatorBaseTy(info), Result(Result),
5788         InvalidBaseOK(InvalidBaseOK) {}
5789 
5790   bool Success(const APValue &V, const Expr *E) {
5791     Result.setFrom(Info.Ctx, V);
5792     return true;
5793   }
5794   bool ZeroInitialization(const Expr *E) {
5795     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5796     Result.setNull(E->getType(), TargetVal);
5797     return true;
5798   }
5799 
5800   bool VisitBinaryOperator(const BinaryOperator *E);
5801   bool VisitCastExpr(const CastExpr* E);
5802   bool VisitUnaryAddrOf(const UnaryOperator *E);
5803   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5804       { return Success(E); }
5805   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5806     if (Info.noteFailure())
5807       EvaluateIgnoredValue(Info, E->getSubExpr());
5808     return Error(E);
5809   }
5810   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5811       { return Success(E); }
5812   bool VisitCallExpr(const CallExpr *E);
5813   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5814   bool VisitBlockExpr(const BlockExpr *E) {
5815     if (!E->getBlockDecl()->hasCaptures())
5816       return Success(E);
5817     return Error(E);
5818   }
5819   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5820     // Can't look at 'this' when checking a potential constant expression.
5821     if (Info.checkingPotentialConstantExpression())
5822       return false;
5823     if (!Info.CurrentCall->This) {
5824       if (Info.getLangOpts().CPlusPlus11)
5825         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5826       else
5827         Info.FFDiag(E);
5828       return false;
5829     }
5830     Result = *Info.CurrentCall->This;
5831     // If we are inside a lambda's call operator, the 'this' expression refers
5832     // to the enclosing '*this' object (either by value or reference) which is
5833     // either copied into the closure object's field that represents the '*this'
5834     // or refers to '*this'.
5835     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5836       // Update 'Result' to refer to the data member/field of the closure object
5837       // that represents the '*this' capture.
5838       if (!HandleLValueMember(Info, E, Result,
5839                              Info.CurrentCall->LambdaThisCaptureField))
5840         return false;
5841       // If we captured '*this' by reference, replace the field with its referent.
5842       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5843               ->isPointerType()) {
5844         APValue RVal;
5845         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5846                                             RVal))
5847           return false;
5848 
5849         Result.setFrom(Info.Ctx, RVal);
5850       }
5851     }
5852     return true;
5853   }
5854 
5855   // FIXME: Missing: @protocol, @selector
5856 };
5857 } // end anonymous namespace
5858 
5859 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5860                             bool InvalidBaseOK) {
5861   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5862   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5863 }
5864 
5865 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5866   if (E->getOpcode() != BO_Add &&
5867       E->getOpcode() != BO_Sub)
5868     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5869 
5870   const Expr *PExp = E->getLHS();
5871   const Expr *IExp = E->getRHS();
5872   if (IExp->getType()->isPointerType())
5873     std::swap(PExp, IExp);
5874 
5875   bool EvalPtrOK = evaluatePointer(PExp, Result);
5876   if (!EvalPtrOK && !Info.noteFailure())
5877     return false;
5878 
5879   llvm::APSInt Offset;
5880   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5881     return false;
5882 
5883   if (E->getOpcode() == BO_Sub)
5884     negateAsSigned(Offset);
5885 
5886   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5887   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5888 }
5889 
5890 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5891   return evaluateLValue(E->getSubExpr(), Result);
5892 }
5893 
5894 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5895   const Expr *SubExpr = E->getSubExpr();
5896 
5897   switch (E->getCastKind()) {
5898   default:
5899     break;
5900 
5901   case CK_BitCast:
5902   case CK_CPointerToObjCPointerCast:
5903   case CK_BlockPointerToObjCPointerCast:
5904   case CK_AnyPointerToBlockPointerCast:
5905   case CK_AddressSpaceConversion:
5906     if (!Visit(SubExpr))
5907       return false;
5908     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5909     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5910     // also static_casts, but we disallow them as a resolution to DR1312.
5911     if (!E->getType()->isVoidPointerType()) {
5912       Result.Designator.setInvalid();
5913       if (SubExpr->getType()->isVoidPointerType())
5914         CCEDiag(E, diag::note_constexpr_invalid_cast)
5915           << 3 << SubExpr->getType();
5916       else
5917         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5918     }
5919     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5920       ZeroInitialization(E);
5921     return true;
5922 
5923   case CK_DerivedToBase:
5924   case CK_UncheckedDerivedToBase:
5925     if (!evaluatePointer(E->getSubExpr(), Result))
5926       return false;
5927     if (!Result.Base && Result.Offset.isZero())
5928       return true;
5929 
5930     // Now figure out the necessary offset to add to the base LV to get from
5931     // the derived class to the base class.
5932     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5933                                   castAs<PointerType>()->getPointeeType(),
5934                                 Result);
5935 
5936   case CK_BaseToDerived:
5937     if (!Visit(E->getSubExpr()))
5938       return false;
5939     if (!Result.Base && Result.Offset.isZero())
5940       return true;
5941     return HandleBaseToDerivedCast(Info, E, Result);
5942 
5943   case CK_NullToPointer:
5944     VisitIgnoredValue(E->getSubExpr());
5945     return ZeroInitialization(E);
5946 
5947   case CK_IntegralToPointer: {
5948     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5949 
5950     APValue Value;
5951     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5952       break;
5953 
5954     if (Value.isInt()) {
5955       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5956       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5957       Result.Base = (Expr*)nullptr;
5958       Result.InvalidBase = false;
5959       Result.Offset = CharUnits::fromQuantity(N);
5960       Result.Designator.setInvalid();
5961       Result.IsNullPtr = false;
5962       return true;
5963     } else {
5964       // Cast is of an lvalue, no need to change value.
5965       Result.setFrom(Info.Ctx, Value);
5966       return true;
5967     }
5968   }
5969 
5970   case CK_ArrayToPointerDecay: {
5971     if (SubExpr->isGLValue()) {
5972       if (!evaluateLValue(SubExpr, Result))
5973         return false;
5974     } else {
5975       APValue &Value = createTemporary(SubExpr, false, Result,
5976                                        *Info.CurrentCall);
5977       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5978         return false;
5979     }
5980     // The result is a pointer to the first element of the array.
5981     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5982     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5983       Result.addArray(Info, E, CAT);
5984     else
5985       Result.addUnsizedArray(Info, E, AT->getElementType());
5986     return true;
5987   }
5988 
5989   case CK_FunctionToPointerDecay:
5990     return evaluateLValue(SubExpr, Result);
5991 
5992   case CK_LValueToRValue: {
5993     LValue LVal;
5994     if (!evaluateLValue(E->getSubExpr(), LVal))
5995       return false;
5996 
5997     APValue RVal;
5998     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5999     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6000                                         LVal, RVal))
6001       return InvalidBaseOK &&
6002              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
6003     return Success(RVal, E);
6004   }
6005   }
6006 
6007   return ExprEvaluatorBaseTy::VisitCastExpr(E);
6008 }
6009 
6010 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6011                                 UnaryExprOrTypeTrait ExprKind) {
6012   // C++ [expr.alignof]p3:
6013   //     When alignof is applied to a reference type, the result is the
6014   //     alignment of the referenced type.
6015   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6016     T = Ref->getPointeeType();
6017 
6018   if (T.getQualifiers().hasUnaligned())
6019     return CharUnits::One();
6020 
6021   const bool AlignOfReturnsPreferred =
6022       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6023 
6024   // __alignof is defined to return the preferred alignment.
6025   // Before 8, clang returned the preferred alignment for alignof and _Alignof
6026   // as well.
6027   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6028     return Info.Ctx.toCharUnitsFromBits(
6029       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6030   // alignof and _Alignof are defined to return the ABI alignment.
6031   else if (ExprKind == UETT_AlignOf)
6032     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6033   else
6034     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6035 }
6036 
6037 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6038                                 UnaryExprOrTypeTrait ExprKind) {
6039   E = E->IgnoreParens();
6040 
6041   // The kinds of expressions that we have special-case logic here for
6042   // should be kept up to date with the special checks for those
6043   // expressions in Sema.
6044 
6045   // alignof decl is always accepted, even if it doesn't make sense: we default
6046   // to 1 in those cases.
6047   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6048     return Info.Ctx.getDeclAlign(DRE->getDecl(),
6049                                  /*RefAsPointee*/true);
6050 
6051   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6052     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6053                                  /*RefAsPointee*/true);
6054 
6055   return GetAlignOfType(Info, E->getType(), ExprKind);
6056 }
6057 
6058 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6059 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6060   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6061     return true;
6062 
6063   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6064     return false;
6065 
6066   Result.setInvalid(E);
6067   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6068   Result.addUnsizedArray(Info, E, PointeeTy);
6069   return true;
6070 }
6071 
6072 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6073   if (IsStringLiteralCall(E))
6074     return Success(E);
6075 
6076   if (unsigned BuiltinOp = E->getBuiltinCallee())
6077     return VisitBuiltinCallExpr(E, BuiltinOp);
6078 
6079   return visitNonBuiltinCallExpr(E);
6080 }
6081 
6082 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6083                                                 unsigned BuiltinOp) {
6084   switch (BuiltinOp) {
6085   case Builtin::BI__builtin_addressof:
6086     return evaluateLValue(E->getArg(0), Result);
6087   case Builtin::BI__builtin_assume_aligned: {
6088     // We need to be very careful here because: if the pointer does not have the
6089     // asserted alignment, then the behavior is undefined, and undefined
6090     // behavior is non-constant.
6091     if (!evaluatePointer(E->getArg(0), Result))
6092       return false;
6093 
6094     LValue OffsetResult(Result);
6095     APSInt Alignment;
6096     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6097       return false;
6098     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6099 
6100     if (E->getNumArgs() > 2) {
6101       APSInt Offset;
6102       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6103         return false;
6104 
6105       int64_t AdditionalOffset = -Offset.getZExtValue();
6106       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6107     }
6108 
6109     // If there is a base object, then it must have the correct alignment.
6110     if (OffsetResult.Base) {
6111       CharUnits BaseAlignment;
6112       if (const ValueDecl *VD =
6113           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6114         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6115       } else {
6116         BaseAlignment = GetAlignOfExpr(
6117             Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
6118       }
6119 
6120       if (BaseAlignment < Align) {
6121         Result.Designator.setInvalid();
6122         // FIXME: Add support to Diagnostic for long / long long.
6123         CCEDiag(E->getArg(0),
6124                 diag::note_constexpr_baa_insufficient_alignment) << 0
6125           << (unsigned)BaseAlignment.getQuantity()
6126           << (unsigned)Align.getQuantity();
6127         return false;
6128       }
6129     }
6130 
6131     // The offset must also have the correct alignment.
6132     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6133       Result.Designator.setInvalid();
6134 
6135       (OffsetResult.Base
6136            ? CCEDiag(E->getArg(0),
6137                      diag::note_constexpr_baa_insufficient_alignment) << 1
6138            : CCEDiag(E->getArg(0),
6139                      diag::note_constexpr_baa_value_insufficient_alignment))
6140         << (int)OffsetResult.Offset.getQuantity()
6141         << (unsigned)Align.getQuantity();
6142       return false;
6143     }
6144 
6145     return true;
6146   }
6147   case Builtin::BI__builtin_launder:
6148     return evaluatePointer(E->getArg(0), Result);
6149   case Builtin::BIstrchr:
6150   case Builtin::BIwcschr:
6151   case Builtin::BImemchr:
6152   case Builtin::BIwmemchr:
6153     if (Info.getLangOpts().CPlusPlus11)
6154       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6155         << /*isConstexpr*/0 << /*isConstructor*/0
6156         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6157     else
6158       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6159     LLVM_FALLTHROUGH;
6160   case Builtin::BI__builtin_strchr:
6161   case Builtin::BI__builtin_wcschr:
6162   case Builtin::BI__builtin_memchr:
6163   case Builtin::BI__builtin_char_memchr:
6164   case Builtin::BI__builtin_wmemchr: {
6165     if (!Visit(E->getArg(0)))
6166       return false;
6167     APSInt Desired;
6168     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6169       return false;
6170     uint64_t MaxLength = uint64_t(-1);
6171     if (BuiltinOp != Builtin::BIstrchr &&
6172         BuiltinOp != Builtin::BIwcschr &&
6173         BuiltinOp != Builtin::BI__builtin_strchr &&
6174         BuiltinOp != Builtin::BI__builtin_wcschr) {
6175       APSInt N;
6176       if (!EvaluateInteger(E->getArg(2), N, Info))
6177         return false;
6178       MaxLength = N.getExtValue();
6179     }
6180     // We cannot find the value if there are no candidates to match against.
6181     if (MaxLength == 0u)
6182       return ZeroInitialization(E);
6183     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6184         Result.Designator.Invalid)
6185       return false;
6186     QualType CharTy = Result.Designator.getType(Info.Ctx);
6187     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6188                      BuiltinOp == Builtin::BI__builtin_memchr;
6189     assert(IsRawByte ||
6190            Info.Ctx.hasSameUnqualifiedType(
6191                CharTy, E->getArg(0)->getType()->getPointeeType()));
6192     // Pointers to const void may point to objects of incomplete type.
6193     if (IsRawByte && CharTy->isIncompleteType()) {
6194       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6195       return false;
6196     }
6197     // Give up on byte-oriented matching against multibyte elements.
6198     // FIXME: We can compare the bytes in the correct order.
6199     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6200       return false;
6201     // Figure out what value we're actually looking for (after converting to
6202     // the corresponding unsigned type if necessary).
6203     uint64_t DesiredVal;
6204     bool StopAtNull = false;
6205     switch (BuiltinOp) {
6206     case Builtin::BIstrchr:
6207     case Builtin::BI__builtin_strchr:
6208       // strchr compares directly to the passed integer, and therefore
6209       // always fails if given an int that is not a char.
6210       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6211                                                   E->getArg(1)->getType(),
6212                                                   Desired),
6213                                Desired))
6214         return ZeroInitialization(E);
6215       StopAtNull = true;
6216       LLVM_FALLTHROUGH;
6217     case Builtin::BImemchr:
6218     case Builtin::BI__builtin_memchr:
6219     case Builtin::BI__builtin_char_memchr:
6220       // memchr compares by converting both sides to unsigned char. That's also
6221       // correct for strchr if we get this far (to cope with plain char being
6222       // unsigned in the strchr case).
6223       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6224       break;
6225 
6226     case Builtin::BIwcschr:
6227     case Builtin::BI__builtin_wcschr:
6228       StopAtNull = true;
6229       LLVM_FALLTHROUGH;
6230     case Builtin::BIwmemchr:
6231     case Builtin::BI__builtin_wmemchr:
6232       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6233       DesiredVal = Desired.getZExtValue();
6234       break;
6235     }
6236 
6237     for (; MaxLength; --MaxLength) {
6238       APValue Char;
6239       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6240           !Char.isInt())
6241         return false;
6242       if (Char.getInt().getZExtValue() == DesiredVal)
6243         return true;
6244       if (StopAtNull && !Char.getInt())
6245         break;
6246       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6247         return false;
6248     }
6249     // Not found: return nullptr.
6250     return ZeroInitialization(E);
6251   }
6252 
6253   case Builtin::BImemcpy:
6254   case Builtin::BImemmove:
6255   case Builtin::BIwmemcpy:
6256   case Builtin::BIwmemmove:
6257     if (Info.getLangOpts().CPlusPlus11)
6258       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6259         << /*isConstexpr*/0 << /*isConstructor*/0
6260         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6261     else
6262       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6263     LLVM_FALLTHROUGH;
6264   case Builtin::BI__builtin_memcpy:
6265   case Builtin::BI__builtin_memmove:
6266   case Builtin::BI__builtin_wmemcpy:
6267   case Builtin::BI__builtin_wmemmove: {
6268     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6269                  BuiltinOp == Builtin::BIwmemmove ||
6270                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6271                  BuiltinOp == Builtin::BI__builtin_wmemmove;
6272     bool Move = BuiltinOp == Builtin::BImemmove ||
6273                 BuiltinOp == Builtin::BIwmemmove ||
6274                 BuiltinOp == Builtin::BI__builtin_memmove ||
6275                 BuiltinOp == Builtin::BI__builtin_wmemmove;
6276 
6277     // The result of mem* is the first argument.
6278     if (!Visit(E->getArg(0)))
6279       return false;
6280     LValue Dest = Result;
6281 
6282     LValue Src;
6283     if (!EvaluatePointer(E->getArg(1), Src, Info))
6284       return false;
6285 
6286     APSInt N;
6287     if (!EvaluateInteger(E->getArg(2), N, Info))
6288       return false;
6289     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6290 
6291     // If the size is zero, we treat this as always being a valid no-op.
6292     // (Even if one of the src and dest pointers is null.)
6293     if (!N)
6294       return true;
6295 
6296     // Otherwise, if either of the operands is null, we can't proceed. Don't
6297     // try to determine the type of the copied objects, because there aren't
6298     // any.
6299     if (!Src.Base || !Dest.Base) {
6300       APValue Val;
6301       (!Src.Base ? Src : Dest).moveInto(Val);
6302       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6303           << Move << WChar << !!Src.Base
6304           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6305       return false;
6306     }
6307     if (Src.Designator.Invalid || Dest.Designator.Invalid)
6308       return false;
6309 
6310     // We require that Src and Dest are both pointers to arrays of
6311     // trivially-copyable type. (For the wide version, the designator will be
6312     // invalid if the designated object is not a wchar_t.)
6313     QualType T = Dest.Designator.getType(Info.Ctx);
6314     QualType SrcT = Src.Designator.getType(Info.Ctx);
6315     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6316       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6317       return false;
6318     }
6319     if (T->isIncompleteType()) {
6320       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6321       return false;
6322     }
6323     if (!T.isTriviallyCopyableType(Info.Ctx)) {
6324       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6325       return false;
6326     }
6327 
6328     // Figure out how many T's we're copying.
6329     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6330     if (!WChar) {
6331       uint64_t Remainder;
6332       llvm::APInt OrigN = N;
6333       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6334       if (Remainder) {
6335         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6336             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6337             << (unsigned)TSize;
6338         return false;
6339       }
6340     }
6341 
6342     // Check that the copying will remain within the arrays, just so that we
6343     // can give a more meaningful diagnostic. This implicitly also checks that
6344     // N fits into 64 bits.
6345     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6346     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6347     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6348       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6349           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6350           << N.toString(10, /*Signed*/false);
6351       return false;
6352     }
6353     uint64_t NElems = N.getZExtValue();
6354     uint64_t NBytes = NElems * TSize;
6355 
6356     // Check for overlap.
6357     int Direction = 1;
6358     if (HasSameBase(Src, Dest)) {
6359       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6360       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6361       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6362         // Dest is inside the source region.
6363         if (!Move) {
6364           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6365           return false;
6366         }
6367         // For memmove and friends, copy backwards.
6368         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6369             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6370           return false;
6371         Direction = -1;
6372       } else if (!Move && SrcOffset >= DestOffset &&
6373                  SrcOffset - DestOffset < NBytes) {
6374         // Src is inside the destination region for memcpy: invalid.
6375         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6376         return false;
6377       }
6378     }
6379 
6380     while (true) {
6381       APValue Val;
6382       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6383           !handleAssignment(Info, E, Dest, T, Val))
6384         return false;
6385       // Do not iterate past the last element; if we're copying backwards, that
6386       // might take us off the start of the array.
6387       if (--NElems == 0)
6388         return true;
6389       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6390           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6391         return false;
6392     }
6393   }
6394 
6395   default:
6396     return visitNonBuiltinCallExpr(E);
6397   }
6398 }
6399 
6400 //===----------------------------------------------------------------------===//
6401 // Member Pointer Evaluation
6402 //===----------------------------------------------------------------------===//
6403 
6404 namespace {
6405 class MemberPointerExprEvaluator
6406   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6407   MemberPtr &Result;
6408 
6409   bool Success(const ValueDecl *D) {
6410     Result = MemberPtr(D);
6411     return true;
6412   }
6413 public:
6414 
6415   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6416     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6417 
6418   bool Success(const APValue &V, const Expr *E) {
6419     Result.setFrom(V);
6420     return true;
6421   }
6422   bool ZeroInitialization(const Expr *E) {
6423     return Success((const ValueDecl*)nullptr);
6424   }
6425 
6426   bool VisitCastExpr(const CastExpr *E);
6427   bool VisitUnaryAddrOf(const UnaryOperator *E);
6428 };
6429 } // end anonymous namespace
6430 
6431 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6432                                   EvalInfo &Info) {
6433   assert(E->isRValue() && E->getType()->isMemberPointerType());
6434   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6435 }
6436 
6437 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6438   switch (E->getCastKind()) {
6439   default:
6440     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6441 
6442   case CK_NullToMemberPointer:
6443     VisitIgnoredValue(E->getSubExpr());
6444     return ZeroInitialization(E);
6445 
6446   case CK_BaseToDerivedMemberPointer: {
6447     if (!Visit(E->getSubExpr()))
6448       return false;
6449     if (E->path_empty())
6450       return true;
6451     // Base-to-derived member pointer casts store the path in derived-to-base
6452     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6453     // the wrong end of the derived->base arc, so stagger the path by one class.
6454     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6455     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6456          PathI != PathE; ++PathI) {
6457       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6458       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6459       if (!Result.castToDerived(Derived))
6460         return Error(E);
6461     }
6462     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6463     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6464       return Error(E);
6465     return true;
6466   }
6467 
6468   case CK_DerivedToBaseMemberPointer:
6469     if (!Visit(E->getSubExpr()))
6470       return false;
6471     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6472          PathE = E->path_end(); PathI != PathE; ++PathI) {
6473       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6474       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6475       if (!Result.castToBase(Base))
6476         return Error(E);
6477     }
6478     return true;
6479   }
6480 }
6481 
6482 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6483   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6484   // member can be formed.
6485   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6486 }
6487 
6488 //===----------------------------------------------------------------------===//
6489 // Record Evaluation
6490 //===----------------------------------------------------------------------===//
6491 
6492 namespace {
6493   class RecordExprEvaluator
6494   : public ExprEvaluatorBase<RecordExprEvaluator> {
6495     const LValue &This;
6496     APValue &Result;
6497   public:
6498 
6499     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6500       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6501 
6502     bool Success(const APValue &V, const Expr *E) {
6503       Result = V;
6504       return true;
6505     }
6506     bool ZeroInitialization(const Expr *E) {
6507       return ZeroInitialization(E, E->getType());
6508     }
6509     bool ZeroInitialization(const Expr *E, QualType T);
6510 
6511     bool VisitCallExpr(const CallExpr *E) {
6512       return handleCallExpr(E, Result, &This);
6513     }
6514     bool VisitCastExpr(const CastExpr *E);
6515     bool VisitInitListExpr(const InitListExpr *E);
6516     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6517       return VisitCXXConstructExpr(E, E->getType());
6518     }
6519     bool VisitLambdaExpr(const LambdaExpr *E);
6520     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6521     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6522     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6523 
6524     bool VisitBinCmp(const BinaryOperator *E);
6525   };
6526 }
6527 
6528 /// Perform zero-initialization on an object of non-union class type.
6529 /// C++11 [dcl.init]p5:
6530 ///  To zero-initialize an object or reference of type T means:
6531 ///    [...]
6532 ///    -- if T is a (possibly cv-qualified) non-union class type,
6533 ///       each non-static data member and each base-class subobject is
6534 ///       zero-initialized
6535 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6536                                           const RecordDecl *RD,
6537                                           const LValue &This, APValue &Result) {
6538   assert(!RD->isUnion() && "Expected non-union class type");
6539   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6540   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6541                    std::distance(RD->field_begin(), RD->field_end()));
6542 
6543   if (RD->isInvalidDecl()) return false;
6544   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6545 
6546   if (CD) {
6547     unsigned Index = 0;
6548     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6549            End = CD->bases_end(); I != End; ++I, ++Index) {
6550       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6551       LValue Subobject = This;
6552       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6553         return false;
6554       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6555                                          Result.getStructBase(Index)))
6556         return false;
6557     }
6558   }
6559 
6560   for (const auto *I : RD->fields()) {
6561     // -- if T is a reference type, no initialization is performed.
6562     if (I->getType()->isReferenceType())
6563       continue;
6564 
6565     LValue Subobject = This;
6566     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6567       return false;
6568 
6569     ImplicitValueInitExpr VIE(I->getType());
6570     if (!EvaluateInPlace(
6571           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6572       return false;
6573   }
6574 
6575   return true;
6576 }
6577 
6578 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6579   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6580   if (RD->isInvalidDecl()) return false;
6581   if (RD->isUnion()) {
6582     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6583     // object's first non-static named data member is zero-initialized
6584     RecordDecl::field_iterator I = RD->field_begin();
6585     if (I == RD->field_end()) {
6586       Result = APValue((const FieldDecl*)nullptr);
6587       return true;
6588     }
6589 
6590     LValue Subobject = This;
6591     if (!HandleLValueMember(Info, E, Subobject, *I))
6592       return false;
6593     Result = APValue(*I);
6594     ImplicitValueInitExpr VIE(I->getType());
6595     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6596   }
6597 
6598   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6599     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6600     return false;
6601   }
6602 
6603   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6604 }
6605 
6606 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6607   switch (E->getCastKind()) {
6608   default:
6609     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6610 
6611   case CK_ConstructorConversion:
6612     return Visit(E->getSubExpr());
6613 
6614   case CK_DerivedToBase:
6615   case CK_UncheckedDerivedToBase: {
6616     APValue DerivedObject;
6617     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6618       return false;
6619     if (!DerivedObject.isStruct())
6620       return Error(E->getSubExpr());
6621 
6622     // Derived-to-base rvalue conversion: just slice off the derived part.
6623     APValue *Value = &DerivedObject;
6624     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6625     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6626          PathE = E->path_end(); PathI != PathE; ++PathI) {
6627       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6628       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6629       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6630       RD = Base;
6631     }
6632     Result = *Value;
6633     return true;
6634   }
6635   }
6636 }
6637 
6638 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6639   if (E->isTransparent())
6640     return Visit(E->getInit(0));
6641 
6642   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6643   if (RD->isInvalidDecl()) return false;
6644   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6645 
6646   if (RD->isUnion()) {
6647     const FieldDecl *Field = E->getInitializedFieldInUnion();
6648     Result = APValue(Field);
6649     if (!Field)
6650       return true;
6651 
6652     // If the initializer list for a union does not contain any elements, the
6653     // first element of the union is value-initialized.
6654     // FIXME: The element should be initialized from an initializer list.
6655     //        Is this difference ever observable for initializer lists which
6656     //        we don't build?
6657     ImplicitValueInitExpr VIE(Field->getType());
6658     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6659 
6660     LValue Subobject = This;
6661     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6662       return false;
6663 
6664     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6665     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6666                                   isa<CXXDefaultInitExpr>(InitExpr));
6667 
6668     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6669   }
6670 
6671   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6672   if (Result.isUninit())
6673     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6674                      std::distance(RD->field_begin(), RD->field_end()));
6675   unsigned ElementNo = 0;
6676   bool Success = true;
6677 
6678   // Initialize base classes.
6679   if (CXXRD) {
6680     for (const auto &Base : CXXRD->bases()) {
6681       assert(ElementNo < E->getNumInits() && "missing init for base class");
6682       const Expr *Init = E->getInit(ElementNo);
6683 
6684       LValue Subobject = This;
6685       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6686         return false;
6687 
6688       APValue &FieldVal = Result.getStructBase(ElementNo);
6689       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6690         if (!Info.noteFailure())
6691           return false;
6692         Success = false;
6693       }
6694       ++ElementNo;
6695     }
6696   }
6697 
6698   // Initialize members.
6699   for (const auto *Field : RD->fields()) {
6700     // Anonymous bit-fields are not considered members of the class for
6701     // purposes of aggregate initialization.
6702     if (Field->isUnnamedBitfield())
6703       continue;
6704 
6705     LValue Subobject = This;
6706 
6707     bool HaveInit = ElementNo < E->getNumInits();
6708 
6709     // FIXME: Diagnostics here should point to the end of the initializer
6710     // list, not the start.
6711     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6712                             Subobject, Field, &Layout))
6713       return false;
6714 
6715     // Perform an implicit value-initialization for members beyond the end of
6716     // the initializer list.
6717     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6718     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6719 
6720     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6721     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6722                                   isa<CXXDefaultInitExpr>(Init));
6723 
6724     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6725     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6726         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6727                                                        FieldVal, Field))) {
6728       if (!Info.noteFailure())
6729         return false;
6730       Success = false;
6731     }
6732   }
6733 
6734   return Success;
6735 }
6736 
6737 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6738                                                 QualType T) {
6739   // Note that E's type is not necessarily the type of our class here; we might
6740   // be initializing an array element instead.
6741   const CXXConstructorDecl *FD = E->getConstructor();
6742   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6743 
6744   bool ZeroInit = E->requiresZeroInitialization();
6745   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6746     // If we've already performed zero-initialization, we're already done.
6747     if (!Result.isUninit())
6748       return true;
6749 
6750     // We can get here in two different ways:
6751     //  1) We're performing value-initialization, and should zero-initialize
6752     //     the object, or
6753     //  2) We're performing default-initialization of an object with a trivial
6754     //     constexpr default constructor, in which case we should start the
6755     //     lifetimes of all the base subobjects (there can be no data member
6756     //     subobjects in this case) per [basic.life]p1.
6757     // Either way, ZeroInitialization is appropriate.
6758     return ZeroInitialization(E, T);
6759   }
6760 
6761   const FunctionDecl *Definition = nullptr;
6762   auto Body = FD->getBody(Definition);
6763 
6764   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6765     return false;
6766 
6767   // Avoid materializing a temporary for an elidable copy/move constructor.
6768   if (E->isElidable() && !ZeroInit)
6769     if (const MaterializeTemporaryExpr *ME
6770           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6771       return Visit(ME->GetTemporaryExpr());
6772 
6773   if (ZeroInit && !ZeroInitialization(E, T))
6774     return false;
6775 
6776   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6777   return HandleConstructorCall(E, This, Args,
6778                                cast<CXXConstructorDecl>(Definition), Info,
6779                                Result);
6780 }
6781 
6782 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6783     const CXXInheritedCtorInitExpr *E) {
6784   if (!Info.CurrentCall) {
6785     assert(Info.checkingPotentialConstantExpression());
6786     return false;
6787   }
6788 
6789   const CXXConstructorDecl *FD = E->getConstructor();
6790   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6791     return false;
6792 
6793   const FunctionDecl *Definition = nullptr;
6794   auto Body = FD->getBody(Definition);
6795 
6796   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6797     return false;
6798 
6799   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6800                                cast<CXXConstructorDecl>(Definition), Info,
6801                                Result);
6802 }
6803 
6804 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6805     const CXXStdInitializerListExpr *E) {
6806   const ConstantArrayType *ArrayType =
6807       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6808 
6809   LValue Array;
6810   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6811     return false;
6812 
6813   // Get a pointer to the first element of the array.
6814   Array.addArray(Info, E, ArrayType);
6815 
6816   // FIXME: Perform the checks on the field types in SemaInit.
6817   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6818   RecordDecl::field_iterator Field = Record->field_begin();
6819   if (Field == Record->field_end())
6820     return Error(E);
6821 
6822   // Start pointer.
6823   if (!Field->getType()->isPointerType() ||
6824       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6825                             ArrayType->getElementType()))
6826     return Error(E);
6827 
6828   // FIXME: What if the initializer_list type has base classes, etc?
6829   Result = APValue(APValue::UninitStruct(), 0, 2);
6830   Array.moveInto(Result.getStructField(0));
6831 
6832   if (++Field == Record->field_end())
6833     return Error(E);
6834 
6835   if (Field->getType()->isPointerType() &&
6836       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6837                            ArrayType->getElementType())) {
6838     // End pointer.
6839     if (!HandleLValueArrayAdjustment(Info, E, Array,
6840                                      ArrayType->getElementType(),
6841                                      ArrayType->getSize().getZExtValue()))
6842       return false;
6843     Array.moveInto(Result.getStructField(1));
6844   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6845     // Length.
6846     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6847   else
6848     return Error(E);
6849 
6850   if (++Field != Record->field_end())
6851     return Error(E);
6852 
6853   return true;
6854 }
6855 
6856 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6857   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6858   if (ClosureClass->isInvalidDecl()) return false;
6859 
6860   if (Info.checkingPotentialConstantExpression()) return true;
6861 
6862   const size_t NumFields =
6863       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6864 
6865   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6866                                             E->capture_init_end()) &&
6867          "The number of lambda capture initializers should equal the number of "
6868          "fields within the closure type");
6869 
6870   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6871   // Iterate through all the lambda's closure object's fields and initialize
6872   // them.
6873   auto *CaptureInitIt = E->capture_init_begin();
6874   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6875   bool Success = true;
6876   for (const auto *Field : ClosureClass->fields()) {
6877     assert(CaptureInitIt != E->capture_init_end());
6878     // Get the initializer for this field
6879     Expr *const CurFieldInit = *CaptureInitIt++;
6880 
6881     // If there is no initializer, either this is a VLA or an error has
6882     // occurred.
6883     if (!CurFieldInit)
6884       return Error(E);
6885 
6886     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6887     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6888       if (!Info.keepEvaluatingAfterFailure())
6889         return false;
6890       Success = false;
6891     }
6892     ++CaptureIt;
6893   }
6894   return Success;
6895 }
6896 
6897 static bool EvaluateRecord(const Expr *E, const LValue &This,
6898                            APValue &Result, EvalInfo &Info) {
6899   assert(E->isRValue() && E->getType()->isRecordType() &&
6900          "can't evaluate expression as a record rvalue");
6901   return RecordExprEvaluator(Info, This, Result).Visit(E);
6902 }
6903 
6904 //===----------------------------------------------------------------------===//
6905 // Temporary Evaluation
6906 //
6907 // Temporaries are represented in the AST as rvalues, but generally behave like
6908 // lvalues. The full-object of which the temporary is a subobject is implicitly
6909 // materialized so that a reference can bind to it.
6910 //===----------------------------------------------------------------------===//
6911 namespace {
6912 class TemporaryExprEvaluator
6913   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6914 public:
6915   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6916     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6917 
6918   /// Visit an expression which constructs the value of this temporary.
6919   bool VisitConstructExpr(const Expr *E) {
6920     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6921     return EvaluateInPlace(Value, Info, Result, E);
6922   }
6923 
6924   bool VisitCastExpr(const CastExpr *E) {
6925     switch (E->getCastKind()) {
6926     default:
6927       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6928 
6929     case CK_ConstructorConversion:
6930       return VisitConstructExpr(E->getSubExpr());
6931     }
6932   }
6933   bool VisitInitListExpr(const InitListExpr *E) {
6934     return VisitConstructExpr(E);
6935   }
6936   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6937     return VisitConstructExpr(E);
6938   }
6939   bool VisitCallExpr(const CallExpr *E) {
6940     return VisitConstructExpr(E);
6941   }
6942   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6943     return VisitConstructExpr(E);
6944   }
6945   bool VisitLambdaExpr(const LambdaExpr *E) {
6946     return VisitConstructExpr(E);
6947   }
6948 };
6949 } // end anonymous namespace
6950 
6951 /// Evaluate an expression of record type as a temporary.
6952 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6953   assert(E->isRValue() && E->getType()->isRecordType());
6954   return TemporaryExprEvaluator(Info, Result).Visit(E);
6955 }
6956 
6957 //===----------------------------------------------------------------------===//
6958 // Vector Evaluation
6959 //===----------------------------------------------------------------------===//
6960 
6961 namespace {
6962   class VectorExprEvaluator
6963   : public ExprEvaluatorBase<VectorExprEvaluator> {
6964     APValue &Result;
6965   public:
6966 
6967     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6968       : ExprEvaluatorBaseTy(info), Result(Result) {}
6969 
6970     bool Success(ArrayRef<APValue> V, const Expr *E) {
6971       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6972       // FIXME: remove this APValue copy.
6973       Result = APValue(V.data(), V.size());
6974       return true;
6975     }
6976     bool Success(const APValue &V, const Expr *E) {
6977       assert(V.isVector());
6978       Result = V;
6979       return true;
6980     }
6981     bool ZeroInitialization(const Expr *E);
6982 
6983     bool VisitUnaryReal(const UnaryOperator *E)
6984       { return Visit(E->getSubExpr()); }
6985     bool VisitCastExpr(const CastExpr* E);
6986     bool VisitInitListExpr(const InitListExpr *E);
6987     bool VisitUnaryImag(const UnaryOperator *E);
6988     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6989     //                 binary comparisons, binary and/or/xor,
6990     //                 shufflevector, ExtVectorElementExpr
6991   };
6992 } // end anonymous namespace
6993 
6994 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6995   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6996   return VectorExprEvaluator(Info, Result).Visit(E);
6997 }
6998 
6999 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
7000   const VectorType *VTy = E->getType()->castAs<VectorType>();
7001   unsigned NElts = VTy->getNumElements();
7002 
7003   const Expr *SE = E->getSubExpr();
7004   QualType SETy = SE->getType();
7005 
7006   switch (E->getCastKind()) {
7007   case CK_VectorSplat: {
7008     APValue Val = APValue();
7009     if (SETy->isIntegerType()) {
7010       APSInt IntResult;
7011       if (!EvaluateInteger(SE, IntResult, Info))
7012         return false;
7013       Val = APValue(std::move(IntResult));
7014     } else if (SETy->isRealFloatingType()) {
7015       APFloat FloatResult(0.0);
7016       if (!EvaluateFloat(SE, FloatResult, Info))
7017         return false;
7018       Val = APValue(std::move(FloatResult));
7019     } else {
7020       return Error(E);
7021     }
7022 
7023     // Splat and create vector APValue.
7024     SmallVector<APValue, 4> Elts(NElts, Val);
7025     return Success(Elts, E);
7026   }
7027   case CK_BitCast: {
7028     // Evaluate the operand into an APInt we can extract from.
7029     llvm::APInt SValInt;
7030     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7031       return false;
7032     // Extract the elements
7033     QualType EltTy = VTy->getElementType();
7034     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7035     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7036     SmallVector<APValue, 4> Elts;
7037     if (EltTy->isRealFloatingType()) {
7038       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7039       unsigned FloatEltSize = EltSize;
7040       if (&Sem == &APFloat::x87DoubleExtended())
7041         FloatEltSize = 80;
7042       for (unsigned i = 0; i < NElts; i++) {
7043         llvm::APInt Elt;
7044         if (BigEndian)
7045           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7046         else
7047           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7048         Elts.push_back(APValue(APFloat(Sem, Elt)));
7049       }
7050     } else if (EltTy->isIntegerType()) {
7051       for (unsigned i = 0; i < NElts; i++) {
7052         llvm::APInt Elt;
7053         if (BigEndian)
7054           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7055         else
7056           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7057         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7058       }
7059     } else {
7060       return Error(E);
7061     }
7062     return Success(Elts, E);
7063   }
7064   default:
7065     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7066   }
7067 }
7068 
7069 bool
7070 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7071   const VectorType *VT = E->getType()->castAs<VectorType>();
7072   unsigned NumInits = E->getNumInits();
7073   unsigned NumElements = VT->getNumElements();
7074 
7075   QualType EltTy = VT->getElementType();
7076   SmallVector<APValue, 4> Elements;
7077 
7078   // The number of initializers can be less than the number of
7079   // vector elements. For OpenCL, this can be due to nested vector
7080   // initialization. For GCC compatibility, missing trailing elements
7081   // should be initialized with zeroes.
7082   unsigned CountInits = 0, CountElts = 0;
7083   while (CountElts < NumElements) {
7084     // Handle nested vector initialization.
7085     if (CountInits < NumInits
7086         && E->getInit(CountInits)->getType()->isVectorType()) {
7087       APValue v;
7088       if (!EvaluateVector(E->getInit(CountInits), v, Info))
7089         return Error(E);
7090       unsigned vlen = v.getVectorLength();
7091       for (unsigned j = 0; j < vlen; j++)
7092         Elements.push_back(v.getVectorElt(j));
7093       CountElts += vlen;
7094     } else if (EltTy->isIntegerType()) {
7095       llvm::APSInt sInt(32);
7096       if (CountInits < NumInits) {
7097         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7098           return false;
7099       } else // trailing integer zero.
7100         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7101       Elements.push_back(APValue(sInt));
7102       CountElts++;
7103     } else {
7104       llvm::APFloat f(0.0);
7105       if (CountInits < NumInits) {
7106         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7107           return false;
7108       } else // trailing float zero.
7109         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7110       Elements.push_back(APValue(f));
7111       CountElts++;
7112     }
7113     CountInits++;
7114   }
7115   return Success(Elements, E);
7116 }
7117 
7118 bool
7119 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7120   const VectorType *VT = E->getType()->getAs<VectorType>();
7121   QualType EltTy = VT->getElementType();
7122   APValue ZeroElement;
7123   if (EltTy->isIntegerType())
7124     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7125   else
7126     ZeroElement =
7127         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7128 
7129   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7130   return Success(Elements, E);
7131 }
7132 
7133 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7134   VisitIgnoredValue(E->getSubExpr());
7135   return ZeroInitialization(E);
7136 }
7137 
7138 //===----------------------------------------------------------------------===//
7139 // Array Evaluation
7140 //===----------------------------------------------------------------------===//
7141 
7142 namespace {
7143   class ArrayExprEvaluator
7144   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7145     const LValue &This;
7146     APValue &Result;
7147   public:
7148 
7149     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7150       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7151 
7152     bool Success(const APValue &V, const Expr *E) {
7153       assert((V.isArray() || V.isLValue()) &&
7154              "expected array or string literal");
7155       Result = V;
7156       return true;
7157     }
7158 
7159     bool ZeroInitialization(const Expr *E) {
7160       const ConstantArrayType *CAT =
7161           Info.Ctx.getAsConstantArrayType(E->getType());
7162       if (!CAT)
7163         return Error(E);
7164 
7165       Result = APValue(APValue::UninitArray(), 0,
7166                        CAT->getSize().getZExtValue());
7167       if (!Result.hasArrayFiller()) return true;
7168 
7169       // Zero-initialize all elements.
7170       LValue Subobject = This;
7171       Subobject.addArray(Info, E, CAT);
7172       ImplicitValueInitExpr VIE(CAT->getElementType());
7173       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7174     }
7175 
7176     bool VisitCallExpr(const CallExpr *E) {
7177       return handleCallExpr(E, Result, &This);
7178     }
7179     bool VisitInitListExpr(const InitListExpr *E);
7180     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7181     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7182     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7183                                const LValue &Subobject,
7184                                APValue *Value, QualType Type);
7185   };
7186 } // end anonymous namespace
7187 
7188 static bool EvaluateArray(const Expr *E, const LValue &This,
7189                           APValue &Result, EvalInfo &Info) {
7190   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7191   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7192 }
7193 
7194 // Return true iff the given array filler may depend on the element index.
7195 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7196   // For now, just whitelist non-class value-initialization and initialization
7197   // lists comprised of them.
7198   if (isa<ImplicitValueInitExpr>(FillerExpr))
7199     return false;
7200   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7201     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7202       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7203         return true;
7204     }
7205     return false;
7206   }
7207   return true;
7208 }
7209 
7210 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7211   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7212   if (!CAT)
7213     return Error(E);
7214 
7215   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7216   // an appropriately-typed string literal enclosed in braces.
7217   if (E->isStringLiteralInit()) {
7218     LValue LV;
7219     if (!EvaluateLValue(E->getInit(0), LV, Info))
7220       return false;
7221     APValue Val;
7222     LV.moveInto(Val);
7223     return Success(Val, E);
7224   }
7225 
7226   bool Success = true;
7227 
7228   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7229          "zero-initialized array shouldn't have any initialized elts");
7230   APValue Filler;
7231   if (Result.isArray() && Result.hasArrayFiller())
7232     Filler = Result.getArrayFiller();
7233 
7234   unsigned NumEltsToInit = E->getNumInits();
7235   unsigned NumElts = CAT->getSize().getZExtValue();
7236   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7237 
7238   // If the initializer might depend on the array index, run it for each
7239   // array element.
7240   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7241     NumEltsToInit = NumElts;
7242 
7243   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7244                           << NumEltsToInit << ".\n");
7245 
7246   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7247 
7248   // If the array was previously zero-initialized, preserve the
7249   // zero-initialized values.
7250   if (!Filler.isUninit()) {
7251     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7252       Result.getArrayInitializedElt(I) = Filler;
7253     if (Result.hasArrayFiller())
7254       Result.getArrayFiller() = Filler;
7255   }
7256 
7257   LValue Subobject = This;
7258   Subobject.addArray(Info, E, CAT);
7259   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7260     const Expr *Init =
7261         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7262     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7263                          Info, Subobject, Init) ||
7264         !HandleLValueArrayAdjustment(Info, Init, Subobject,
7265                                      CAT->getElementType(), 1)) {
7266       if (!Info.noteFailure())
7267         return false;
7268       Success = false;
7269     }
7270   }
7271 
7272   if (!Result.hasArrayFiller())
7273     return Success;
7274 
7275   // If we get here, we have a trivial filler, which we can just evaluate
7276   // once and splat over the rest of the array elements.
7277   assert(FillerExpr && "no array filler for incomplete init list");
7278   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7279                          FillerExpr) && Success;
7280 }
7281 
7282 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7283   if (E->getCommonExpr() &&
7284       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7285                 Info, E->getCommonExpr()->getSourceExpr()))
7286     return false;
7287 
7288   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7289 
7290   uint64_t Elements = CAT->getSize().getZExtValue();
7291   Result = APValue(APValue::UninitArray(), Elements, Elements);
7292 
7293   LValue Subobject = This;
7294   Subobject.addArray(Info, E, CAT);
7295 
7296   bool Success = true;
7297   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7298     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7299                          Info, Subobject, E->getSubExpr()) ||
7300         !HandleLValueArrayAdjustment(Info, E, Subobject,
7301                                      CAT->getElementType(), 1)) {
7302       if (!Info.noteFailure())
7303         return false;
7304       Success = false;
7305     }
7306   }
7307 
7308   return Success;
7309 }
7310 
7311 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7312   return VisitCXXConstructExpr(E, This, &Result, E->getType());
7313 }
7314 
7315 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7316                                                const LValue &Subobject,
7317                                                APValue *Value,
7318                                                QualType Type) {
7319   bool HadZeroInit = !Value->isUninit();
7320 
7321   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7322     unsigned N = CAT->getSize().getZExtValue();
7323 
7324     // Preserve the array filler if we had prior zero-initialization.
7325     APValue Filler =
7326       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7327                                              : APValue();
7328 
7329     *Value = APValue(APValue::UninitArray(), N, N);
7330 
7331     if (HadZeroInit)
7332       for (unsigned I = 0; I != N; ++I)
7333         Value->getArrayInitializedElt(I) = Filler;
7334 
7335     // Initialize the elements.
7336     LValue ArrayElt = Subobject;
7337     ArrayElt.addArray(Info, E, CAT);
7338     for (unsigned I = 0; I != N; ++I)
7339       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7340                                  CAT->getElementType()) ||
7341           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7342                                        CAT->getElementType(), 1))
7343         return false;
7344 
7345     return true;
7346   }
7347 
7348   if (!Type->isRecordType())
7349     return Error(E);
7350 
7351   return RecordExprEvaluator(Info, Subobject, *Value)
7352              .VisitCXXConstructExpr(E, Type);
7353 }
7354 
7355 //===----------------------------------------------------------------------===//
7356 // Integer Evaluation
7357 //
7358 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7359 // types and back in constant folding. Integer values are thus represented
7360 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7361 //===----------------------------------------------------------------------===//
7362 
7363 namespace {
7364 class IntExprEvaluator
7365         : public ExprEvaluatorBase<IntExprEvaluator> {
7366   APValue &Result;
7367 public:
7368   IntExprEvaluator(EvalInfo &info, APValue &result)
7369       : ExprEvaluatorBaseTy(info), Result(result) {}
7370 
7371   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7372     assert(E->getType()->isIntegralOrEnumerationType() &&
7373            "Invalid evaluation result.");
7374     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7375            "Invalid evaluation result.");
7376     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7377            "Invalid evaluation result.");
7378     Result = APValue(SI);
7379     return true;
7380   }
7381   bool Success(const llvm::APSInt &SI, const Expr *E) {
7382     return Success(SI, E, Result);
7383   }
7384 
7385   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7386     assert(E->getType()->isIntegralOrEnumerationType() &&
7387            "Invalid evaluation result.");
7388     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7389            "Invalid evaluation result.");
7390     Result = APValue(APSInt(I));
7391     Result.getInt().setIsUnsigned(
7392                             E->getType()->isUnsignedIntegerOrEnumerationType());
7393     return true;
7394   }
7395   bool Success(const llvm::APInt &I, const Expr *E) {
7396     return Success(I, E, Result);
7397   }
7398 
7399   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7400     assert(E->getType()->isIntegralOrEnumerationType() &&
7401            "Invalid evaluation result.");
7402     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7403     return true;
7404   }
7405   bool Success(uint64_t Value, const Expr *E) {
7406     return Success(Value, E, Result);
7407   }
7408 
7409   bool Success(CharUnits Size, const Expr *E) {
7410     return Success(Size.getQuantity(), E);
7411   }
7412 
7413   bool Success(const APValue &V, const Expr *E) {
7414     if (V.isLValue() || V.isAddrLabelDiff()) {
7415       Result = V;
7416       return true;
7417     }
7418     return Success(V.getInt(), E);
7419   }
7420 
7421   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7422 
7423   //===--------------------------------------------------------------------===//
7424   //                            Visitor Methods
7425   //===--------------------------------------------------------------------===//
7426 
7427   bool VisitConstantExpr(const ConstantExpr *E);
7428 
7429   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7430     return Success(E->getValue(), E);
7431   }
7432   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7433     return Success(E->getValue(), E);
7434   }
7435 
7436   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7437   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7438     if (CheckReferencedDecl(E, E->getDecl()))
7439       return true;
7440 
7441     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7442   }
7443   bool VisitMemberExpr(const MemberExpr *E) {
7444     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7445       VisitIgnoredBaseExpression(E->getBase());
7446       return true;
7447     }
7448 
7449     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7450   }
7451 
7452   bool VisitCallExpr(const CallExpr *E);
7453   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7454   bool VisitBinaryOperator(const BinaryOperator *E);
7455   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7456   bool VisitUnaryOperator(const UnaryOperator *E);
7457 
7458   bool VisitCastExpr(const CastExpr* E);
7459   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7460 
7461   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7462     return Success(E->getValue(), E);
7463   }
7464 
7465   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7466     return Success(E->getValue(), E);
7467   }
7468 
7469   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7470     if (Info.ArrayInitIndex == uint64_t(-1)) {
7471       // We were asked to evaluate this subexpression independent of the
7472       // enclosing ArrayInitLoopExpr. We can't do that.
7473       Info.FFDiag(E);
7474       return false;
7475     }
7476     return Success(Info.ArrayInitIndex, E);
7477   }
7478 
7479   // Note, GNU defines __null as an integer, not a pointer.
7480   bool VisitGNUNullExpr(const GNUNullExpr *E) {
7481     return ZeroInitialization(E);
7482   }
7483 
7484   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7485     return Success(E->getValue(), E);
7486   }
7487 
7488   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7489     return Success(E->getValue(), E);
7490   }
7491 
7492   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7493     return Success(E->getValue(), E);
7494   }
7495 
7496   bool VisitUnaryReal(const UnaryOperator *E);
7497   bool VisitUnaryImag(const UnaryOperator *E);
7498 
7499   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7500   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7501 
7502   // FIXME: Missing: array subscript of vector, member of vector
7503 };
7504 
7505 class FixedPointExprEvaluator
7506     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7507   APValue &Result;
7508 
7509  public:
7510   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7511       : ExprEvaluatorBaseTy(info), Result(result) {}
7512 
7513   bool Success(const llvm::APInt &I, const Expr *E) {
7514     return Success(
7515         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
7516   }
7517 
7518   bool Success(uint64_t Value, const Expr *E) {
7519     return Success(
7520         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
7521   }
7522 
7523   bool Success(const APValue &V, const Expr *E) {
7524     return Success(V.getFixedPoint(), E);
7525   }
7526 
7527   bool Success(const APFixedPoint &V, const Expr *E) {
7528     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7529     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7530            "Invalid evaluation result.");
7531     Result = APValue(V);
7532     return true;
7533   }
7534 
7535   //===--------------------------------------------------------------------===//
7536   //                            Visitor Methods
7537   //===--------------------------------------------------------------------===//
7538 
7539   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7540     return Success(E->getValue(), E);
7541   }
7542 
7543   bool VisitCastExpr(const CastExpr *E);
7544   bool VisitUnaryOperator(const UnaryOperator *E);
7545   bool VisitBinaryOperator(const BinaryOperator *E);
7546 };
7547 } // end anonymous namespace
7548 
7549 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7550 /// produce either the integer value or a pointer.
7551 ///
7552 /// GCC has a heinous extension which folds casts between pointer types and
7553 /// pointer-sized integral types. We support this by allowing the evaluation of
7554 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7555 /// Some simple arithmetic on such values is supported (they are treated much
7556 /// like char*).
7557 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7558                                     EvalInfo &Info) {
7559   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7560   return IntExprEvaluator(Info, Result).Visit(E);
7561 }
7562 
7563 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7564   APValue Val;
7565   if (!EvaluateIntegerOrLValue(E, Val, Info))
7566     return false;
7567   if (!Val.isInt()) {
7568     // FIXME: It would be better to produce the diagnostic for casting
7569     //        a pointer to an integer.
7570     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7571     return false;
7572   }
7573   Result = Val.getInt();
7574   return true;
7575 }
7576 
7577 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
7578                                EvalInfo &Info) {
7579   if (E->getType()->isFixedPointType()) {
7580     APValue Val;
7581     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
7582       return false;
7583     if (!Val.isFixedPoint())
7584       return false;
7585 
7586     Result = Val.getFixedPoint();
7587     return true;
7588   }
7589   return false;
7590 }
7591 
7592 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
7593                                         EvalInfo &Info) {
7594   if (E->getType()->isIntegerType()) {
7595     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
7596     APSInt Val;
7597     if (!EvaluateInteger(E, Val, Info))
7598       return false;
7599     Result = APFixedPoint(Val, FXSema);
7600     return true;
7601   } else if (E->getType()->isFixedPointType()) {
7602     return EvaluateFixedPoint(E, Result, Info);
7603   }
7604   return false;
7605 }
7606 
7607 /// Check whether the given declaration can be directly converted to an integral
7608 /// rvalue. If not, no diagnostic is produced; there are other things we can
7609 /// try.
7610 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7611   // Enums are integer constant exprs.
7612   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7613     // Check for signedness/width mismatches between E type and ECD value.
7614     bool SameSign = (ECD->getInitVal().isSigned()
7615                      == E->getType()->isSignedIntegerOrEnumerationType());
7616     bool SameWidth = (ECD->getInitVal().getBitWidth()
7617                       == Info.Ctx.getIntWidth(E->getType()));
7618     if (SameSign && SameWidth)
7619       return Success(ECD->getInitVal(), E);
7620     else {
7621       // Get rid of mismatch (otherwise Success assertions will fail)
7622       // by computing a new value matching the type of E.
7623       llvm::APSInt Val = ECD->getInitVal();
7624       if (!SameSign)
7625         Val.setIsSigned(!ECD->getInitVal().isSigned());
7626       if (!SameWidth)
7627         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7628       return Success(Val, E);
7629     }
7630   }
7631   return false;
7632 }
7633 
7634 /// Values returned by __builtin_classify_type, chosen to match the values
7635 /// produced by GCC's builtin.
7636 enum class GCCTypeClass {
7637   None = -1,
7638   Void = 0,
7639   Integer = 1,
7640   // GCC reserves 2 for character types, but instead classifies them as
7641   // integers.
7642   Enum = 3,
7643   Bool = 4,
7644   Pointer = 5,
7645   // GCC reserves 6 for references, but appears to never use it (because
7646   // expressions never have reference type, presumably).
7647   PointerToDataMember = 7,
7648   RealFloat = 8,
7649   Complex = 9,
7650   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7651   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7652   // GCC claims to reserve 11 for pointers to member functions, but *actually*
7653   // uses 12 for that purpose, same as for a class or struct. Maybe it
7654   // internally implements a pointer to member as a struct?  Who knows.
7655   PointerToMemberFunction = 12, // Not a bug, see above.
7656   ClassOrStruct = 12,
7657   Union = 13,
7658   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7659   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7660   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7661   // literals.
7662 };
7663 
7664 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7665 /// as GCC.
7666 static GCCTypeClass
7667 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7668   assert(!T->isDependentType() && "unexpected dependent type");
7669 
7670   QualType CanTy = T.getCanonicalType();
7671   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7672 
7673   switch (CanTy->getTypeClass()) {
7674 #define TYPE(ID, BASE)
7675 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7676 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7677 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7678 #include "clang/AST/TypeNodes.def"
7679   case Type::Auto:
7680   case Type::DeducedTemplateSpecialization:
7681       llvm_unreachable("unexpected non-canonical or dependent type");
7682 
7683   case Type::Builtin:
7684     switch (BT->getKind()) {
7685 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7686 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7687     case BuiltinType::ID: return GCCTypeClass::Integer;
7688 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7689     case BuiltinType::ID: return GCCTypeClass::RealFloat;
7690 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7691     case BuiltinType::ID: break;
7692 #include "clang/AST/BuiltinTypes.def"
7693     case BuiltinType::Void:
7694       return GCCTypeClass::Void;
7695 
7696     case BuiltinType::Bool:
7697       return GCCTypeClass::Bool;
7698 
7699     case BuiltinType::Char_U:
7700     case BuiltinType::UChar:
7701     case BuiltinType::WChar_U:
7702     case BuiltinType::Char8:
7703     case BuiltinType::Char16:
7704     case BuiltinType::Char32:
7705     case BuiltinType::UShort:
7706     case BuiltinType::UInt:
7707     case BuiltinType::ULong:
7708     case BuiltinType::ULongLong:
7709     case BuiltinType::UInt128:
7710       return GCCTypeClass::Integer;
7711 
7712     case BuiltinType::UShortAccum:
7713     case BuiltinType::UAccum:
7714     case BuiltinType::ULongAccum:
7715     case BuiltinType::UShortFract:
7716     case BuiltinType::UFract:
7717     case BuiltinType::ULongFract:
7718     case BuiltinType::SatUShortAccum:
7719     case BuiltinType::SatUAccum:
7720     case BuiltinType::SatULongAccum:
7721     case BuiltinType::SatUShortFract:
7722     case BuiltinType::SatUFract:
7723     case BuiltinType::SatULongFract:
7724       return GCCTypeClass::None;
7725 
7726     case BuiltinType::NullPtr:
7727 
7728     case BuiltinType::ObjCId:
7729     case BuiltinType::ObjCClass:
7730     case BuiltinType::ObjCSel:
7731 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7732     case BuiltinType::Id:
7733 #include "clang/Basic/OpenCLImageTypes.def"
7734 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7735     case BuiltinType::Id:
7736 #include "clang/Basic/OpenCLExtensionTypes.def"
7737     case BuiltinType::OCLSampler:
7738     case BuiltinType::OCLEvent:
7739     case BuiltinType::OCLClkEvent:
7740     case BuiltinType::OCLQueue:
7741     case BuiltinType::OCLReserveID:
7742       return GCCTypeClass::None;
7743 
7744     case BuiltinType::Dependent:
7745       llvm_unreachable("unexpected dependent type");
7746     };
7747     llvm_unreachable("unexpected placeholder type");
7748 
7749   case Type::Enum:
7750     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7751 
7752   case Type::Pointer:
7753   case Type::ConstantArray:
7754   case Type::VariableArray:
7755   case Type::IncompleteArray:
7756   case Type::FunctionNoProto:
7757   case Type::FunctionProto:
7758     return GCCTypeClass::Pointer;
7759 
7760   case Type::MemberPointer:
7761     return CanTy->isMemberDataPointerType()
7762                ? GCCTypeClass::PointerToDataMember
7763                : GCCTypeClass::PointerToMemberFunction;
7764 
7765   case Type::Complex:
7766     return GCCTypeClass::Complex;
7767 
7768   case Type::Record:
7769     return CanTy->isUnionType() ? GCCTypeClass::Union
7770                                 : GCCTypeClass::ClassOrStruct;
7771 
7772   case Type::Atomic:
7773     // GCC classifies _Atomic T the same as T.
7774     return EvaluateBuiltinClassifyType(
7775         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7776 
7777   case Type::BlockPointer:
7778   case Type::Vector:
7779   case Type::ExtVector:
7780   case Type::ObjCObject:
7781   case Type::ObjCInterface:
7782   case Type::ObjCObjectPointer:
7783   case Type::Pipe:
7784     // GCC classifies vectors as None. We follow its lead and classify all
7785     // other types that don't fit into the regular classification the same way.
7786     return GCCTypeClass::None;
7787 
7788   case Type::LValueReference:
7789   case Type::RValueReference:
7790     llvm_unreachable("invalid type for expression");
7791   }
7792 
7793   llvm_unreachable("unexpected type class");
7794 }
7795 
7796 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7797 /// as GCC.
7798 static GCCTypeClass
7799 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7800   // If no argument was supplied, default to None. This isn't
7801   // ideal, however it is what gcc does.
7802   if (E->getNumArgs() == 0)
7803     return GCCTypeClass::None;
7804 
7805   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7806   // being an ICE, but still folds it to a constant using the type of the first
7807   // argument.
7808   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7809 }
7810 
7811 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7812 /// __builtin_constant_p when applied to the given lvalue.
7813 ///
7814 /// An lvalue is only "constant" if it is a pointer or reference to the first
7815 /// character of a string literal.
7816 template<typename LValue>
7817 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7818   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7819   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7820 }
7821 
7822 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7823 /// GCC as we can manage.
7824 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7825   QualType ArgType = Arg->getType();
7826 
7827   // __builtin_constant_p always has one operand. The rules which gcc follows
7828   // are not precisely documented, but are as follows:
7829   //
7830   //  - If the operand is of integral, floating, complex or enumeration type,
7831   //    and can be folded to a known value of that type, it returns 1.
7832   //  - If the operand and can be folded to a pointer to the first character
7833   //    of a string literal (or such a pointer cast to an integral type), it
7834   //    returns 1.
7835   //
7836   // Otherwise, it returns 0.
7837   //
7838   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7839   // its support for this does not currently work.
7840   if (ArgType->isIntegralOrEnumerationType()) {
7841     Expr::EvalResult Result;
7842     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7843       return false;
7844 
7845     APValue &V = Result.Val;
7846     if (V.getKind() == APValue::Int)
7847       return true;
7848     if (V.getKind() == APValue::LValue)
7849       return EvaluateBuiltinConstantPForLValue(V);
7850   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7851     return Arg->isEvaluatable(Ctx);
7852   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7853     LValue LV;
7854     Expr::EvalStatus Status;
7855     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7856     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7857                           : EvaluatePointer(Arg, LV, Info)) &&
7858         !Status.HasSideEffects)
7859       return EvaluateBuiltinConstantPForLValue(LV);
7860   }
7861 
7862   // Anything else isn't considered to be sufficiently constant.
7863   return false;
7864 }
7865 
7866 /// Retrieves the "underlying object type" of the given expression,
7867 /// as used by __builtin_object_size.
7868 static QualType getObjectType(APValue::LValueBase B) {
7869   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7870     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7871       return VD->getType();
7872   } else if (const Expr *E = B.get<const Expr*>()) {
7873     if (isa<CompoundLiteralExpr>(E))
7874       return E->getType();
7875   }
7876 
7877   return QualType();
7878 }
7879 
7880 /// A more selective version of E->IgnoreParenCasts for
7881 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7882 /// to change the type of E.
7883 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7884 ///
7885 /// Always returns an RValue with a pointer representation.
7886 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7887   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7888 
7889   auto *NoParens = E->IgnoreParens();
7890   auto *Cast = dyn_cast<CastExpr>(NoParens);
7891   if (Cast == nullptr)
7892     return NoParens;
7893 
7894   // We only conservatively allow a few kinds of casts, because this code is
7895   // inherently a simple solution that seeks to support the common case.
7896   auto CastKind = Cast->getCastKind();
7897   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7898       CastKind != CK_AddressSpaceConversion)
7899     return NoParens;
7900 
7901   auto *SubExpr = Cast->getSubExpr();
7902   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7903     return NoParens;
7904   return ignorePointerCastsAndParens(SubExpr);
7905 }
7906 
7907 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7908 /// record layout. e.g.
7909 ///   struct { struct { int a, b; } fst, snd; } obj;
7910 ///   obj.fst   // no
7911 ///   obj.snd   // yes
7912 ///   obj.fst.a // no
7913 ///   obj.fst.b // no
7914 ///   obj.snd.a // no
7915 ///   obj.snd.b // yes
7916 ///
7917 /// Please note: this function is specialized for how __builtin_object_size
7918 /// views "objects".
7919 ///
7920 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7921 /// correct result, it will always return true.
7922 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7923   assert(!LVal.Designator.Invalid);
7924 
7925   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7926     const RecordDecl *Parent = FD->getParent();
7927     Invalid = Parent->isInvalidDecl();
7928     if (Invalid || Parent->isUnion())
7929       return true;
7930     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7931     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7932   };
7933 
7934   auto &Base = LVal.getLValueBase();
7935   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7936     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7937       bool Invalid;
7938       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7939         return Invalid;
7940     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7941       for (auto *FD : IFD->chain()) {
7942         bool Invalid;
7943         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7944           return Invalid;
7945       }
7946     }
7947   }
7948 
7949   unsigned I = 0;
7950   QualType BaseType = getType(Base);
7951   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7952     // If we don't know the array bound, conservatively assume we're looking at
7953     // the final array element.
7954     ++I;
7955     if (BaseType->isIncompleteArrayType())
7956       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7957     else
7958       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7959   }
7960 
7961   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7962     const auto &Entry = LVal.Designator.Entries[I];
7963     if (BaseType->isArrayType()) {
7964       // Because __builtin_object_size treats arrays as objects, we can ignore
7965       // the index iff this is the last array in the Designator.
7966       if (I + 1 == E)
7967         return true;
7968       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7969       uint64_t Index = Entry.ArrayIndex;
7970       if (Index + 1 != CAT->getSize())
7971         return false;
7972       BaseType = CAT->getElementType();
7973     } else if (BaseType->isAnyComplexType()) {
7974       const auto *CT = BaseType->castAs<ComplexType>();
7975       uint64_t Index = Entry.ArrayIndex;
7976       if (Index != 1)
7977         return false;
7978       BaseType = CT->getElementType();
7979     } else if (auto *FD = getAsField(Entry)) {
7980       bool Invalid;
7981       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7982         return Invalid;
7983       BaseType = FD->getType();
7984     } else {
7985       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7986       return false;
7987     }
7988   }
7989   return true;
7990 }
7991 
7992 /// Tests to see if the LValue has a user-specified designator (that isn't
7993 /// necessarily valid). Note that this always returns 'true' if the LValue has
7994 /// an unsized array as its first designator entry, because there's currently no
7995 /// way to tell if the user typed *foo or foo[0].
7996 static bool refersToCompleteObject(const LValue &LVal) {
7997   if (LVal.Designator.Invalid)
7998     return false;
7999 
8000   if (!LVal.Designator.Entries.empty())
8001     return LVal.Designator.isMostDerivedAnUnsizedArray();
8002 
8003   if (!LVal.InvalidBase)
8004     return true;
8005 
8006   // If `E` is a MemberExpr, then the first part of the designator is hiding in
8007   // the LValueBase.
8008   const auto *E = LVal.Base.dyn_cast<const Expr *>();
8009   return !E || !isa<MemberExpr>(E);
8010 }
8011 
8012 /// Attempts to detect a user writing into a piece of memory that's impossible
8013 /// to figure out the size of by just using types.
8014 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8015   const SubobjectDesignator &Designator = LVal.Designator;
8016   // Notes:
8017   // - Users can only write off of the end when we have an invalid base. Invalid
8018   //   bases imply we don't know where the memory came from.
8019   // - We used to be a bit more aggressive here; we'd only be conservative if
8020   //   the array at the end was flexible, or if it had 0 or 1 elements. This
8021   //   broke some common standard library extensions (PR30346), but was
8022   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
8023   //   with some sort of whitelist. OTOH, it seems that GCC is always
8024   //   conservative with the last element in structs (if it's an array), so our
8025   //   current behavior is more compatible than a whitelisting approach would
8026   //   be.
8027   return LVal.InvalidBase &&
8028          Designator.Entries.size() == Designator.MostDerivedPathLength &&
8029          Designator.MostDerivedIsArrayElement &&
8030          isDesignatorAtObjectEnd(Ctx, LVal);
8031 }
8032 
8033 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8034 /// Fails if the conversion would cause loss of precision.
8035 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8036                                             CharUnits &Result) {
8037   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8038   if (Int.ugt(CharUnitsMax))
8039     return false;
8040   Result = CharUnits::fromQuantity(Int.getZExtValue());
8041   return true;
8042 }
8043 
8044 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8045 /// determine how many bytes exist from the beginning of the object to either
8046 /// the end of the current subobject, or the end of the object itself, depending
8047 /// on what the LValue looks like + the value of Type.
8048 ///
8049 /// If this returns false, the value of Result is undefined.
8050 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8051                                unsigned Type, const LValue &LVal,
8052                                CharUnits &EndOffset) {
8053   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8054 
8055   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8056     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8057       return false;
8058     return HandleSizeof(Info, ExprLoc, Ty, Result);
8059   };
8060 
8061   // We want to evaluate the size of the entire object. This is a valid fallback
8062   // for when Type=1 and the designator is invalid, because we're asked for an
8063   // upper-bound.
8064   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8065     // Type=3 wants a lower bound, so we can't fall back to this.
8066     if (Type == 3 && !DetermineForCompleteObject)
8067       return false;
8068 
8069     llvm::APInt APEndOffset;
8070     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8071         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8072       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8073 
8074     if (LVal.InvalidBase)
8075       return false;
8076 
8077     QualType BaseTy = getObjectType(LVal.getLValueBase());
8078     return CheckedHandleSizeof(BaseTy, EndOffset);
8079   }
8080 
8081   // We want to evaluate the size of a subobject.
8082   const SubobjectDesignator &Designator = LVal.Designator;
8083 
8084   // The following is a moderately common idiom in C:
8085   //
8086   // struct Foo { int a; char c[1]; };
8087   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8088   // strcpy(&F->c[0], Bar);
8089   //
8090   // In order to not break too much legacy code, we need to support it.
8091   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8092     // If we can resolve this to an alloc_size call, we can hand that back,
8093     // because we know for certain how many bytes there are to write to.
8094     llvm::APInt APEndOffset;
8095     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8096         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8097       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8098 
8099     // If we cannot determine the size of the initial allocation, then we can't
8100     // given an accurate upper-bound. However, we are still able to give
8101     // conservative lower-bounds for Type=3.
8102     if (Type == 1)
8103       return false;
8104   }
8105 
8106   CharUnits BytesPerElem;
8107   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8108     return false;
8109 
8110   // According to the GCC documentation, we want the size of the subobject
8111   // denoted by the pointer. But that's not quite right -- what we actually
8112   // want is the size of the immediately-enclosing array, if there is one.
8113   int64_t ElemsRemaining;
8114   if (Designator.MostDerivedIsArrayElement &&
8115       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8116     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8117     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8118     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8119   } else {
8120     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8121   }
8122 
8123   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8124   return true;
8125 }
8126 
8127 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8128 /// returns true and stores the result in @p Size.
8129 ///
8130 /// If @p WasError is non-null, this will report whether the failure to evaluate
8131 /// is to be treated as an Error in IntExprEvaluator.
8132 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8133                                          EvalInfo &Info, uint64_t &Size) {
8134   // Determine the denoted object.
8135   LValue LVal;
8136   {
8137     // The operand of __builtin_object_size is never evaluated for side-effects.
8138     // If there are any, but we can determine the pointed-to object anyway, then
8139     // ignore the side-effects.
8140     SpeculativeEvaluationRAII SpeculativeEval(Info);
8141     IgnoreSideEffectsRAII Fold(Info);
8142 
8143     if (E->isGLValue()) {
8144       // It's possible for us to be given GLValues if we're called via
8145       // Expr::tryEvaluateObjectSize.
8146       APValue RVal;
8147       if (!EvaluateAsRValue(Info, E, RVal))
8148         return false;
8149       LVal.setFrom(Info.Ctx, RVal);
8150     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8151                                 /*InvalidBaseOK=*/true))
8152       return false;
8153   }
8154 
8155   // If we point to before the start of the object, there are no accessible
8156   // bytes.
8157   if (LVal.getLValueOffset().isNegative()) {
8158     Size = 0;
8159     return true;
8160   }
8161 
8162   CharUnits EndOffset;
8163   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8164     return false;
8165 
8166   // If we've fallen outside of the end offset, just pretend there's nothing to
8167   // write to/read from.
8168   if (EndOffset <= LVal.getLValueOffset())
8169     Size = 0;
8170   else
8171     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8172   return true;
8173 }
8174 
8175 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8176   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8177   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8178 }
8179 
8180 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8181   if (unsigned BuiltinOp = E->getBuiltinCallee())
8182     return VisitBuiltinCallExpr(E, BuiltinOp);
8183 
8184   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8185 }
8186 
8187 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8188                                             unsigned BuiltinOp) {
8189   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8190   default:
8191     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8192 
8193   case Builtin::BI__builtin_dynamic_object_size:
8194   case Builtin::BI__builtin_object_size: {
8195     // The type was checked when we built the expression.
8196     unsigned Type =
8197         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8198     assert(Type <= 3 && "unexpected type");
8199 
8200     uint64_t Size;
8201     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8202       return Success(Size, E);
8203 
8204     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8205       return Success((Type & 2) ? 0 : -1, E);
8206 
8207     // Expression had no side effects, but we couldn't statically determine the
8208     // size of the referenced object.
8209     switch (Info.EvalMode) {
8210     case EvalInfo::EM_ConstantExpression:
8211     case EvalInfo::EM_PotentialConstantExpression:
8212     case EvalInfo::EM_ConstantFold:
8213     case EvalInfo::EM_EvaluateForOverflow:
8214     case EvalInfo::EM_IgnoreSideEffects:
8215       // Leave it to IR generation.
8216       return Error(E);
8217     case EvalInfo::EM_ConstantExpressionUnevaluated:
8218     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8219       // Reduce it to a constant now.
8220       return Success((Type & 2) ? 0 : -1, E);
8221     }
8222 
8223     llvm_unreachable("unexpected EvalMode");
8224   }
8225 
8226   case Builtin::BI__builtin_os_log_format_buffer_size: {
8227     analyze_os_log::OSLogBufferLayout Layout;
8228     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8229     return Success(Layout.size().getQuantity(), E);
8230   }
8231 
8232   case Builtin::BI__builtin_bswap16:
8233   case Builtin::BI__builtin_bswap32:
8234   case Builtin::BI__builtin_bswap64: {
8235     APSInt Val;
8236     if (!EvaluateInteger(E->getArg(0), Val, Info))
8237       return false;
8238 
8239     return Success(Val.byteSwap(), E);
8240   }
8241 
8242   case Builtin::BI__builtin_classify_type:
8243     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8244 
8245   case Builtin::BI__builtin_clrsb:
8246   case Builtin::BI__builtin_clrsbl:
8247   case Builtin::BI__builtin_clrsbll: {
8248     APSInt Val;
8249     if (!EvaluateInteger(E->getArg(0), Val, Info))
8250       return false;
8251 
8252     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8253   }
8254 
8255   case Builtin::BI__builtin_clz:
8256   case Builtin::BI__builtin_clzl:
8257   case Builtin::BI__builtin_clzll:
8258   case Builtin::BI__builtin_clzs: {
8259     APSInt Val;
8260     if (!EvaluateInteger(E->getArg(0), Val, Info))
8261       return false;
8262     if (!Val)
8263       return Error(E);
8264 
8265     return Success(Val.countLeadingZeros(), E);
8266   }
8267 
8268   case Builtin::BI__builtin_constant_p: {
8269     auto Arg = E->getArg(0);
8270     if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8271       return Success(true, E);
8272     auto ArgTy = Arg->IgnoreImplicit()->getType();
8273     if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8274         !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8275       // We can delay calculation of __builtin_constant_p until after
8276       // inlining. Note: This diagnostic won't be shown to the user.
8277       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8278       return false;
8279     }
8280     return Success(false, E);
8281   }
8282 
8283   case Builtin::BI__builtin_ctz:
8284   case Builtin::BI__builtin_ctzl:
8285   case Builtin::BI__builtin_ctzll:
8286   case Builtin::BI__builtin_ctzs: {
8287     APSInt Val;
8288     if (!EvaluateInteger(E->getArg(0), Val, Info))
8289       return false;
8290     if (!Val)
8291       return Error(E);
8292 
8293     return Success(Val.countTrailingZeros(), E);
8294   }
8295 
8296   case Builtin::BI__builtin_eh_return_data_regno: {
8297     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8298     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8299     return Success(Operand, E);
8300   }
8301 
8302   case Builtin::BI__builtin_expect:
8303     return Visit(E->getArg(0));
8304 
8305   case Builtin::BI__builtin_ffs:
8306   case Builtin::BI__builtin_ffsl:
8307   case Builtin::BI__builtin_ffsll: {
8308     APSInt Val;
8309     if (!EvaluateInteger(E->getArg(0), Val, Info))
8310       return false;
8311 
8312     unsigned N = Val.countTrailingZeros();
8313     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8314   }
8315 
8316   case Builtin::BI__builtin_fpclassify: {
8317     APFloat Val(0.0);
8318     if (!EvaluateFloat(E->getArg(5), Val, Info))
8319       return false;
8320     unsigned Arg;
8321     switch (Val.getCategory()) {
8322     case APFloat::fcNaN: Arg = 0; break;
8323     case APFloat::fcInfinity: Arg = 1; break;
8324     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8325     case APFloat::fcZero: Arg = 4; break;
8326     }
8327     return Visit(E->getArg(Arg));
8328   }
8329 
8330   case Builtin::BI__builtin_isinf_sign: {
8331     APFloat Val(0.0);
8332     return EvaluateFloat(E->getArg(0), Val, Info) &&
8333            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8334   }
8335 
8336   case Builtin::BI__builtin_isinf: {
8337     APFloat Val(0.0);
8338     return EvaluateFloat(E->getArg(0), Val, Info) &&
8339            Success(Val.isInfinity() ? 1 : 0, E);
8340   }
8341 
8342   case Builtin::BI__builtin_isfinite: {
8343     APFloat Val(0.0);
8344     return EvaluateFloat(E->getArg(0), Val, Info) &&
8345            Success(Val.isFinite() ? 1 : 0, E);
8346   }
8347 
8348   case Builtin::BI__builtin_isnan: {
8349     APFloat Val(0.0);
8350     return EvaluateFloat(E->getArg(0), Val, Info) &&
8351            Success(Val.isNaN() ? 1 : 0, E);
8352   }
8353 
8354   case Builtin::BI__builtin_isnormal: {
8355     APFloat Val(0.0);
8356     return EvaluateFloat(E->getArg(0), Val, Info) &&
8357            Success(Val.isNormal() ? 1 : 0, E);
8358   }
8359 
8360   case Builtin::BI__builtin_parity:
8361   case Builtin::BI__builtin_parityl:
8362   case Builtin::BI__builtin_parityll: {
8363     APSInt Val;
8364     if (!EvaluateInteger(E->getArg(0), Val, Info))
8365       return false;
8366 
8367     return Success(Val.countPopulation() % 2, E);
8368   }
8369 
8370   case Builtin::BI__builtin_popcount:
8371   case Builtin::BI__builtin_popcountl:
8372   case Builtin::BI__builtin_popcountll: {
8373     APSInt Val;
8374     if (!EvaluateInteger(E->getArg(0), Val, Info))
8375       return false;
8376 
8377     return Success(Val.countPopulation(), E);
8378   }
8379 
8380   case Builtin::BIstrlen:
8381   case Builtin::BIwcslen:
8382     // A call to strlen is not a constant expression.
8383     if (Info.getLangOpts().CPlusPlus11)
8384       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8385         << /*isConstexpr*/0 << /*isConstructor*/0
8386         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8387     else
8388       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8389     LLVM_FALLTHROUGH;
8390   case Builtin::BI__builtin_strlen:
8391   case Builtin::BI__builtin_wcslen: {
8392     // As an extension, we support __builtin_strlen() as a constant expression,
8393     // and support folding strlen() to a constant.
8394     LValue String;
8395     if (!EvaluatePointer(E->getArg(0), String, Info))
8396       return false;
8397 
8398     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8399 
8400     // Fast path: if it's a string literal, search the string value.
8401     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8402             String.getLValueBase().dyn_cast<const Expr *>())) {
8403       // The string literal may have embedded null characters. Find the first
8404       // one and truncate there.
8405       StringRef Str = S->getBytes();
8406       int64_t Off = String.Offset.getQuantity();
8407       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8408           S->getCharByteWidth() == 1 &&
8409           // FIXME: Add fast-path for wchar_t too.
8410           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8411         Str = Str.substr(Off);
8412 
8413         StringRef::size_type Pos = Str.find(0);
8414         if (Pos != StringRef::npos)
8415           Str = Str.substr(0, Pos);
8416 
8417         return Success(Str.size(), E);
8418       }
8419 
8420       // Fall through to slow path to issue appropriate diagnostic.
8421     }
8422 
8423     // Slow path: scan the bytes of the string looking for the terminating 0.
8424     for (uint64_t Strlen = 0; /**/; ++Strlen) {
8425       APValue Char;
8426       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8427           !Char.isInt())
8428         return false;
8429       if (!Char.getInt())
8430         return Success(Strlen, E);
8431       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8432         return false;
8433     }
8434   }
8435 
8436   case Builtin::BIstrcmp:
8437   case Builtin::BIwcscmp:
8438   case Builtin::BIstrncmp:
8439   case Builtin::BIwcsncmp:
8440   case Builtin::BImemcmp:
8441   case Builtin::BIwmemcmp:
8442     // A call to strlen is not a constant expression.
8443     if (Info.getLangOpts().CPlusPlus11)
8444       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8445         << /*isConstexpr*/0 << /*isConstructor*/0
8446         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8447     else
8448       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8449     LLVM_FALLTHROUGH;
8450   case Builtin::BI__builtin_strcmp:
8451   case Builtin::BI__builtin_wcscmp:
8452   case Builtin::BI__builtin_strncmp:
8453   case Builtin::BI__builtin_wcsncmp:
8454   case Builtin::BI__builtin_memcmp:
8455   case Builtin::BI__builtin_wmemcmp: {
8456     LValue String1, String2;
8457     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8458         !EvaluatePointer(E->getArg(1), String2, Info))
8459       return false;
8460 
8461     uint64_t MaxLength = uint64_t(-1);
8462     if (BuiltinOp != Builtin::BIstrcmp &&
8463         BuiltinOp != Builtin::BIwcscmp &&
8464         BuiltinOp != Builtin::BI__builtin_strcmp &&
8465         BuiltinOp != Builtin::BI__builtin_wcscmp) {
8466       APSInt N;
8467       if (!EvaluateInteger(E->getArg(2), N, Info))
8468         return false;
8469       MaxLength = N.getExtValue();
8470     }
8471 
8472     // Empty substrings compare equal by definition.
8473     if (MaxLength == 0u)
8474       return Success(0, E);
8475 
8476     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8477         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8478         String1.Designator.Invalid || String2.Designator.Invalid)
8479       return false;
8480 
8481     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8482     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8483 
8484     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
8485                      BuiltinOp == Builtin::BI__builtin_memcmp;
8486 
8487     assert(IsRawByte ||
8488            (Info.Ctx.hasSameUnqualifiedType(
8489                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8490             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8491 
8492     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8493       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8494              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8495              Char1.isInt() && Char2.isInt();
8496     };
8497     const auto &AdvanceElems = [&] {
8498       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8499              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8500     };
8501 
8502     if (IsRawByte) {
8503       uint64_t BytesRemaining = MaxLength;
8504       // Pointers to const void may point to objects of incomplete type.
8505       if (CharTy1->isIncompleteType()) {
8506         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8507         return false;
8508       }
8509       if (CharTy2->isIncompleteType()) {
8510         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8511         return false;
8512       }
8513       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8514       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8515       // Give up on comparing between elements with disparate widths.
8516       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8517         return false;
8518       uint64_t BytesPerElement = CharTy1Size.getQuantity();
8519       assert(BytesRemaining && "BytesRemaining should not be zero: the "
8520                                "following loop considers at least one element");
8521       while (true) {
8522         APValue Char1, Char2;
8523         if (!ReadCurElems(Char1, Char2))
8524           return false;
8525         // We have compatible in-memory widths, but a possible type and
8526         // (for `bool`) internal representation mismatch.
8527         // Assuming two's complement representation, including 0 for `false` and
8528         // 1 for `true`, we can check an appropriate number of elements for
8529         // equality even if they are not byte-sized.
8530         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8531         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8532         if (Char1InMem.ne(Char2InMem)) {
8533           // If the elements are byte-sized, then we can produce a three-way
8534           // comparison result in a straightforward manner.
8535           if (BytesPerElement == 1u) {
8536             // memcmp always compares unsigned chars.
8537             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8538           }
8539           // The result is byte-order sensitive, and we have multibyte elements.
8540           // FIXME: We can compare the remaining bytes in the correct order.
8541           return false;
8542         }
8543         if (!AdvanceElems())
8544           return false;
8545         if (BytesRemaining <= BytesPerElement)
8546           break;
8547         BytesRemaining -= BytesPerElement;
8548       }
8549       // Enough elements are equal to account for the memcmp limit.
8550       return Success(0, E);
8551     }
8552 
8553     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8554                        BuiltinOp != Builtin::BIwmemcmp &&
8555                        BuiltinOp != Builtin::BI__builtin_memcmp &&
8556                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
8557     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8558                   BuiltinOp == Builtin::BIwcsncmp ||
8559                   BuiltinOp == Builtin::BIwmemcmp ||
8560                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
8561                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8562                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
8563 
8564     for (; MaxLength; --MaxLength) {
8565       APValue Char1, Char2;
8566       if (!ReadCurElems(Char1, Char2))
8567         return false;
8568       if (Char1.getInt() != Char2.getInt()) {
8569         if (IsWide) // wmemcmp compares with wchar_t signedness.
8570           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8571         // memcmp always compares unsigned chars.
8572         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8573       }
8574       if (StopAtNull && !Char1.getInt())
8575         return Success(0, E);
8576       assert(!(StopAtNull && !Char2.getInt()));
8577       if (!AdvanceElems())
8578         return false;
8579     }
8580     // We hit the strncmp / memcmp limit.
8581     return Success(0, E);
8582   }
8583 
8584   case Builtin::BI__atomic_always_lock_free:
8585   case Builtin::BI__atomic_is_lock_free:
8586   case Builtin::BI__c11_atomic_is_lock_free: {
8587     APSInt SizeVal;
8588     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8589       return false;
8590 
8591     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8592     // of two less than the maximum inline atomic width, we know it is
8593     // lock-free.  If the size isn't a power of two, or greater than the
8594     // maximum alignment where we promote atomics, we know it is not lock-free
8595     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
8596     // the answer can only be determined at runtime; for example, 16-byte
8597     // atomics have lock-free implementations on some, but not all,
8598     // x86-64 processors.
8599 
8600     // Check power-of-two.
8601     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8602     if (Size.isPowerOfTwo()) {
8603       // Check against inlining width.
8604       unsigned InlineWidthBits =
8605           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8606       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8607         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8608             Size == CharUnits::One() ||
8609             E->getArg(1)->isNullPointerConstant(Info.Ctx,
8610                                                 Expr::NPC_NeverValueDependent))
8611           // OK, we will inline appropriately-aligned operations of this size,
8612           // and _Atomic(T) is appropriately-aligned.
8613           return Success(1, E);
8614 
8615         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8616           castAs<PointerType>()->getPointeeType();
8617         if (!PointeeType->isIncompleteType() &&
8618             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8619           // OK, we will inline operations on this object.
8620           return Success(1, E);
8621         }
8622       }
8623     }
8624 
8625     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8626         Success(0, E) : Error(E);
8627   }
8628   case Builtin::BIomp_is_initial_device:
8629     // We can decide statically which value the runtime would return if called.
8630     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8631   case Builtin::BI__builtin_add_overflow:
8632   case Builtin::BI__builtin_sub_overflow:
8633   case Builtin::BI__builtin_mul_overflow:
8634   case Builtin::BI__builtin_sadd_overflow:
8635   case Builtin::BI__builtin_uadd_overflow:
8636   case Builtin::BI__builtin_uaddl_overflow:
8637   case Builtin::BI__builtin_uaddll_overflow:
8638   case Builtin::BI__builtin_usub_overflow:
8639   case Builtin::BI__builtin_usubl_overflow:
8640   case Builtin::BI__builtin_usubll_overflow:
8641   case Builtin::BI__builtin_umul_overflow:
8642   case Builtin::BI__builtin_umull_overflow:
8643   case Builtin::BI__builtin_umulll_overflow:
8644   case Builtin::BI__builtin_saddl_overflow:
8645   case Builtin::BI__builtin_saddll_overflow:
8646   case Builtin::BI__builtin_ssub_overflow:
8647   case Builtin::BI__builtin_ssubl_overflow:
8648   case Builtin::BI__builtin_ssubll_overflow:
8649   case Builtin::BI__builtin_smul_overflow:
8650   case Builtin::BI__builtin_smull_overflow:
8651   case Builtin::BI__builtin_smulll_overflow: {
8652     LValue ResultLValue;
8653     APSInt LHS, RHS;
8654 
8655     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8656     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8657         !EvaluateInteger(E->getArg(1), RHS, Info) ||
8658         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8659       return false;
8660 
8661     APSInt Result;
8662     bool DidOverflow = false;
8663 
8664     // If the types don't have to match, enlarge all 3 to the largest of them.
8665     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8666         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8667         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8668       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8669                       ResultType->isSignedIntegerOrEnumerationType();
8670       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8671                       ResultType->isSignedIntegerOrEnumerationType();
8672       uint64_t LHSSize = LHS.getBitWidth();
8673       uint64_t RHSSize = RHS.getBitWidth();
8674       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8675       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8676 
8677       // Add an additional bit if the signedness isn't uniformly agreed to. We
8678       // could do this ONLY if there is a signed and an unsigned that both have
8679       // MaxBits, but the code to check that is pretty nasty.  The issue will be
8680       // caught in the shrink-to-result later anyway.
8681       if (IsSigned && !AllSigned)
8682         ++MaxBits;
8683 
8684       LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8685                    !IsSigned);
8686       RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8687                    !IsSigned);
8688       Result = APSInt(MaxBits, !IsSigned);
8689     }
8690 
8691     // Find largest int.
8692     switch (BuiltinOp) {
8693     default:
8694       llvm_unreachable("Invalid value for BuiltinOp");
8695     case Builtin::BI__builtin_add_overflow:
8696     case Builtin::BI__builtin_sadd_overflow:
8697     case Builtin::BI__builtin_saddl_overflow:
8698     case Builtin::BI__builtin_saddll_overflow:
8699     case Builtin::BI__builtin_uadd_overflow:
8700     case Builtin::BI__builtin_uaddl_overflow:
8701     case Builtin::BI__builtin_uaddll_overflow:
8702       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8703                               : LHS.uadd_ov(RHS, DidOverflow);
8704       break;
8705     case Builtin::BI__builtin_sub_overflow:
8706     case Builtin::BI__builtin_ssub_overflow:
8707     case Builtin::BI__builtin_ssubl_overflow:
8708     case Builtin::BI__builtin_ssubll_overflow:
8709     case Builtin::BI__builtin_usub_overflow:
8710     case Builtin::BI__builtin_usubl_overflow:
8711     case Builtin::BI__builtin_usubll_overflow:
8712       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8713                               : LHS.usub_ov(RHS, DidOverflow);
8714       break;
8715     case Builtin::BI__builtin_mul_overflow:
8716     case Builtin::BI__builtin_smul_overflow:
8717     case Builtin::BI__builtin_smull_overflow:
8718     case Builtin::BI__builtin_smulll_overflow:
8719     case Builtin::BI__builtin_umul_overflow:
8720     case Builtin::BI__builtin_umull_overflow:
8721     case Builtin::BI__builtin_umulll_overflow:
8722       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8723                               : LHS.umul_ov(RHS, DidOverflow);
8724       break;
8725     }
8726 
8727     // In the case where multiple sizes are allowed, truncate and see if
8728     // the values are the same.
8729     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8730         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8731         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8732       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8733       // since it will give us the behavior of a TruncOrSelf in the case where
8734       // its parameter <= its size.  We previously set Result to be at least the
8735       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8736       // will work exactly like TruncOrSelf.
8737       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8738       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8739 
8740       if (!APSInt::isSameValue(Temp, Result))
8741         DidOverflow = true;
8742       Result = Temp;
8743     }
8744 
8745     APValue APV{Result};
8746     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8747       return false;
8748     return Success(DidOverflow, E);
8749   }
8750   }
8751 }
8752 
8753 /// Determine whether this is a pointer past the end of the complete
8754 /// object referred to by the lvalue.
8755 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8756                                             const LValue &LV) {
8757   // A null pointer can be viewed as being "past the end" but we don't
8758   // choose to look at it that way here.
8759   if (!LV.getLValueBase())
8760     return false;
8761 
8762   // If the designator is valid and refers to a subobject, we're not pointing
8763   // past the end.
8764   if (!LV.getLValueDesignator().Invalid &&
8765       !LV.getLValueDesignator().isOnePastTheEnd())
8766     return false;
8767 
8768   // A pointer to an incomplete type might be past-the-end if the type's size is
8769   // zero.  We cannot tell because the type is incomplete.
8770   QualType Ty = getType(LV.getLValueBase());
8771   if (Ty->isIncompleteType())
8772     return true;
8773 
8774   // We're a past-the-end pointer if we point to the byte after the object,
8775   // no matter what our type or path is.
8776   auto Size = Ctx.getTypeSizeInChars(Ty);
8777   return LV.getLValueOffset() == Size;
8778 }
8779 
8780 namespace {
8781 
8782 /// Data recursive integer evaluator of certain binary operators.
8783 ///
8784 /// We use a data recursive algorithm for binary operators so that we are able
8785 /// to handle extreme cases of chained binary operators without causing stack
8786 /// overflow.
8787 class DataRecursiveIntBinOpEvaluator {
8788   struct EvalResult {
8789     APValue Val;
8790     bool Failed;
8791 
8792     EvalResult() : Failed(false) { }
8793 
8794     void swap(EvalResult &RHS) {
8795       Val.swap(RHS.Val);
8796       Failed = RHS.Failed;
8797       RHS.Failed = false;
8798     }
8799   };
8800 
8801   struct Job {
8802     const Expr *E;
8803     EvalResult LHSResult; // meaningful only for binary operator expression.
8804     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8805 
8806     Job() = default;
8807     Job(Job &&) = default;
8808 
8809     void startSpeculativeEval(EvalInfo &Info) {
8810       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8811     }
8812 
8813   private:
8814     SpeculativeEvaluationRAII SpecEvalRAII;
8815   };
8816 
8817   SmallVector<Job, 16> Queue;
8818 
8819   IntExprEvaluator &IntEval;
8820   EvalInfo &Info;
8821   APValue &FinalResult;
8822 
8823 public:
8824   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8825     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8826 
8827   /// True if \param E is a binary operator that we are going to handle
8828   /// data recursively.
8829   /// We handle binary operators that are comma, logical, or that have operands
8830   /// with integral or enumeration type.
8831   static bool shouldEnqueue(const BinaryOperator *E) {
8832     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8833            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8834             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8835             E->getRHS()->getType()->isIntegralOrEnumerationType());
8836   }
8837 
8838   bool Traverse(const BinaryOperator *E) {
8839     enqueue(E);
8840     EvalResult PrevResult;
8841     while (!Queue.empty())
8842       process(PrevResult);
8843 
8844     if (PrevResult.Failed) return false;
8845 
8846     FinalResult.swap(PrevResult.Val);
8847     return true;
8848   }
8849 
8850 private:
8851   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8852     return IntEval.Success(Value, E, Result);
8853   }
8854   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8855     return IntEval.Success(Value, E, Result);
8856   }
8857   bool Error(const Expr *E) {
8858     return IntEval.Error(E);
8859   }
8860   bool Error(const Expr *E, diag::kind D) {
8861     return IntEval.Error(E, D);
8862   }
8863 
8864   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8865     return Info.CCEDiag(E, D);
8866   }
8867 
8868   // Returns true if visiting the RHS is necessary, false otherwise.
8869   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8870                          bool &SuppressRHSDiags);
8871 
8872   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8873                   const BinaryOperator *E, APValue &Result);
8874 
8875   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8876     Result.Failed = !Evaluate(Result.Val, Info, E);
8877     if (Result.Failed)
8878       Result.Val = APValue();
8879   }
8880 
8881   void process(EvalResult &Result);
8882 
8883   void enqueue(const Expr *E) {
8884     E = E->IgnoreParens();
8885     Queue.resize(Queue.size()+1);
8886     Queue.back().E = E;
8887     Queue.back().Kind = Job::AnyExprKind;
8888   }
8889 };
8890 
8891 }
8892 
8893 bool DataRecursiveIntBinOpEvaluator::
8894        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8895                          bool &SuppressRHSDiags) {
8896   if (E->getOpcode() == BO_Comma) {
8897     // Ignore LHS but note if we could not evaluate it.
8898     if (LHSResult.Failed)
8899       return Info.noteSideEffect();
8900     return true;
8901   }
8902 
8903   if (E->isLogicalOp()) {
8904     bool LHSAsBool;
8905     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8906       // We were able to evaluate the LHS, see if we can get away with not
8907       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8908       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8909         Success(LHSAsBool, E, LHSResult.Val);
8910         return false; // Ignore RHS
8911       }
8912     } else {
8913       LHSResult.Failed = true;
8914 
8915       // Since we weren't able to evaluate the left hand side, it
8916       // might have had side effects.
8917       if (!Info.noteSideEffect())
8918         return false;
8919 
8920       // We can't evaluate the LHS; however, sometimes the result
8921       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8922       // Don't ignore RHS and suppress diagnostics from this arm.
8923       SuppressRHSDiags = true;
8924     }
8925 
8926     return true;
8927   }
8928 
8929   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8930          E->getRHS()->getType()->isIntegralOrEnumerationType());
8931 
8932   if (LHSResult.Failed && !Info.noteFailure())
8933     return false; // Ignore RHS;
8934 
8935   return true;
8936 }
8937 
8938 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8939                                     bool IsSub) {
8940   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8941   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8942   // offsets.
8943   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8944   CharUnits &Offset = LVal.getLValueOffset();
8945   uint64_t Offset64 = Offset.getQuantity();
8946   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8947   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8948                                          : Offset64 + Index64);
8949 }
8950 
8951 bool DataRecursiveIntBinOpEvaluator::
8952        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8953                   const BinaryOperator *E, APValue &Result) {
8954   if (E->getOpcode() == BO_Comma) {
8955     if (RHSResult.Failed)
8956       return false;
8957     Result = RHSResult.Val;
8958     return true;
8959   }
8960 
8961   if (E->isLogicalOp()) {
8962     bool lhsResult, rhsResult;
8963     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8964     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8965 
8966     if (LHSIsOK) {
8967       if (RHSIsOK) {
8968         if (E->getOpcode() == BO_LOr)
8969           return Success(lhsResult || rhsResult, E, Result);
8970         else
8971           return Success(lhsResult && rhsResult, E, Result);
8972       }
8973     } else {
8974       if (RHSIsOK) {
8975         // We can't evaluate the LHS; however, sometimes the result
8976         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8977         if (rhsResult == (E->getOpcode() == BO_LOr))
8978           return Success(rhsResult, E, Result);
8979       }
8980     }
8981 
8982     return false;
8983   }
8984 
8985   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8986          E->getRHS()->getType()->isIntegralOrEnumerationType());
8987 
8988   if (LHSResult.Failed || RHSResult.Failed)
8989     return false;
8990 
8991   const APValue &LHSVal = LHSResult.Val;
8992   const APValue &RHSVal = RHSResult.Val;
8993 
8994   // Handle cases like (unsigned long)&a + 4.
8995   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8996     Result = LHSVal;
8997     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8998     return true;
8999   }
9000 
9001   // Handle cases like 4 + (unsigned long)&a
9002   if (E->getOpcode() == BO_Add &&
9003       RHSVal.isLValue() && LHSVal.isInt()) {
9004     Result = RHSVal;
9005     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
9006     return true;
9007   }
9008 
9009   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9010     // Handle (intptr_t)&&A - (intptr_t)&&B.
9011     if (!LHSVal.getLValueOffset().isZero() ||
9012         !RHSVal.getLValueOffset().isZero())
9013       return false;
9014     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9015     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9016     if (!LHSExpr || !RHSExpr)
9017       return false;
9018     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9019     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9020     if (!LHSAddrExpr || !RHSAddrExpr)
9021       return false;
9022     // Make sure both labels come from the same function.
9023     if (LHSAddrExpr->getLabel()->getDeclContext() !=
9024         RHSAddrExpr->getLabel()->getDeclContext())
9025       return false;
9026     Result = APValue(LHSAddrExpr, RHSAddrExpr);
9027     return true;
9028   }
9029 
9030   // All the remaining cases expect both operands to be an integer
9031   if (!LHSVal.isInt() || !RHSVal.isInt())
9032     return Error(E);
9033 
9034   // Set up the width and signedness manually, in case it can't be deduced
9035   // from the operation we're performing.
9036   // FIXME: Don't do this in the cases where we can deduce it.
9037   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9038                E->getType()->isUnsignedIntegerOrEnumerationType());
9039   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9040                          RHSVal.getInt(), Value))
9041     return false;
9042   return Success(Value, E, Result);
9043 }
9044 
9045 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9046   Job &job = Queue.back();
9047 
9048   switch (job.Kind) {
9049     case Job::AnyExprKind: {
9050       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9051         if (shouldEnqueue(Bop)) {
9052           job.Kind = Job::BinOpKind;
9053           enqueue(Bop->getLHS());
9054           return;
9055         }
9056       }
9057 
9058       EvaluateExpr(job.E, Result);
9059       Queue.pop_back();
9060       return;
9061     }
9062 
9063     case Job::BinOpKind: {
9064       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9065       bool SuppressRHSDiags = false;
9066       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9067         Queue.pop_back();
9068         return;
9069       }
9070       if (SuppressRHSDiags)
9071         job.startSpeculativeEval(Info);
9072       job.LHSResult.swap(Result);
9073       job.Kind = Job::BinOpVisitedLHSKind;
9074       enqueue(Bop->getRHS());
9075       return;
9076     }
9077 
9078     case Job::BinOpVisitedLHSKind: {
9079       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9080       EvalResult RHS;
9081       RHS.swap(Result);
9082       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9083       Queue.pop_back();
9084       return;
9085     }
9086   }
9087 
9088   llvm_unreachable("Invalid Job::Kind!");
9089 }
9090 
9091 namespace {
9092 /// Used when we determine that we should fail, but can keep evaluating prior to
9093 /// noting that we had a failure.
9094 class DelayedNoteFailureRAII {
9095   EvalInfo &Info;
9096   bool NoteFailure;
9097 
9098 public:
9099   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9100       : Info(Info), NoteFailure(NoteFailure) {}
9101   ~DelayedNoteFailureRAII() {
9102     if (NoteFailure) {
9103       bool ContinueAfterFailure = Info.noteFailure();
9104       (void)ContinueAfterFailure;
9105       assert(ContinueAfterFailure &&
9106              "Shouldn't have kept evaluating on failure.");
9107     }
9108   }
9109 };
9110 }
9111 
9112 template <class SuccessCB, class AfterCB>
9113 static bool
9114 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9115                                  SuccessCB &&Success, AfterCB &&DoAfter) {
9116   assert(E->isComparisonOp() && "expected comparison operator");
9117   assert((E->getOpcode() == BO_Cmp ||
9118           E->getType()->isIntegralOrEnumerationType()) &&
9119          "unsupported binary expression evaluation");
9120   auto Error = [&](const Expr *E) {
9121     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9122     return false;
9123   };
9124 
9125   using CCR = ComparisonCategoryResult;
9126   bool IsRelational = E->isRelationalOp();
9127   bool IsEquality = E->isEqualityOp();
9128   if (E->getOpcode() == BO_Cmp) {
9129     const ComparisonCategoryInfo &CmpInfo =
9130         Info.Ctx.CompCategories.getInfoForType(E->getType());
9131     IsRelational = CmpInfo.isOrdered();
9132     IsEquality = CmpInfo.isEquality();
9133   }
9134 
9135   QualType LHSTy = E->getLHS()->getType();
9136   QualType RHSTy = E->getRHS()->getType();
9137 
9138   if (LHSTy->isIntegralOrEnumerationType() &&
9139       RHSTy->isIntegralOrEnumerationType()) {
9140     APSInt LHS, RHS;
9141     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9142     if (!LHSOK && !Info.noteFailure())
9143       return false;
9144     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9145       return false;
9146     if (LHS < RHS)
9147       return Success(CCR::Less, E);
9148     if (LHS > RHS)
9149       return Success(CCR::Greater, E);
9150     return Success(CCR::Equal, E);
9151   }
9152 
9153   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
9154     ComplexValue LHS, RHS;
9155     bool LHSOK;
9156     if (E->isAssignmentOp()) {
9157       LValue LV;
9158       EvaluateLValue(E->getLHS(), LV, Info);
9159       LHSOK = false;
9160     } else if (LHSTy->isRealFloatingType()) {
9161       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9162       if (LHSOK) {
9163         LHS.makeComplexFloat();
9164         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9165       }
9166     } else {
9167       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9168     }
9169     if (!LHSOK && !Info.noteFailure())
9170       return false;
9171 
9172     if (E->getRHS()->getType()->isRealFloatingType()) {
9173       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9174         return false;
9175       RHS.makeComplexFloat();
9176       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9177     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9178       return false;
9179 
9180     if (LHS.isComplexFloat()) {
9181       APFloat::cmpResult CR_r =
9182         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9183       APFloat::cmpResult CR_i =
9184         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
9185       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9186       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9187     } else {
9188       assert(IsEquality && "invalid complex comparison");
9189       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9190                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
9191       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9192     }
9193   }
9194 
9195   if (LHSTy->isRealFloatingType() &&
9196       RHSTy->isRealFloatingType()) {
9197     APFloat RHS(0.0), LHS(0.0);
9198 
9199     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
9200     if (!LHSOK && !Info.noteFailure())
9201       return false;
9202 
9203     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
9204       return false;
9205 
9206     assert(E->isComparisonOp() && "Invalid binary operator!");
9207     auto GetCmpRes = [&]() {
9208       switch (LHS.compare(RHS)) {
9209       case APFloat::cmpEqual:
9210         return CCR::Equal;
9211       case APFloat::cmpLessThan:
9212         return CCR::Less;
9213       case APFloat::cmpGreaterThan:
9214         return CCR::Greater;
9215       case APFloat::cmpUnordered:
9216         return CCR::Unordered;
9217       }
9218       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9219     };
9220     return Success(GetCmpRes(), E);
9221   }
9222 
9223   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9224     LValue LHSValue, RHSValue;
9225 
9226     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9227     if (!LHSOK && !Info.noteFailure())
9228       return false;
9229 
9230     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9231       return false;
9232 
9233     // Reject differing bases from the normal codepath; we special-case
9234     // comparisons to null.
9235     if (!HasSameBase(LHSValue, RHSValue)) {
9236       // Inequalities and subtractions between unrelated pointers have
9237       // unspecified or undefined behavior.
9238       if (!IsEquality)
9239         return Error(E);
9240       // A constant address may compare equal to the address of a symbol.
9241       // The one exception is that address of an object cannot compare equal
9242       // to a null pointer constant.
9243       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9244           (!RHSValue.Base && !RHSValue.Offset.isZero()))
9245         return Error(E);
9246       // It's implementation-defined whether distinct literals will have
9247       // distinct addresses. In clang, the result of such a comparison is
9248       // unspecified, so it is not a constant expression. However, we do know
9249       // that the address of a literal will be non-null.
9250       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9251           LHSValue.Base && RHSValue.Base)
9252         return Error(E);
9253       // We can't tell whether weak symbols will end up pointing to the same
9254       // object.
9255       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9256         return Error(E);
9257       // We can't compare the address of the start of one object with the
9258       // past-the-end address of another object, per C++ DR1652.
9259       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9260            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9261           (RHSValue.Base && RHSValue.Offset.isZero() &&
9262            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9263         return Error(E);
9264       // We can't tell whether an object is at the same address as another
9265       // zero sized object.
9266       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9267           (LHSValue.Base && isZeroSized(RHSValue)))
9268         return Error(E);
9269       return Success(CCR::Nonequal, E);
9270     }
9271 
9272     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9273     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9274 
9275     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9276     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9277 
9278     // C++11 [expr.rel]p3:
9279     //   Pointers to void (after pointer conversions) can be compared, with a
9280     //   result defined as follows: If both pointers represent the same
9281     //   address or are both the null pointer value, the result is true if the
9282     //   operator is <= or >= and false otherwise; otherwise the result is
9283     //   unspecified.
9284     // We interpret this as applying to pointers to *cv* void.
9285     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9286       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9287 
9288     // C++11 [expr.rel]p2:
9289     // - If two pointers point to non-static data members of the same object,
9290     //   or to subobjects or array elements fo such members, recursively, the
9291     //   pointer to the later declared member compares greater provided the
9292     //   two members have the same access control and provided their class is
9293     //   not a union.
9294     //   [...]
9295     // - Otherwise pointer comparisons are unspecified.
9296     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9297       bool WasArrayIndex;
9298       unsigned Mismatch = FindDesignatorMismatch(
9299           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9300       // At the point where the designators diverge, the comparison has a
9301       // specified value if:
9302       //  - we are comparing array indices
9303       //  - we are comparing fields of a union, or fields with the same access
9304       // Otherwise, the result is unspecified and thus the comparison is not a
9305       // constant expression.
9306       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9307           Mismatch < RHSDesignator.Entries.size()) {
9308         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9309         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9310         if (!LF && !RF)
9311           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9312         else if (!LF)
9313           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9314               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9315               << RF->getParent() << RF;
9316         else if (!RF)
9317           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9318               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9319               << LF->getParent() << LF;
9320         else if (!LF->getParent()->isUnion() &&
9321                  LF->getAccess() != RF->getAccess())
9322           Info.CCEDiag(E,
9323                        diag::note_constexpr_pointer_comparison_differing_access)
9324               << LF << LF->getAccess() << RF << RF->getAccess()
9325               << LF->getParent();
9326       }
9327     }
9328 
9329     // The comparison here must be unsigned, and performed with the same
9330     // width as the pointer.
9331     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9332     uint64_t CompareLHS = LHSOffset.getQuantity();
9333     uint64_t CompareRHS = RHSOffset.getQuantity();
9334     assert(PtrSize <= 64 && "Unexpected pointer width");
9335     uint64_t Mask = ~0ULL >> (64 - PtrSize);
9336     CompareLHS &= Mask;
9337     CompareRHS &= Mask;
9338 
9339     // If there is a base and this is a relational operator, we can only
9340     // compare pointers within the object in question; otherwise, the result
9341     // depends on where the object is located in memory.
9342     if (!LHSValue.Base.isNull() && IsRelational) {
9343       QualType BaseTy = getType(LHSValue.Base);
9344       if (BaseTy->isIncompleteType())
9345         return Error(E);
9346       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9347       uint64_t OffsetLimit = Size.getQuantity();
9348       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9349         return Error(E);
9350     }
9351 
9352     if (CompareLHS < CompareRHS)
9353       return Success(CCR::Less, E);
9354     if (CompareLHS > CompareRHS)
9355       return Success(CCR::Greater, E);
9356     return Success(CCR::Equal, E);
9357   }
9358 
9359   if (LHSTy->isMemberPointerType()) {
9360     assert(IsEquality && "unexpected member pointer operation");
9361     assert(RHSTy->isMemberPointerType() && "invalid comparison");
9362 
9363     MemberPtr LHSValue, RHSValue;
9364 
9365     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9366     if (!LHSOK && !Info.noteFailure())
9367       return false;
9368 
9369     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9370       return false;
9371 
9372     // C++11 [expr.eq]p2:
9373     //   If both operands are null, they compare equal. Otherwise if only one is
9374     //   null, they compare unequal.
9375     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9376       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9377       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9378     }
9379 
9380     //   Otherwise if either is a pointer to a virtual member function, the
9381     //   result is unspecified.
9382     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9383       if (MD->isVirtual())
9384         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9385     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9386       if (MD->isVirtual())
9387         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9388 
9389     //   Otherwise they compare equal if and only if they would refer to the
9390     //   same member of the same most derived object or the same subobject if
9391     //   they were dereferenced with a hypothetical object of the associated
9392     //   class type.
9393     bool Equal = LHSValue == RHSValue;
9394     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9395   }
9396 
9397   if (LHSTy->isNullPtrType()) {
9398     assert(E->isComparisonOp() && "unexpected nullptr operation");
9399     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9400     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9401     // are compared, the result is true of the operator is <=, >= or ==, and
9402     // false otherwise.
9403     return Success(CCR::Equal, E);
9404   }
9405 
9406   return DoAfter();
9407 }
9408 
9409 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9410   if (!CheckLiteralType(Info, E))
9411     return false;
9412 
9413   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9414                        const BinaryOperator *E) {
9415     // Evaluation succeeded. Lookup the information for the comparison category
9416     // type and fetch the VarDecl for the result.
9417     const ComparisonCategoryInfo &CmpInfo =
9418         Info.Ctx.CompCategories.getInfoForType(E->getType());
9419     const VarDecl *VD =
9420         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9421     // Check and evaluate the result as a constant expression.
9422     LValue LV;
9423     LV.set(VD);
9424     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9425       return false;
9426     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9427   };
9428   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9429     return ExprEvaluatorBaseTy::VisitBinCmp(E);
9430   });
9431 }
9432 
9433 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9434   // We don't call noteFailure immediately because the assignment happens after
9435   // we evaluate LHS and RHS.
9436   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9437     return Error(E);
9438 
9439   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9440   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9441     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9442 
9443   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9444           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9445          "DataRecursiveIntBinOpEvaluator should have handled integral types");
9446 
9447   if (E->isComparisonOp()) {
9448     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9449     // comparisons and then translating the result.
9450     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9451                          const BinaryOperator *E) {
9452       using CCR = ComparisonCategoryResult;
9453       bool IsEqual   = ResKind == CCR::Equal,
9454            IsLess    = ResKind == CCR::Less,
9455            IsGreater = ResKind == CCR::Greater;
9456       auto Op = E->getOpcode();
9457       switch (Op) {
9458       default:
9459         llvm_unreachable("unsupported binary operator");
9460       case BO_EQ:
9461       case BO_NE:
9462         return Success(IsEqual == (Op == BO_EQ), E);
9463       case BO_LT: return Success(IsLess, E);
9464       case BO_GT: return Success(IsGreater, E);
9465       case BO_LE: return Success(IsEqual || IsLess, E);
9466       case BO_GE: return Success(IsEqual || IsGreater, E);
9467       }
9468     };
9469     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9470       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9471     });
9472   }
9473 
9474   QualType LHSTy = E->getLHS()->getType();
9475   QualType RHSTy = E->getRHS()->getType();
9476 
9477   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9478       E->getOpcode() == BO_Sub) {
9479     LValue LHSValue, RHSValue;
9480 
9481     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9482     if (!LHSOK && !Info.noteFailure())
9483       return false;
9484 
9485     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9486       return false;
9487 
9488     // Reject differing bases from the normal codepath; we special-case
9489     // comparisons to null.
9490     if (!HasSameBase(LHSValue, RHSValue)) {
9491       // Handle &&A - &&B.
9492       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9493         return Error(E);
9494       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9495       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9496       if (!LHSExpr || !RHSExpr)
9497         return Error(E);
9498       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9499       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9500       if (!LHSAddrExpr || !RHSAddrExpr)
9501         return Error(E);
9502       // Make sure both labels come from the same function.
9503       if (LHSAddrExpr->getLabel()->getDeclContext() !=
9504           RHSAddrExpr->getLabel()->getDeclContext())
9505         return Error(E);
9506       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9507     }
9508     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9509     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9510 
9511     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9512     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9513 
9514     // C++11 [expr.add]p6:
9515     //   Unless both pointers point to elements of the same array object, or
9516     //   one past the last element of the array object, the behavior is
9517     //   undefined.
9518     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9519         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9520                                 RHSDesignator))
9521       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9522 
9523     QualType Type = E->getLHS()->getType();
9524     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9525 
9526     CharUnits ElementSize;
9527     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9528       return false;
9529 
9530     // As an extension, a type may have zero size (empty struct or union in
9531     // C, array of zero length). Pointer subtraction in such cases has
9532     // undefined behavior, so is not constant.
9533     if (ElementSize.isZero()) {
9534       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9535           << ElementType;
9536       return false;
9537     }
9538 
9539     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9540     // and produce incorrect results when it overflows. Such behavior
9541     // appears to be non-conforming, but is common, so perhaps we should
9542     // assume the standard intended for such cases to be undefined behavior
9543     // and check for them.
9544 
9545     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9546     // overflow in the final conversion to ptrdiff_t.
9547     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9548     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9549     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9550                     false);
9551     APSInt TrueResult = (LHS - RHS) / ElemSize;
9552     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9553 
9554     if (Result.extend(65) != TrueResult &&
9555         !HandleOverflow(Info, E, TrueResult, E->getType()))
9556       return false;
9557     return Success(Result, E);
9558   }
9559 
9560   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9561 }
9562 
9563 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9564 /// a result as the expression's type.
9565 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9566                                     const UnaryExprOrTypeTraitExpr *E) {
9567   switch(E->getKind()) {
9568   case UETT_PreferredAlignOf:
9569   case UETT_AlignOf: {
9570     if (E->isArgumentType())
9571       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9572                      E);
9573     else
9574       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9575                      E);
9576   }
9577 
9578   case UETT_VecStep: {
9579     QualType Ty = E->getTypeOfArgument();
9580 
9581     if (Ty->isVectorType()) {
9582       unsigned n = Ty->castAs<VectorType>()->getNumElements();
9583 
9584       // The vec_step built-in functions that take a 3-component
9585       // vector return 4. (OpenCL 1.1 spec 6.11.12)
9586       if (n == 3)
9587         n = 4;
9588 
9589       return Success(n, E);
9590     } else
9591       return Success(1, E);
9592   }
9593 
9594   case UETT_SizeOf: {
9595     QualType SrcTy = E->getTypeOfArgument();
9596     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9597     //   the result is the size of the referenced type."
9598     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9599       SrcTy = Ref->getPointeeType();
9600 
9601     CharUnits Sizeof;
9602     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9603       return false;
9604     return Success(Sizeof, E);
9605   }
9606   case UETT_OpenMPRequiredSimdAlign:
9607     assert(E->isArgumentType());
9608     return Success(
9609         Info.Ctx.toCharUnitsFromBits(
9610                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9611             .getQuantity(),
9612         E);
9613   }
9614 
9615   llvm_unreachable("unknown expr/type trait");
9616 }
9617 
9618 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9619   CharUnits Result;
9620   unsigned n = OOE->getNumComponents();
9621   if (n == 0)
9622     return Error(OOE);
9623   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9624   for (unsigned i = 0; i != n; ++i) {
9625     OffsetOfNode ON = OOE->getComponent(i);
9626     switch (ON.getKind()) {
9627     case OffsetOfNode::Array: {
9628       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9629       APSInt IdxResult;
9630       if (!EvaluateInteger(Idx, IdxResult, Info))
9631         return false;
9632       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9633       if (!AT)
9634         return Error(OOE);
9635       CurrentType = AT->getElementType();
9636       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9637       Result += IdxResult.getSExtValue() * ElementSize;
9638       break;
9639     }
9640 
9641     case OffsetOfNode::Field: {
9642       FieldDecl *MemberDecl = ON.getField();
9643       const RecordType *RT = CurrentType->getAs<RecordType>();
9644       if (!RT)
9645         return Error(OOE);
9646       RecordDecl *RD = RT->getDecl();
9647       if (RD->isInvalidDecl()) return false;
9648       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9649       unsigned i = MemberDecl->getFieldIndex();
9650       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9651       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9652       CurrentType = MemberDecl->getType().getNonReferenceType();
9653       break;
9654     }
9655 
9656     case OffsetOfNode::Identifier:
9657       llvm_unreachable("dependent __builtin_offsetof");
9658 
9659     case OffsetOfNode::Base: {
9660       CXXBaseSpecifier *BaseSpec = ON.getBase();
9661       if (BaseSpec->isVirtual())
9662         return Error(OOE);
9663 
9664       // Find the layout of the class whose base we are looking into.
9665       const RecordType *RT = CurrentType->getAs<RecordType>();
9666       if (!RT)
9667         return Error(OOE);
9668       RecordDecl *RD = RT->getDecl();
9669       if (RD->isInvalidDecl()) return false;
9670       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9671 
9672       // Find the base class itself.
9673       CurrentType = BaseSpec->getType();
9674       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9675       if (!BaseRT)
9676         return Error(OOE);
9677 
9678       // Add the offset to the base.
9679       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9680       break;
9681     }
9682     }
9683   }
9684   return Success(Result, OOE);
9685 }
9686 
9687 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9688   switch (E->getOpcode()) {
9689   default:
9690     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9691     // See C99 6.6p3.
9692     return Error(E);
9693   case UO_Extension:
9694     // FIXME: Should extension allow i-c-e extension expressions in its scope?
9695     // If so, we could clear the diagnostic ID.
9696     return Visit(E->getSubExpr());
9697   case UO_Plus:
9698     // The result is just the value.
9699     return Visit(E->getSubExpr());
9700   case UO_Minus: {
9701     if (!Visit(E->getSubExpr()))
9702       return false;
9703     if (!Result.isInt()) return Error(E);
9704     const APSInt &Value = Result.getInt();
9705     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9706         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9707                         E->getType()))
9708       return false;
9709     return Success(-Value, E);
9710   }
9711   case UO_Not: {
9712     if (!Visit(E->getSubExpr()))
9713       return false;
9714     if (!Result.isInt()) return Error(E);
9715     return Success(~Result.getInt(), E);
9716   }
9717   case UO_LNot: {
9718     bool bres;
9719     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9720       return false;
9721     return Success(!bres, E);
9722   }
9723   }
9724 }
9725 
9726 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9727 /// result type is integer.
9728 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9729   const Expr *SubExpr = E->getSubExpr();
9730   QualType DestType = E->getType();
9731   QualType SrcType = SubExpr->getType();
9732 
9733   switch (E->getCastKind()) {
9734   case CK_BaseToDerived:
9735   case CK_DerivedToBase:
9736   case CK_UncheckedDerivedToBase:
9737   case CK_Dynamic:
9738   case CK_ToUnion:
9739   case CK_ArrayToPointerDecay:
9740   case CK_FunctionToPointerDecay:
9741   case CK_NullToPointer:
9742   case CK_NullToMemberPointer:
9743   case CK_BaseToDerivedMemberPointer:
9744   case CK_DerivedToBaseMemberPointer:
9745   case CK_ReinterpretMemberPointer:
9746   case CK_ConstructorConversion:
9747   case CK_IntegralToPointer:
9748   case CK_ToVoid:
9749   case CK_VectorSplat:
9750   case CK_IntegralToFloating:
9751   case CK_FloatingCast:
9752   case CK_CPointerToObjCPointerCast:
9753   case CK_BlockPointerToObjCPointerCast:
9754   case CK_AnyPointerToBlockPointerCast:
9755   case CK_ObjCObjectLValueCast:
9756   case CK_FloatingRealToComplex:
9757   case CK_FloatingComplexToReal:
9758   case CK_FloatingComplexCast:
9759   case CK_FloatingComplexToIntegralComplex:
9760   case CK_IntegralRealToComplex:
9761   case CK_IntegralComplexCast:
9762   case CK_IntegralComplexToFloatingComplex:
9763   case CK_BuiltinFnToFnPtr:
9764   case CK_ZeroToOCLOpaqueType:
9765   case CK_NonAtomicToAtomic:
9766   case CK_AddressSpaceConversion:
9767   case CK_IntToOCLSampler:
9768   case CK_FixedPointCast:
9769     llvm_unreachable("invalid cast kind for integral value");
9770 
9771   case CK_BitCast:
9772   case CK_Dependent:
9773   case CK_LValueBitCast:
9774   case CK_ARCProduceObject:
9775   case CK_ARCConsumeObject:
9776   case CK_ARCReclaimReturnedObject:
9777   case CK_ARCExtendBlockObject:
9778   case CK_CopyAndAutoreleaseBlockObject:
9779     return Error(E);
9780 
9781   case CK_UserDefinedConversion:
9782   case CK_LValueToRValue:
9783   case CK_AtomicToNonAtomic:
9784   case CK_NoOp:
9785     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9786 
9787   case CK_MemberPointerToBoolean:
9788   case CK_PointerToBoolean:
9789   case CK_IntegralToBoolean:
9790   case CK_FloatingToBoolean:
9791   case CK_BooleanToSignedIntegral:
9792   case CK_FloatingComplexToBoolean:
9793   case CK_IntegralComplexToBoolean: {
9794     bool BoolResult;
9795     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9796       return false;
9797     uint64_t IntResult = BoolResult;
9798     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9799       IntResult = (uint64_t)-1;
9800     return Success(IntResult, E);
9801   }
9802 
9803   case CK_FixedPointToBoolean: {
9804     // Unsigned padding does not affect this.
9805     APValue Val;
9806     if (!Evaluate(Val, Info, SubExpr))
9807       return false;
9808     return Success(Val.getFixedPoint().getBoolValue(), E);
9809   }
9810 
9811   case CK_IntegralCast: {
9812     if (!Visit(SubExpr))
9813       return false;
9814 
9815     if (!Result.isInt()) {
9816       // Allow casts of address-of-label differences if they are no-ops
9817       // or narrowing.  (The narrowing case isn't actually guaranteed to
9818       // be constant-evaluatable except in some narrow cases which are hard
9819       // to detect here.  We let it through on the assumption the user knows
9820       // what they are doing.)
9821       if (Result.isAddrLabelDiff())
9822         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9823       // Only allow casts of lvalues if they are lossless.
9824       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9825     }
9826 
9827     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9828                                       Result.getInt()), E);
9829   }
9830 
9831   case CK_PointerToIntegral: {
9832     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9833 
9834     LValue LV;
9835     if (!EvaluatePointer(SubExpr, LV, Info))
9836       return false;
9837 
9838     if (LV.getLValueBase()) {
9839       // Only allow based lvalue casts if they are lossless.
9840       // FIXME: Allow a larger integer size than the pointer size, and allow
9841       // narrowing back down to pointer width in subsequent integral casts.
9842       // FIXME: Check integer type's active bits, not its type size.
9843       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9844         return Error(E);
9845 
9846       LV.Designator.setInvalid();
9847       LV.moveInto(Result);
9848       return true;
9849     }
9850 
9851     uint64_t V;
9852     if (LV.isNullPointer())
9853       V = Info.Ctx.getTargetNullPointerValue(SrcType);
9854     else
9855       V = LV.getLValueOffset().getQuantity();
9856 
9857     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9858     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9859   }
9860 
9861   case CK_IntegralComplexToReal: {
9862     ComplexValue C;
9863     if (!EvaluateComplex(SubExpr, C, Info))
9864       return false;
9865     return Success(C.getComplexIntReal(), E);
9866   }
9867 
9868   case CK_FloatingToIntegral: {
9869     APFloat F(0.0);
9870     if (!EvaluateFloat(SubExpr, F, Info))
9871       return false;
9872 
9873     APSInt Value;
9874     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9875       return false;
9876     return Success(Value, E);
9877   }
9878   }
9879 
9880   llvm_unreachable("unknown cast resulting in integral value");
9881 }
9882 
9883 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9884   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9885     ComplexValue LV;
9886     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9887       return false;
9888     if (!LV.isComplexInt())
9889       return Error(E);
9890     return Success(LV.getComplexIntReal(), E);
9891   }
9892 
9893   return Visit(E->getSubExpr());
9894 }
9895 
9896 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9897   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9898     ComplexValue LV;
9899     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9900       return false;
9901     if (!LV.isComplexInt())
9902       return Error(E);
9903     return Success(LV.getComplexIntImag(), E);
9904   }
9905 
9906   VisitIgnoredValue(E->getSubExpr());
9907   return Success(0, E);
9908 }
9909 
9910 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9911   return Success(E->getPackLength(), E);
9912 }
9913 
9914 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9915   return Success(E->getValue(), E);
9916 }
9917 
9918 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9919   switch (E->getOpcode()) {
9920     default:
9921       // Invalid unary operators
9922       return Error(E);
9923     case UO_Plus:
9924       // The result is just the value.
9925       return Visit(E->getSubExpr());
9926     case UO_Minus: {
9927       if (!Visit(E->getSubExpr())) return false;
9928       if (!Result.isFixedPoint())
9929         return Error(E);
9930       bool Overflowed;
9931       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
9932       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
9933         return false;
9934       return Success(Negated, E);
9935     }
9936     case UO_LNot: {
9937       bool bres;
9938       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9939         return false;
9940       return Success(!bres, E);
9941     }
9942   }
9943 }
9944 
9945 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
9946   const Expr *SubExpr = E->getSubExpr();
9947   QualType DestType = E->getType();
9948   assert(DestType->isFixedPointType() &&
9949          "Expected destination type to be a fixed point type");
9950   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
9951 
9952   switch (E->getCastKind()) {
9953   case CK_FixedPointCast: {
9954     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
9955     if (!EvaluateFixedPoint(SubExpr, Src, Info))
9956       return false;
9957     bool Overflowed;
9958     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
9959     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
9960       return false;
9961     return Success(Result, E);
9962   }
9963   case CK_NoOp:
9964   case CK_LValueToRValue:
9965     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9966   default:
9967     return Error(E);
9968   }
9969 }
9970 
9971 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9972   const Expr *LHS = E->getLHS();
9973   const Expr *RHS = E->getRHS();
9974   FixedPointSemantics ResultFXSema =
9975       Info.Ctx.getFixedPointSemantics(E->getType());
9976 
9977   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
9978   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
9979     return false;
9980   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
9981   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
9982     return false;
9983 
9984   switch (E->getOpcode()) {
9985   case BO_Add: {
9986     bool AddOverflow, ConversionOverflow;
9987     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
9988                               .convert(ResultFXSema, &ConversionOverflow);
9989     if ((AddOverflow || ConversionOverflow) &&
9990         !HandleOverflow(Info, E, Result, E->getType()))
9991       return false;
9992     return Success(Result, E);
9993   }
9994   default:
9995     return false;
9996   }
9997   llvm_unreachable("Should've exited before this");
9998 }
9999 
10000 //===----------------------------------------------------------------------===//
10001 // Float Evaluation
10002 //===----------------------------------------------------------------------===//
10003 
10004 namespace {
10005 class FloatExprEvaluator
10006   : public ExprEvaluatorBase<FloatExprEvaluator> {
10007   APFloat &Result;
10008 public:
10009   FloatExprEvaluator(EvalInfo &info, APFloat &result)
10010     : ExprEvaluatorBaseTy(info), Result(result) {}
10011 
10012   bool Success(const APValue &V, const Expr *e) {
10013     Result = V.getFloat();
10014     return true;
10015   }
10016 
10017   bool ZeroInitialization(const Expr *E) {
10018     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10019     return true;
10020   }
10021 
10022   bool VisitCallExpr(const CallExpr *E);
10023 
10024   bool VisitUnaryOperator(const UnaryOperator *E);
10025   bool VisitBinaryOperator(const BinaryOperator *E);
10026   bool VisitFloatingLiteral(const FloatingLiteral *E);
10027   bool VisitCastExpr(const CastExpr *E);
10028 
10029   bool VisitUnaryReal(const UnaryOperator *E);
10030   bool VisitUnaryImag(const UnaryOperator *E);
10031 
10032   // FIXME: Missing: array subscript of vector, member of vector
10033 };
10034 } // end anonymous namespace
10035 
10036 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
10037   assert(E->isRValue() && E->getType()->isRealFloatingType());
10038   return FloatExprEvaluator(Info, Result).Visit(E);
10039 }
10040 
10041 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
10042                                   QualType ResultTy,
10043                                   const Expr *Arg,
10044                                   bool SNaN,
10045                                   llvm::APFloat &Result) {
10046   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10047   if (!S) return false;
10048 
10049   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10050 
10051   llvm::APInt fill;
10052 
10053   // Treat empty strings as if they were zero.
10054   if (S->getString().empty())
10055     fill = llvm::APInt(32, 0);
10056   else if (S->getString().getAsInteger(0, fill))
10057     return false;
10058 
10059   if (Context.getTargetInfo().isNan2008()) {
10060     if (SNaN)
10061       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10062     else
10063       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10064   } else {
10065     // Prior to IEEE 754-2008, architectures were allowed to choose whether
10066     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10067     // a different encoding to what became a standard in 2008, and for pre-
10068     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10069     // sNaN. This is now known as "legacy NaN" encoding.
10070     if (SNaN)
10071       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10072     else
10073       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10074   }
10075 
10076   return true;
10077 }
10078 
10079 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
10080   switch (E->getBuiltinCallee()) {
10081   default:
10082     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10083 
10084   case Builtin::BI__builtin_huge_val:
10085   case Builtin::BI__builtin_huge_valf:
10086   case Builtin::BI__builtin_huge_vall:
10087   case Builtin::BI__builtin_huge_valf128:
10088   case Builtin::BI__builtin_inf:
10089   case Builtin::BI__builtin_inff:
10090   case Builtin::BI__builtin_infl:
10091   case Builtin::BI__builtin_inff128: {
10092     const llvm::fltSemantics &Sem =
10093       Info.Ctx.getFloatTypeSemantics(E->getType());
10094     Result = llvm::APFloat::getInf(Sem);
10095     return true;
10096   }
10097 
10098   case Builtin::BI__builtin_nans:
10099   case Builtin::BI__builtin_nansf:
10100   case Builtin::BI__builtin_nansl:
10101   case Builtin::BI__builtin_nansf128:
10102     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10103                                true, Result))
10104       return Error(E);
10105     return true;
10106 
10107   case Builtin::BI__builtin_nan:
10108   case Builtin::BI__builtin_nanf:
10109   case Builtin::BI__builtin_nanl:
10110   case Builtin::BI__builtin_nanf128:
10111     // If this is __builtin_nan() turn this into a nan, otherwise we
10112     // can't constant fold it.
10113     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10114                                false, Result))
10115       return Error(E);
10116     return true;
10117 
10118   case Builtin::BI__builtin_fabs:
10119   case Builtin::BI__builtin_fabsf:
10120   case Builtin::BI__builtin_fabsl:
10121   case Builtin::BI__builtin_fabsf128:
10122     if (!EvaluateFloat(E->getArg(0), Result, Info))
10123       return false;
10124 
10125     if (Result.isNegative())
10126       Result.changeSign();
10127     return true;
10128 
10129   // FIXME: Builtin::BI__builtin_powi
10130   // FIXME: Builtin::BI__builtin_powif
10131   // FIXME: Builtin::BI__builtin_powil
10132 
10133   case Builtin::BI__builtin_copysign:
10134   case Builtin::BI__builtin_copysignf:
10135   case Builtin::BI__builtin_copysignl:
10136   case Builtin::BI__builtin_copysignf128: {
10137     APFloat RHS(0.);
10138     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10139         !EvaluateFloat(E->getArg(1), RHS, Info))
10140       return false;
10141     Result.copySign(RHS);
10142     return true;
10143   }
10144   }
10145 }
10146 
10147 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10148   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10149     ComplexValue CV;
10150     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10151       return false;
10152     Result = CV.FloatReal;
10153     return true;
10154   }
10155 
10156   return Visit(E->getSubExpr());
10157 }
10158 
10159 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10160   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10161     ComplexValue CV;
10162     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10163       return false;
10164     Result = CV.FloatImag;
10165     return true;
10166   }
10167 
10168   VisitIgnoredValue(E->getSubExpr());
10169   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10170   Result = llvm::APFloat::getZero(Sem);
10171   return true;
10172 }
10173 
10174 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10175   switch (E->getOpcode()) {
10176   default: return Error(E);
10177   case UO_Plus:
10178     return EvaluateFloat(E->getSubExpr(), Result, Info);
10179   case UO_Minus:
10180     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10181       return false;
10182     Result.changeSign();
10183     return true;
10184   }
10185 }
10186 
10187 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10188   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10189     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10190 
10191   APFloat RHS(0.0);
10192   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
10193   if (!LHSOK && !Info.noteFailure())
10194     return false;
10195   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10196          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
10197 }
10198 
10199 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10200   Result = E->getValue();
10201   return true;
10202 }
10203 
10204 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10205   const Expr* SubExpr = E->getSubExpr();
10206 
10207   switch (E->getCastKind()) {
10208   default:
10209     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10210 
10211   case CK_IntegralToFloating: {
10212     APSInt IntResult;
10213     return EvaluateInteger(SubExpr, IntResult, Info) &&
10214            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10215                                 E->getType(), Result);
10216   }
10217 
10218   case CK_FloatingCast: {
10219     if (!Visit(SubExpr))
10220       return false;
10221     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10222                                   Result);
10223   }
10224 
10225   case CK_FloatingComplexToReal: {
10226     ComplexValue V;
10227     if (!EvaluateComplex(SubExpr, V, Info))
10228       return false;
10229     Result = V.getComplexFloatReal();
10230     return true;
10231   }
10232   }
10233 }
10234 
10235 //===----------------------------------------------------------------------===//
10236 // Complex Evaluation (for float and integer)
10237 //===----------------------------------------------------------------------===//
10238 
10239 namespace {
10240 class ComplexExprEvaluator
10241   : public ExprEvaluatorBase<ComplexExprEvaluator> {
10242   ComplexValue &Result;
10243 
10244 public:
10245   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
10246     : ExprEvaluatorBaseTy(info), Result(Result) {}
10247 
10248   bool Success(const APValue &V, const Expr *e) {
10249     Result.setFrom(V);
10250     return true;
10251   }
10252 
10253   bool ZeroInitialization(const Expr *E);
10254 
10255   //===--------------------------------------------------------------------===//
10256   //                            Visitor Methods
10257   //===--------------------------------------------------------------------===//
10258 
10259   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
10260   bool VisitCastExpr(const CastExpr *E);
10261   bool VisitBinaryOperator(const BinaryOperator *E);
10262   bool VisitUnaryOperator(const UnaryOperator *E);
10263   bool VisitInitListExpr(const InitListExpr *E);
10264 };
10265 } // end anonymous namespace
10266 
10267 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10268                             EvalInfo &Info) {
10269   assert(E->isRValue() && E->getType()->isAnyComplexType());
10270   return ComplexExprEvaluator(Info, Result).Visit(E);
10271 }
10272 
10273 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10274   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10275   if (ElemTy->isRealFloatingType()) {
10276     Result.makeComplexFloat();
10277     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10278     Result.FloatReal = Zero;
10279     Result.FloatImag = Zero;
10280   } else {
10281     Result.makeComplexInt();
10282     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10283     Result.IntReal = Zero;
10284     Result.IntImag = Zero;
10285   }
10286   return true;
10287 }
10288 
10289 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10290   const Expr* SubExpr = E->getSubExpr();
10291 
10292   if (SubExpr->getType()->isRealFloatingType()) {
10293     Result.makeComplexFloat();
10294     APFloat &Imag = Result.FloatImag;
10295     if (!EvaluateFloat(SubExpr, Imag, Info))
10296       return false;
10297 
10298     Result.FloatReal = APFloat(Imag.getSemantics());
10299     return true;
10300   } else {
10301     assert(SubExpr->getType()->isIntegerType() &&
10302            "Unexpected imaginary literal.");
10303 
10304     Result.makeComplexInt();
10305     APSInt &Imag = Result.IntImag;
10306     if (!EvaluateInteger(SubExpr, Imag, Info))
10307       return false;
10308 
10309     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10310     return true;
10311   }
10312 }
10313 
10314 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10315 
10316   switch (E->getCastKind()) {
10317   case CK_BitCast:
10318   case CK_BaseToDerived:
10319   case CK_DerivedToBase:
10320   case CK_UncheckedDerivedToBase:
10321   case CK_Dynamic:
10322   case CK_ToUnion:
10323   case CK_ArrayToPointerDecay:
10324   case CK_FunctionToPointerDecay:
10325   case CK_NullToPointer:
10326   case CK_NullToMemberPointer:
10327   case CK_BaseToDerivedMemberPointer:
10328   case CK_DerivedToBaseMemberPointer:
10329   case CK_MemberPointerToBoolean:
10330   case CK_ReinterpretMemberPointer:
10331   case CK_ConstructorConversion:
10332   case CK_IntegralToPointer:
10333   case CK_PointerToIntegral:
10334   case CK_PointerToBoolean:
10335   case CK_ToVoid:
10336   case CK_VectorSplat:
10337   case CK_IntegralCast:
10338   case CK_BooleanToSignedIntegral:
10339   case CK_IntegralToBoolean:
10340   case CK_IntegralToFloating:
10341   case CK_FloatingToIntegral:
10342   case CK_FloatingToBoolean:
10343   case CK_FloatingCast:
10344   case CK_CPointerToObjCPointerCast:
10345   case CK_BlockPointerToObjCPointerCast:
10346   case CK_AnyPointerToBlockPointerCast:
10347   case CK_ObjCObjectLValueCast:
10348   case CK_FloatingComplexToReal:
10349   case CK_FloatingComplexToBoolean:
10350   case CK_IntegralComplexToReal:
10351   case CK_IntegralComplexToBoolean:
10352   case CK_ARCProduceObject:
10353   case CK_ARCConsumeObject:
10354   case CK_ARCReclaimReturnedObject:
10355   case CK_ARCExtendBlockObject:
10356   case CK_CopyAndAutoreleaseBlockObject:
10357   case CK_BuiltinFnToFnPtr:
10358   case CK_ZeroToOCLOpaqueType:
10359   case CK_NonAtomicToAtomic:
10360   case CK_AddressSpaceConversion:
10361   case CK_IntToOCLSampler:
10362   case CK_FixedPointCast:
10363   case CK_FixedPointToBoolean:
10364     llvm_unreachable("invalid cast kind for complex value");
10365 
10366   case CK_LValueToRValue:
10367   case CK_AtomicToNonAtomic:
10368   case CK_NoOp:
10369     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10370 
10371   case CK_Dependent:
10372   case CK_LValueBitCast:
10373   case CK_UserDefinedConversion:
10374     return Error(E);
10375 
10376   case CK_FloatingRealToComplex: {
10377     APFloat &Real = Result.FloatReal;
10378     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
10379       return false;
10380 
10381     Result.makeComplexFloat();
10382     Result.FloatImag = APFloat(Real.getSemantics());
10383     return true;
10384   }
10385 
10386   case CK_FloatingComplexCast: {
10387     if (!Visit(E->getSubExpr()))
10388       return false;
10389 
10390     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10391     QualType From
10392       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10393 
10394     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10395            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
10396   }
10397 
10398   case CK_FloatingComplexToIntegralComplex: {
10399     if (!Visit(E->getSubExpr()))
10400       return false;
10401 
10402     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10403     QualType From
10404       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10405     Result.makeComplexInt();
10406     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10407                                 To, Result.IntReal) &&
10408            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10409                                 To, Result.IntImag);
10410   }
10411 
10412   case CK_IntegralRealToComplex: {
10413     APSInt &Real = Result.IntReal;
10414     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10415       return false;
10416 
10417     Result.makeComplexInt();
10418     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10419     return true;
10420   }
10421 
10422   case CK_IntegralComplexCast: {
10423     if (!Visit(E->getSubExpr()))
10424       return false;
10425 
10426     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10427     QualType From
10428       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10429 
10430     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10431     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10432     return true;
10433   }
10434 
10435   case CK_IntegralComplexToFloatingComplex: {
10436     if (!Visit(E->getSubExpr()))
10437       return false;
10438 
10439     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10440     QualType From
10441       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10442     Result.makeComplexFloat();
10443     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10444                                 To, Result.FloatReal) &&
10445            HandleIntToFloatCast(Info, E, From, Result.IntImag,
10446                                 To, Result.FloatImag);
10447   }
10448   }
10449 
10450   llvm_unreachable("unknown cast resulting in complex value");
10451 }
10452 
10453 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10454   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10455     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10456 
10457   // Track whether the LHS or RHS is real at the type system level. When this is
10458   // the case we can simplify our evaluation strategy.
10459   bool LHSReal = false, RHSReal = false;
10460 
10461   bool LHSOK;
10462   if (E->getLHS()->getType()->isRealFloatingType()) {
10463     LHSReal = true;
10464     APFloat &Real = Result.FloatReal;
10465     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10466     if (LHSOK) {
10467       Result.makeComplexFloat();
10468       Result.FloatImag = APFloat(Real.getSemantics());
10469     }
10470   } else {
10471     LHSOK = Visit(E->getLHS());
10472   }
10473   if (!LHSOK && !Info.noteFailure())
10474     return false;
10475 
10476   ComplexValue RHS;
10477   if (E->getRHS()->getType()->isRealFloatingType()) {
10478     RHSReal = true;
10479     APFloat &Real = RHS.FloatReal;
10480     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10481       return false;
10482     RHS.makeComplexFloat();
10483     RHS.FloatImag = APFloat(Real.getSemantics());
10484   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10485     return false;
10486 
10487   assert(!(LHSReal && RHSReal) &&
10488          "Cannot have both operands of a complex operation be real.");
10489   switch (E->getOpcode()) {
10490   default: return Error(E);
10491   case BO_Add:
10492     if (Result.isComplexFloat()) {
10493       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10494                                        APFloat::rmNearestTiesToEven);
10495       if (LHSReal)
10496         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10497       else if (!RHSReal)
10498         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10499                                          APFloat::rmNearestTiesToEven);
10500     } else {
10501       Result.getComplexIntReal() += RHS.getComplexIntReal();
10502       Result.getComplexIntImag() += RHS.getComplexIntImag();
10503     }
10504     break;
10505   case BO_Sub:
10506     if (Result.isComplexFloat()) {
10507       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10508                                             APFloat::rmNearestTiesToEven);
10509       if (LHSReal) {
10510         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10511         Result.getComplexFloatImag().changeSign();
10512       } else if (!RHSReal) {
10513         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10514                                               APFloat::rmNearestTiesToEven);
10515       }
10516     } else {
10517       Result.getComplexIntReal() -= RHS.getComplexIntReal();
10518       Result.getComplexIntImag() -= RHS.getComplexIntImag();
10519     }
10520     break;
10521   case BO_Mul:
10522     if (Result.isComplexFloat()) {
10523       // This is an implementation of complex multiplication according to the
10524       // constraints laid out in C11 Annex G. The implementation uses the
10525       // following naming scheme:
10526       //   (a + ib) * (c + id)
10527       ComplexValue LHS = Result;
10528       APFloat &A = LHS.getComplexFloatReal();
10529       APFloat &B = LHS.getComplexFloatImag();
10530       APFloat &C = RHS.getComplexFloatReal();
10531       APFloat &D = RHS.getComplexFloatImag();
10532       APFloat &ResR = Result.getComplexFloatReal();
10533       APFloat &ResI = Result.getComplexFloatImag();
10534       if (LHSReal) {
10535         assert(!RHSReal && "Cannot have two real operands for a complex op!");
10536         ResR = A * C;
10537         ResI = A * D;
10538       } else if (RHSReal) {
10539         ResR = C * A;
10540         ResI = C * B;
10541       } else {
10542         // In the fully general case, we need to handle NaNs and infinities
10543         // robustly.
10544         APFloat AC = A * C;
10545         APFloat BD = B * D;
10546         APFloat AD = A * D;
10547         APFloat BC = B * C;
10548         ResR = AC - BD;
10549         ResI = AD + BC;
10550         if (ResR.isNaN() && ResI.isNaN()) {
10551           bool Recalc = false;
10552           if (A.isInfinity() || B.isInfinity()) {
10553             A = APFloat::copySign(
10554                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10555             B = APFloat::copySign(
10556                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10557             if (C.isNaN())
10558               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10559             if (D.isNaN())
10560               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10561             Recalc = true;
10562           }
10563           if (C.isInfinity() || D.isInfinity()) {
10564             C = APFloat::copySign(
10565                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10566             D = APFloat::copySign(
10567                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10568             if (A.isNaN())
10569               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10570             if (B.isNaN())
10571               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10572             Recalc = true;
10573           }
10574           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10575                           AD.isInfinity() || BC.isInfinity())) {
10576             if (A.isNaN())
10577               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10578             if (B.isNaN())
10579               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10580             if (C.isNaN())
10581               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10582             if (D.isNaN())
10583               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10584             Recalc = true;
10585           }
10586           if (Recalc) {
10587             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10588             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10589           }
10590         }
10591       }
10592     } else {
10593       ComplexValue LHS = Result;
10594       Result.getComplexIntReal() =
10595         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10596          LHS.getComplexIntImag() * RHS.getComplexIntImag());
10597       Result.getComplexIntImag() =
10598         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10599          LHS.getComplexIntImag() * RHS.getComplexIntReal());
10600     }
10601     break;
10602   case BO_Div:
10603     if (Result.isComplexFloat()) {
10604       // This is an implementation of complex division according to the
10605       // constraints laid out in C11 Annex G. The implementation uses the
10606       // following naming scheme:
10607       //   (a + ib) / (c + id)
10608       ComplexValue LHS = Result;
10609       APFloat &A = LHS.getComplexFloatReal();
10610       APFloat &B = LHS.getComplexFloatImag();
10611       APFloat &C = RHS.getComplexFloatReal();
10612       APFloat &D = RHS.getComplexFloatImag();
10613       APFloat &ResR = Result.getComplexFloatReal();
10614       APFloat &ResI = Result.getComplexFloatImag();
10615       if (RHSReal) {
10616         ResR = A / C;
10617         ResI = B / C;
10618       } else {
10619         if (LHSReal) {
10620           // No real optimizations we can do here, stub out with zero.
10621           B = APFloat::getZero(A.getSemantics());
10622         }
10623         int DenomLogB = 0;
10624         APFloat MaxCD = maxnum(abs(C), abs(D));
10625         if (MaxCD.isFinite()) {
10626           DenomLogB = ilogb(MaxCD);
10627           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10628           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10629         }
10630         APFloat Denom = C * C + D * D;
10631         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10632                       APFloat::rmNearestTiesToEven);
10633         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10634                       APFloat::rmNearestTiesToEven);
10635         if (ResR.isNaN() && ResI.isNaN()) {
10636           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10637             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10638             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10639           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10640                      D.isFinite()) {
10641             A = APFloat::copySign(
10642                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10643             B = APFloat::copySign(
10644                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10645             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10646             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10647           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10648             C = APFloat::copySign(
10649                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10650             D = APFloat::copySign(
10651                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10652             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10653             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10654           }
10655         }
10656       }
10657     } else {
10658       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10659         return Error(E, diag::note_expr_divide_by_zero);
10660 
10661       ComplexValue LHS = Result;
10662       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10663         RHS.getComplexIntImag() * RHS.getComplexIntImag();
10664       Result.getComplexIntReal() =
10665         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10666          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10667       Result.getComplexIntImag() =
10668         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10669          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10670     }
10671     break;
10672   }
10673 
10674   return true;
10675 }
10676 
10677 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10678   // Get the operand value into 'Result'.
10679   if (!Visit(E->getSubExpr()))
10680     return false;
10681 
10682   switch (E->getOpcode()) {
10683   default:
10684     return Error(E);
10685   case UO_Extension:
10686     return true;
10687   case UO_Plus:
10688     // The result is always just the subexpr.
10689     return true;
10690   case UO_Minus:
10691     if (Result.isComplexFloat()) {
10692       Result.getComplexFloatReal().changeSign();
10693       Result.getComplexFloatImag().changeSign();
10694     }
10695     else {
10696       Result.getComplexIntReal() = -Result.getComplexIntReal();
10697       Result.getComplexIntImag() = -Result.getComplexIntImag();
10698     }
10699     return true;
10700   case UO_Not:
10701     if (Result.isComplexFloat())
10702       Result.getComplexFloatImag().changeSign();
10703     else
10704       Result.getComplexIntImag() = -Result.getComplexIntImag();
10705     return true;
10706   }
10707 }
10708 
10709 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10710   if (E->getNumInits() == 2) {
10711     if (E->getType()->isComplexType()) {
10712       Result.makeComplexFloat();
10713       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10714         return false;
10715       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10716         return false;
10717     } else {
10718       Result.makeComplexInt();
10719       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10720         return false;
10721       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10722         return false;
10723     }
10724     return true;
10725   }
10726   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10727 }
10728 
10729 //===----------------------------------------------------------------------===//
10730 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10731 // implicit conversion.
10732 //===----------------------------------------------------------------------===//
10733 
10734 namespace {
10735 class AtomicExprEvaluator :
10736     public ExprEvaluatorBase<AtomicExprEvaluator> {
10737   const LValue *This;
10738   APValue &Result;
10739 public:
10740   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10741       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10742 
10743   bool Success(const APValue &V, const Expr *E) {
10744     Result = V;
10745     return true;
10746   }
10747 
10748   bool ZeroInitialization(const Expr *E) {
10749     ImplicitValueInitExpr VIE(
10750         E->getType()->castAs<AtomicType>()->getValueType());
10751     // For atomic-qualified class (and array) types in C++, initialize the
10752     // _Atomic-wrapped subobject directly, in-place.
10753     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10754                 : Evaluate(Result, Info, &VIE);
10755   }
10756 
10757   bool VisitCastExpr(const CastExpr *E) {
10758     switch (E->getCastKind()) {
10759     default:
10760       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10761     case CK_NonAtomicToAtomic:
10762       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10763                   : Evaluate(Result, Info, E->getSubExpr());
10764     }
10765   }
10766 };
10767 } // end anonymous namespace
10768 
10769 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10770                            EvalInfo &Info) {
10771   assert(E->isRValue() && E->getType()->isAtomicType());
10772   return AtomicExprEvaluator(Info, This, Result).Visit(E);
10773 }
10774 
10775 //===----------------------------------------------------------------------===//
10776 // Void expression evaluation, primarily for a cast to void on the LHS of a
10777 // comma operator
10778 //===----------------------------------------------------------------------===//
10779 
10780 namespace {
10781 class VoidExprEvaluator
10782   : public ExprEvaluatorBase<VoidExprEvaluator> {
10783 public:
10784   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10785 
10786   bool Success(const APValue &V, const Expr *e) { return true; }
10787 
10788   bool ZeroInitialization(const Expr *E) { return true; }
10789 
10790   bool VisitCastExpr(const CastExpr *E) {
10791     switch (E->getCastKind()) {
10792     default:
10793       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10794     case CK_ToVoid:
10795       VisitIgnoredValue(E->getSubExpr());
10796       return true;
10797     }
10798   }
10799 
10800   bool VisitCallExpr(const CallExpr *E) {
10801     switch (E->getBuiltinCallee()) {
10802     default:
10803       return ExprEvaluatorBaseTy::VisitCallExpr(E);
10804     case Builtin::BI__assume:
10805     case Builtin::BI__builtin_assume:
10806       // The argument is not evaluated!
10807       return true;
10808     }
10809   }
10810 };
10811 } // end anonymous namespace
10812 
10813 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10814   assert(E->isRValue() && E->getType()->isVoidType());
10815   return VoidExprEvaluator(Info).Visit(E);
10816 }
10817 
10818 //===----------------------------------------------------------------------===//
10819 // Top level Expr::EvaluateAsRValue method.
10820 //===----------------------------------------------------------------------===//
10821 
10822 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10823   // In C, function designators are not lvalues, but we evaluate them as if they
10824   // are.
10825   QualType T = E->getType();
10826   if (E->isGLValue() || T->isFunctionType()) {
10827     LValue LV;
10828     if (!EvaluateLValue(E, LV, Info))
10829       return false;
10830     LV.moveInto(Result);
10831   } else if (T->isVectorType()) {
10832     if (!EvaluateVector(E, Result, Info))
10833       return false;
10834   } else if (T->isIntegralOrEnumerationType()) {
10835     if (!IntExprEvaluator(Info, Result).Visit(E))
10836       return false;
10837   } else if (T->hasPointerRepresentation()) {
10838     LValue LV;
10839     if (!EvaluatePointer(E, LV, Info))
10840       return false;
10841     LV.moveInto(Result);
10842   } else if (T->isRealFloatingType()) {
10843     llvm::APFloat F(0.0);
10844     if (!EvaluateFloat(E, F, Info))
10845       return false;
10846     Result = APValue(F);
10847   } else if (T->isAnyComplexType()) {
10848     ComplexValue C;
10849     if (!EvaluateComplex(E, C, Info))
10850       return false;
10851     C.moveInto(Result);
10852   } else if (T->isFixedPointType()) {
10853     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10854   } else if (T->isMemberPointerType()) {
10855     MemberPtr P;
10856     if (!EvaluateMemberPointer(E, P, Info))
10857       return false;
10858     P.moveInto(Result);
10859     return true;
10860   } else if (T->isArrayType()) {
10861     LValue LV;
10862     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10863     if (!EvaluateArray(E, LV, Value, Info))
10864       return false;
10865     Result = Value;
10866   } else if (T->isRecordType()) {
10867     LValue LV;
10868     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10869     if (!EvaluateRecord(E, LV, Value, Info))
10870       return false;
10871     Result = Value;
10872   } else if (T->isVoidType()) {
10873     if (!Info.getLangOpts().CPlusPlus11)
10874       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10875         << E->getType();
10876     if (!EvaluateVoid(E, Info))
10877       return false;
10878   } else if (T->isAtomicType()) {
10879     QualType Unqual = T.getAtomicUnqualifiedType();
10880     if (Unqual->isArrayType() || Unqual->isRecordType()) {
10881       LValue LV;
10882       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10883       if (!EvaluateAtomic(E, &LV, Value, Info))
10884         return false;
10885     } else {
10886       if (!EvaluateAtomic(E, nullptr, Result, Info))
10887         return false;
10888     }
10889   } else if (Info.getLangOpts().CPlusPlus11) {
10890     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10891     return false;
10892   } else {
10893     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10894     return false;
10895   }
10896 
10897   return true;
10898 }
10899 
10900 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10901 /// cases, the in-place evaluation is essential, since later initializers for
10902 /// an object can indirectly refer to subobjects which were initialized earlier.
10903 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10904                             const Expr *E, bool AllowNonLiteralTypes) {
10905   assert(!E->isValueDependent());
10906 
10907   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10908     return false;
10909 
10910   if (E->isRValue()) {
10911     // Evaluate arrays and record types in-place, so that later initializers can
10912     // refer to earlier-initialized members of the object.
10913     QualType T = E->getType();
10914     if (T->isArrayType())
10915       return EvaluateArray(E, This, Result, Info);
10916     else if (T->isRecordType())
10917       return EvaluateRecord(E, This, Result, Info);
10918     else if (T->isAtomicType()) {
10919       QualType Unqual = T.getAtomicUnqualifiedType();
10920       if (Unqual->isArrayType() || Unqual->isRecordType())
10921         return EvaluateAtomic(E, &This, Result, Info);
10922     }
10923   }
10924 
10925   // For any other type, in-place evaluation is unimportant.
10926   return Evaluate(Result, Info, E);
10927 }
10928 
10929 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10930 /// lvalue-to-rvalue cast if it is an lvalue.
10931 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10932   if (E->getType().isNull())
10933     return false;
10934 
10935   if (!CheckLiteralType(Info, E))
10936     return false;
10937 
10938   if (!::Evaluate(Result, Info, E))
10939     return false;
10940 
10941   if (E->isGLValue()) {
10942     LValue LV;
10943     LV.setFrom(Info.Ctx, Result);
10944     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10945       return false;
10946   }
10947 
10948   // Check this core constant expression is a constant expression.
10949   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10950 }
10951 
10952 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10953                                  const ASTContext &Ctx, bool &IsConst) {
10954   // Fast-path evaluations of integer literals, since we sometimes see files
10955   // containing vast quantities of these.
10956   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10957     Result.Val = APValue(APSInt(L->getValue(),
10958                                 L->getType()->isUnsignedIntegerType()));
10959     IsConst = true;
10960     return true;
10961   }
10962 
10963   // This case should be rare, but we need to check it before we check on
10964   // the type below.
10965   if (Exp->getType().isNull()) {
10966     IsConst = false;
10967     return true;
10968   }
10969 
10970   // FIXME: Evaluating values of large array and record types can cause
10971   // performance problems. Only do so in C++11 for now.
10972   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10973                           Exp->getType()->isRecordType()) &&
10974       !Ctx.getLangOpts().CPlusPlus11) {
10975     IsConst = false;
10976     return true;
10977   }
10978   return false;
10979 }
10980 
10981 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10982                                       Expr::SideEffectsKind SEK) {
10983   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10984          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10985 }
10986 
10987 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10988                              const ASTContext &Ctx, EvalInfo &Info) {
10989   bool IsConst;
10990   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10991     return IsConst;
10992 
10993   return EvaluateAsRValue(Info, E, Result.Val);
10994 }
10995 
10996 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10997                           const ASTContext &Ctx,
10998                           Expr::SideEffectsKind AllowSideEffects,
10999                           EvalInfo &Info) {
11000   if (!E->getType()->isIntegralOrEnumerationType())
11001     return false;
11002 
11003   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11004       !ExprResult.Val.isInt() ||
11005       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11006     return false;
11007 
11008   return true;
11009 }
11010 
11011 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11012                                  const ASTContext &Ctx,
11013                                  Expr::SideEffectsKind AllowSideEffects,
11014                                  EvalInfo &Info) {
11015   if (!E->getType()->isFixedPointType())
11016     return false;
11017 
11018   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11019     return false;
11020 
11021   if (!ExprResult.Val.isFixedPoint() ||
11022       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11023     return false;
11024 
11025   return true;
11026 }
11027 
11028 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
11029 /// any crazy technique (that has nothing to do with language standards) that
11030 /// we want to.  If this function returns true, it returns the folded constant
11031 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11032 /// will be applied to the result.
11033 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11034                             bool InConstantContext) const {
11035   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11036   Info.InConstantContext = InConstantContext;
11037   return ::EvaluateAsRValue(this, Result, Ctx, Info);
11038 }
11039 
11040 bool Expr::EvaluateAsBooleanCondition(bool &Result,
11041                                       const ASTContext &Ctx) const {
11042   EvalResult Scratch;
11043   return EvaluateAsRValue(Scratch, Ctx) &&
11044          HandleConversionToBool(Scratch.Val, Result);
11045 }
11046 
11047 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
11048                          SideEffectsKind AllowSideEffects) const {
11049   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11050   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
11051 }
11052 
11053 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11054                                 SideEffectsKind AllowSideEffects) const {
11055   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11056   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11057 }
11058 
11059 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11060                            SideEffectsKind AllowSideEffects) const {
11061   if (!getType()->isRealFloatingType())
11062     return false;
11063 
11064   EvalResult ExprResult;
11065   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
11066       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11067     return false;
11068 
11069   Result = ExprResult.Val.getFloat();
11070   return true;
11071 }
11072 
11073 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
11074   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
11075 
11076   LValue LV;
11077   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11078       !CheckLValueConstantExpression(Info, getExprLoc(),
11079                                      Ctx.getLValueReferenceType(getType()), LV,
11080                                      Expr::EvaluateForCodeGen))
11081     return false;
11082 
11083   LV.moveInto(Result.Val);
11084   return true;
11085 }
11086 
11087 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11088                                   const ASTContext &Ctx) const {
11089   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11090   EvalInfo Info(Ctx, Result, EM);
11091   if (!::Evaluate(Result.Val, Info, this))
11092     return false;
11093 
11094   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11095                                  Usage);
11096 }
11097 
11098 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11099                                  const VarDecl *VD,
11100                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
11101   // FIXME: Evaluating initializers for large array and record types can cause
11102   // performance problems. Only do so in C++11 for now.
11103   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
11104       !Ctx.getLangOpts().CPlusPlus11)
11105     return false;
11106 
11107   Expr::EvalStatus EStatus;
11108   EStatus.Diag = &Notes;
11109 
11110   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11111                                       ? EvalInfo::EM_ConstantExpression
11112                                       : EvalInfo::EM_ConstantFold);
11113   InitInfo.setEvaluatingDecl(VD, Value);
11114   InitInfo.InConstantContext = true;
11115 
11116   LValue LVal;
11117   LVal.set(VD);
11118 
11119   // C++11 [basic.start.init]p2:
11120   //  Variables with static storage duration or thread storage duration shall be
11121   //  zero-initialized before any other initialization takes place.
11122   // This behavior is not present in C.
11123   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
11124       !VD->getType()->isReferenceType()) {
11125     ImplicitValueInitExpr VIE(VD->getType());
11126     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
11127                          /*AllowNonLiteralTypes=*/true))
11128       return false;
11129   }
11130 
11131   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11132                        /*AllowNonLiteralTypes=*/true) ||
11133       EStatus.HasSideEffects)
11134     return false;
11135 
11136   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11137                                  Value);
11138 }
11139 
11140 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11141 /// constant folded, but discard the result.
11142 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
11143   EvalResult Result;
11144   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
11145          !hasUnacceptableSideEffect(Result, SEK);
11146 }
11147 
11148 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
11149                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11150   EvalResult EVResult;
11151   EVResult.Diag = Diag;
11152   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11153   Info.InConstantContext = true;
11154 
11155   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
11156   (void)Result;
11157   assert(Result && "Could not evaluate expression");
11158   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11159 
11160   return EVResult.Val.getInt();
11161 }
11162 
11163 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11164     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11165   EvalResult EVResult;
11166   EVResult.Diag = Diag;
11167   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11168   Info.InConstantContext = true;
11169 
11170   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
11171   (void)Result;
11172   assert(Result && "Could not evaluate expression");
11173   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11174 
11175   return EVResult.Val.getInt();
11176 }
11177 
11178 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
11179   bool IsConst;
11180   EvalResult EVResult;
11181   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11182     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11183     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
11184   }
11185 }
11186 
11187 bool Expr::EvalResult::isGlobalLValue() const {
11188   assert(Val.isLValue());
11189   return IsGlobalLValue(Val.getLValueBase());
11190 }
11191 
11192 
11193 /// isIntegerConstantExpr - this recursive routine will test if an expression is
11194 /// an integer constant expression.
11195 
11196 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11197 /// comma, etc
11198 
11199 // CheckICE - This function does the fundamental ICE checking: the returned
11200 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11201 // and a (possibly null) SourceLocation indicating the location of the problem.
11202 //
11203 // Note that to reduce code duplication, this helper does no evaluation
11204 // itself; the caller checks whether the expression is evaluatable, and
11205 // in the rare cases where CheckICE actually cares about the evaluated
11206 // value, it calls into Evaluate.
11207 
11208 namespace {
11209 
11210 enum ICEKind {
11211   /// This expression is an ICE.
11212   IK_ICE,
11213   /// This expression is not an ICE, but if it isn't evaluated, it's
11214   /// a legal subexpression for an ICE. This return value is used to handle
11215   /// the comma operator in C99 mode, and non-constant subexpressions.
11216   IK_ICEIfUnevaluated,
11217   /// This expression is not an ICE, and is not a legal subexpression for one.
11218   IK_NotICE
11219 };
11220 
11221 struct ICEDiag {
11222   ICEKind Kind;
11223   SourceLocation Loc;
11224 
11225   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
11226 };
11227 
11228 }
11229 
11230 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11231 
11232 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
11233 
11234 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
11235   Expr::EvalResult EVResult;
11236   Expr::EvalStatus Status;
11237   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11238 
11239   Info.InConstantContext = true;
11240   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
11241       !EVResult.Val.isInt())
11242     return ICEDiag(IK_NotICE, E->getBeginLoc());
11243 
11244   return NoDiag();
11245 }
11246 
11247 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
11248   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
11249   if (!E->getType()->isIntegralOrEnumerationType())
11250     return ICEDiag(IK_NotICE, E->getBeginLoc());
11251 
11252   switch (E->getStmtClass()) {
11253 #define ABSTRACT_STMT(Node)
11254 #define STMT(Node, Base) case Expr::Node##Class:
11255 #define EXPR(Node, Base)
11256 #include "clang/AST/StmtNodes.inc"
11257   case Expr::PredefinedExprClass:
11258   case Expr::FloatingLiteralClass:
11259   case Expr::ImaginaryLiteralClass:
11260   case Expr::StringLiteralClass:
11261   case Expr::ArraySubscriptExprClass:
11262   case Expr::OMPArraySectionExprClass:
11263   case Expr::MemberExprClass:
11264   case Expr::CompoundAssignOperatorClass:
11265   case Expr::CompoundLiteralExprClass:
11266   case Expr::ExtVectorElementExprClass:
11267   case Expr::DesignatedInitExprClass:
11268   case Expr::ArrayInitLoopExprClass:
11269   case Expr::ArrayInitIndexExprClass:
11270   case Expr::NoInitExprClass:
11271   case Expr::DesignatedInitUpdateExprClass:
11272   case Expr::ImplicitValueInitExprClass:
11273   case Expr::ParenListExprClass:
11274   case Expr::VAArgExprClass:
11275   case Expr::AddrLabelExprClass:
11276   case Expr::StmtExprClass:
11277   case Expr::CXXMemberCallExprClass:
11278   case Expr::CUDAKernelCallExprClass:
11279   case Expr::CXXDynamicCastExprClass:
11280   case Expr::CXXTypeidExprClass:
11281   case Expr::CXXUuidofExprClass:
11282   case Expr::MSPropertyRefExprClass:
11283   case Expr::MSPropertySubscriptExprClass:
11284   case Expr::CXXNullPtrLiteralExprClass:
11285   case Expr::UserDefinedLiteralClass:
11286   case Expr::CXXThisExprClass:
11287   case Expr::CXXThrowExprClass:
11288   case Expr::CXXNewExprClass:
11289   case Expr::CXXDeleteExprClass:
11290   case Expr::CXXPseudoDestructorExprClass:
11291   case Expr::UnresolvedLookupExprClass:
11292   case Expr::TypoExprClass:
11293   case Expr::DependentScopeDeclRefExprClass:
11294   case Expr::CXXConstructExprClass:
11295   case Expr::CXXInheritedCtorInitExprClass:
11296   case Expr::CXXStdInitializerListExprClass:
11297   case Expr::CXXBindTemporaryExprClass:
11298   case Expr::ExprWithCleanupsClass:
11299   case Expr::CXXTemporaryObjectExprClass:
11300   case Expr::CXXUnresolvedConstructExprClass:
11301   case Expr::CXXDependentScopeMemberExprClass:
11302   case Expr::UnresolvedMemberExprClass:
11303   case Expr::ObjCStringLiteralClass:
11304   case Expr::ObjCBoxedExprClass:
11305   case Expr::ObjCArrayLiteralClass:
11306   case Expr::ObjCDictionaryLiteralClass:
11307   case Expr::ObjCEncodeExprClass:
11308   case Expr::ObjCMessageExprClass:
11309   case Expr::ObjCSelectorExprClass:
11310   case Expr::ObjCProtocolExprClass:
11311   case Expr::ObjCIvarRefExprClass:
11312   case Expr::ObjCPropertyRefExprClass:
11313   case Expr::ObjCSubscriptRefExprClass:
11314   case Expr::ObjCIsaExprClass:
11315   case Expr::ObjCAvailabilityCheckExprClass:
11316   case Expr::ShuffleVectorExprClass:
11317   case Expr::ConvertVectorExprClass:
11318   case Expr::BlockExprClass:
11319   case Expr::NoStmtClass:
11320   case Expr::OpaqueValueExprClass:
11321   case Expr::PackExpansionExprClass:
11322   case Expr::SubstNonTypeTemplateParmPackExprClass:
11323   case Expr::FunctionParmPackExprClass:
11324   case Expr::AsTypeExprClass:
11325   case Expr::ObjCIndirectCopyRestoreExprClass:
11326   case Expr::MaterializeTemporaryExprClass:
11327   case Expr::PseudoObjectExprClass:
11328   case Expr::AtomicExprClass:
11329   case Expr::LambdaExprClass:
11330   case Expr::CXXFoldExprClass:
11331   case Expr::CoawaitExprClass:
11332   case Expr::DependentCoawaitExprClass:
11333   case Expr::CoyieldExprClass:
11334     return ICEDiag(IK_NotICE, E->getBeginLoc());
11335 
11336   case Expr::InitListExprClass: {
11337     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11338     // form "T x = { a };" is equivalent to "T x = a;".
11339     // Unless we're initializing a reference, T is a scalar as it is known to be
11340     // of integral or enumeration type.
11341     if (E->isRValue())
11342       if (cast<InitListExpr>(E)->getNumInits() == 1)
11343         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
11344     return ICEDiag(IK_NotICE, E->getBeginLoc());
11345   }
11346 
11347   case Expr::SizeOfPackExprClass:
11348   case Expr::GNUNullExprClass:
11349     // GCC considers the GNU __null value to be an integral constant expression.
11350     return NoDiag();
11351 
11352   case Expr::SubstNonTypeTemplateParmExprClass:
11353     return
11354       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11355 
11356   case Expr::ConstantExprClass:
11357     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11358 
11359   case Expr::ParenExprClass:
11360     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
11361   case Expr::GenericSelectionExprClass:
11362     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
11363   case Expr::IntegerLiteralClass:
11364   case Expr::FixedPointLiteralClass:
11365   case Expr::CharacterLiteralClass:
11366   case Expr::ObjCBoolLiteralExprClass:
11367   case Expr::CXXBoolLiteralExprClass:
11368   case Expr::CXXScalarValueInitExprClass:
11369   case Expr::TypeTraitExprClass:
11370   case Expr::ArrayTypeTraitExprClass:
11371   case Expr::ExpressionTraitExprClass:
11372   case Expr::CXXNoexceptExprClass:
11373     return NoDiag();
11374   case Expr::CallExprClass:
11375   case Expr::CXXOperatorCallExprClass: {
11376     // C99 6.6/3 allows function calls within unevaluated subexpressions of
11377     // constant expressions, but they can never be ICEs because an ICE cannot
11378     // contain an operand of (pointer to) function type.
11379     const CallExpr *CE = cast<CallExpr>(E);
11380     if (CE->getBuiltinCallee())
11381       return CheckEvalInICE(E, Ctx);
11382     return ICEDiag(IK_NotICE, E->getBeginLoc());
11383   }
11384   case Expr::DeclRefExprClass: {
11385     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11386       return NoDiag();
11387     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
11388     if (Ctx.getLangOpts().CPlusPlus &&
11389         D && IsConstNonVolatile(D->getType())) {
11390       // Parameter variables are never constants.  Without this check,
11391       // getAnyInitializer() can find a default argument, which leads
11392       // to chaos.
11393       if (isa<ParmVarDecl>(D))
11394         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11395 
11396       // C++ 7.1.5.1p2
11397       //   A variable of non-volatile const-qualified integral or enumeration
11398       //   type initialized by an ICE can be used in ICEs.
11399       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
11400         if (!Dcl->getType()->isIntegralOrEnumerationType())
11401           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11402 
11403         const VarDecl *VD;
11404         // Look for a declaration of this variable that has an initializer, and
11405         // check whether it is an ICE.
11406         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11407           return NoDiag();
11408         else
11409           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11410       }
11411     }
11412     return ICEDiag(IK_NotICE, E->getBeginLoc());
11413   }
11414   case Expr::UnaryOperatorClass: {
11415     const UnaryOperator *Exp = cast<UnaryOperator>(E);
11416     switch (Exp->getOpcode()) {
11417     case UO_PostInc:
11418     case UO_PostDec:
11419     case UO_PreInc:
11420     case UO_PreDec:
11421     case UO_AddrOf:
11422     case UO_Deref:
11423     case UO_Coawait:
11424       // C99 6.6/3 allows increment and decrement within unevaluated
11425       // subexpressions of constant expressions, but they can never be ICEs
11426       // because an ICE cannot contain an lvalue operand.
11427       return ICEDiag(IK_NotICE, E->getBeginLoc());
11428     case UO_Extension:
11429     case UO_LNot:
11430     case UO_Plus:
11431     case UO_Minus:
11432     case UO_Not:
11433     case UO_Real:
11434     case UO_Imag:
11435       return CheckICE(Exp->getSubExpr(), Ctx);
11436     }
11437     llvm_unreachable("invalid unary operator class");
11438   }
11439   case Expr::OffsetOfExprClass: {
11440     // Note that per C99, offsetof must be an ICE. And AFAIK, using
11441     // EvaluateAsRValue matches the proposed gcc behavior for cases like
11442     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
11443     // compliance: we should warn earlier for offsetof expressions with
11444     // array subscripts that aren't ICEs, and if the array subscripts
11445     // are ICEs, the value of the offsetof must be an integer constant.
11446     return CheckEvalInICE(E, Ctx);
11447   }
11448   case Expr::UnaryExprOrTypeTraitExprClass: {
11449     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11450     if ((Exp->getKind() ==  UETT_SizeOf) &&
11451         Exp->getTypeOfArgument()->isVariableArrayType())
11452       return ICEDiag(IK_NotICE, E->getBeginLoc());
11453     return NoDiag();
11454   }
11455   case Expr::BinaryOperatorClass: {
11456     const BinaryOperator *Exp = cast<BinaryOperator>(E);
11457     switch (Exp->getOpcode()) {
11458     case BO_PtrMemD:
11459     case BO_PtrMemI:
11460     case BO_Assign:
11461     case BO_MulAssign:
11462     case BO_DivAssign:
11463     case BO_RemAssign:
11464     case BO_AddAssign:
11465     case BO_SubAssign:
11466     case BO_ShlAssign:
11467     case BO_ShrAssign:
11468     case BO_AndAssign:
11469     case BO_XorAssign:
11470     case BO_OrAssign:
11471       // C99 6.6/3 allows assignments within unevaluated subexpressions of
11472       // constant expressions, but they can never be ICEs because an ICE cannot
11473       // contain an lvalue operand.
11474       return ICEDiag(IK_NotICE, E->getBeginLoc());
11475 
11476     case BO_Mul:
11477     case BO_Div:
11478     case BO_Rem:
11479     case BO_Add:
11480     case BO_Sub:
11481     case BO_Shl:
11482     case BO_Shr:
11483     case BO_LT:
11484     case BO_GT:
11485     case BO_LE:
11486     case BO_GE:
11487     case BO_EQ:
11488     case BO_NE:
11489     case BO_And:
11490     case BO_Xor:
11491     case BO_Or:
11492     case BO_Comma:
11493     case BO_Cmp: {
11494       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11495       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11496       if (Exp->getOpcode() == BO_Div ||
11497           Exp->getOpcode() == BO_Rem) {
11498         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11499         // we don't evaluate one.
11500         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11501           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11502           if (REval == 0)
11503             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11504           if (REval.isSigned() && REval.isAllOnesValue()) {
11505             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11506             if (LEval.isMinSignedValue())
11507               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11508           }
11509         }
11510       }
11511       if (Exp->getOpcode() == BO_Comma) {
11512         if (Ctx.getLangOpts().C99) {
11513           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11514           // if it isn't evaluated.
11515           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11516             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11517         } else {
11518           // In both C89 and C++, commas in ICEs are illegal.
11519           return ICEDiag(IK_NotICE, E->getBeginLoc());
11520         }
11521       }
11522       return Worst(LHSResult, RHSResult);
11523     }
11524     case BO_LAnd:
11525     case BO_LOr: {
11526       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11527       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11528       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11529         // Rare case where the RHS has a comma "side-effect"; we need
11530         // to actually check the condition to see whether the side
11531         // with the comma is evaluated.
11532         if ((Exp->getOpcode() == BO_LAnd) !=
11533             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11534           return RHSResult;
11535         return NoDiag();
11536       }
11537 
11538       return Worst(LHSResult, RHSResult);
11539     }
11540     }
11541     llvm_unreachable("invalid binary operator kind");
11542   }
11543   case Expr::ImplicitCastExprClass:
11544   case Expr::CStyleCastExprClass:
11545   case Expr::CXXFunctionalCastExprClass:
11546   case Expr::CXXStaticCastExprClass:
11547   case Expr::CXXReinterpretCastExprClass:
11548   case Expr::CXXConstCastExprClass:
11549   case Expr::ObjCBridgedCastExprClass: {
11550     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11551     if (isa<ExplicitCastExpr>(E)) {
11552       if (const FloatingLiteral *FL
11553             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11554         unsigned DestWidth = Ctx.getIntWidth(E->getType());
11555         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11556         APSInt IgnoredVal(DestWidth, !DestSigned);
11557         bool Ignored;
11558         // If the value does not fit in the destination type, the behavior is
11559         // undefined, so we are not required to treat it as a constant
11560         // expression.
11561         if (FL->getValue().convertToInteger(IgnoredVal,
11562                                             llvm::APFloat::rmTowardZero,
11563                                             &Ignored) & APFloat::opInvalidOp)
11564           return ICEDiag(IK_NotICE, E->getBeginLoc());
11565         return NoDiag();
11566       }
11567     }
11568     switch (cast<CastExpr>(E)->getCastKind()) {
11569     case CK_LValueToRValue:
11570     case CK_AtomicToNonAtomic:
11571     case CK_NonAtomicToAtomic:
11572     case CK_NoOp:
11573     case CK_IntegralToBoolean:
11574     case CK_IntegralCast:
11575       return CheckICE(SubExpr, Ctx);
11576     default:
11577       return ICEDiag(IK_NotICE, E->getBeginLoc());
11578     }
11579   }
11580   case Expr::BinaryConditionalOperatorClass: {
11581     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11582     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11583     if (CommonResult.Kind == IK_NotICE) return CommonResult;
11584     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11585     if (FalseResult.Kind == IK_NotICE) return FalseResult;
11586     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11587     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11588         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11589     return FalseResult;
11590   }
11591   case Expr::ConditionalOperatorClass: {
11592     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11593     // If the condition (ignoring parens) is a __builtin_constant_p call,
11594     // then only the true side is actually considered in an integer constant
11595     // expression, and it is fully evaluated.  This is an important GNU
11596     // extension.  See GCC PR38377 for discussion.
11597     if (const CallExpr *CallCE
11598         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11599       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11600         return CheckEvalInICE(E, Ctx);
11601     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11602     if (CondResult.Kind == IK_NotICE)
11603       return CondResult;
11604 
11605     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11606     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11607 
11608     if (TrueResult.Kind == IK_NotICE)
11609       return TrueResult;
11610     if (FalseResult.Kind == IK_NotICE)
11611       return FalseResult;
11612     if (CondResult.Kind == IK_ICEIfUnevaluated)
11613       return CondResult;
11614     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11615       return NoDiag();
11616     // Rare case where the diagnostics depend on which side is evaluated
11617     // Note that if we get here, CondResult is 0, and at least one of
11618     // TrueResult and FalseResult is non-zero.
11619     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11620       return FalseResult;
11621     return TrueResult;
11622   }
11623   case Expr::CXXDefaultArgExprClass:
11624     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11625   case Expr::CXXDefaultInitExprClass:
11626     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11627   case Expr::ChooseExprClass: {
11628     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11629   }
11630   }
11631 
11632   llvm_unreachable("Invalid StmtClass!");
11633 }
11634 
11635 /// Evaluate an expression as a C++11 integral constant expression.
11636 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11637                                                     const Expr *E,
11638                                                     llvm::APSInt *Value,
11639                                                     SourceLocation *Loc) {
11640   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11641     if (Loc) *Loc = E->getExprLoc();
11642     return false;
11643   }
11644 
11645   APValue Result;
11646   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11647     return false;
11648 
11649   if (!Result.isInt()) {
11650     if (Loc) *Loc = E->getExprLoc();
11651     return false;
11652   }
11653 
11654   if (Value) *Value = Result.getInt();
11655   return true;
11656 }
11657 
11658 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11659                                  SourceLocation *Loc) const {
11660   if (Ctx.getLangOpts().CPlusPlus11)
11661     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11662 
11663   ICEDiag D = CheckICE(this, Ctx);
11664   if (D.Kind != IK_ICE) {
11665     if (Loc) *Loc = D.Loc;
11666     return false;
11667   }
11668   return true;
11669 }
11670 
11671 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11672                                  SourceLocation *Loc, bool isEvaluated) const {
11673   if (Ctx.getLangOpts().CPlusPlus11)
11674     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11675 
11676   if (!isIntegerConstantExpr(Ctx, Loc))
11677     return false;
11678 
11679   // The only possible side-effects here are due to UB discovered in the
11680   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11681   // required to treat the expression as an ICE, so we produce the folded
11682   // value.
11683   EvalResult ExprResult;
11684   Expr::EvalStatus Status;
11685   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11686   Info.InConstantContext = true;
11687 
11688   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
11689     llvm_unreachable("ICE cannot be evaluated!");
11690 
11691   Value = ExprResult.Val.getInt();
11692   return true;
11693 }
11694 
11695 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11696   return CheckICE(this, Ctx).Kind == IK_ICE;
11697 }
11698 
11699 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11700                                SourceLocation *Loc) const {
11701   // We support this checking in C++98 mode in order to diagnose compatibility
11702   // issues.
11703   assert(Ctx.getLangOpts().CPlusPlus);
11704 
11705   // Build evaluation settings.
11706   Expr::EvalStatus Status;
11707   SmallVector<PartialDiagnosticAt, 8> Diags;
11708   Status.Diag = &Diags;
11709   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11710 
11711   APValue Scratch;
11712   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11713 
11714   if (!Diags.empty()) {
11715     IsConstExpr = false;
11716     if (Loc) *Loc = Diags[0].first;
11717   } else if (!IsConstExpr) {
11718     // FIXME: This shouldn't happen.
11719     if (Loc) *Loc = getExprLoc();
11720   }
11721 
11722   return IsConstExpr;
11723 }
11724 
11725 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11726                                     const FunctionDecl *Callee,
11727                                     ArrayRef<const Expr*> Args,
11728                                     const Expr *This) const {
11729   Expr::EvalStatus Status;
11730   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11731 
11732   LValue ThisVal;
11733   const LValue *ThisPtr = nullptr;
11734   if (This) {
11735 #ifndef NDEBUG
11736     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11737     assert(MD && "Don't provide `this` for non-methods.");
11738     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11739 #endif
11740     if (EvaluateObjectArgument(Info, This, ThisVal))
11741       ThisPtr = &ThisVal;
11742     if (Info.EvalStatus.HasSideEffects)
11743       return false;
11744   }
11745 
11746   ArgVector ArgValues(Args.size());
11747   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11748        I != E; ++I) {
11749     if ((*I)->isValueDependent() ||
11750         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11751       // If evaluation fails, throw away the argument entirely.
11752       ArgValues[I - Args.begin()] = APValue();
11753     if (Info.EvalStatus.HasSideEffects)
11754       return false;
11755   }
11756 
11757   // Build fake call to Callee.
11758   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11759                        ArgValues.data());
11760   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11761 }
11762 
11763 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11764                                    SmallVectorImpl<
11765                                      PartialDiagnosticAt> &Diags) {
11766   // FIXME: It would be useful to check constexpr function templates, but at the
11767   // moment the constant expression evaluator cannot cope with the non-rigorous
11768   // ASTs which we build for dependent expressions.
11769   if (FD->isDependentContext())
11770     return true;
11771 
11772   Expr::EvalStatus Status;
11773   Status.Diag = &Diags;
11774 
11775   EvalInfo Info(FD->getASTContext(), Status,
11776                 EvalInfo::EM_PotentialConstantExpression);
11777   Info.InConstantContext = true;
11778 
11779   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11780   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11781 
11782   // Fabricate an arbitrary expression on the stack and pretend that it
11783   // is a temporary being used as the 'this' pointer.
11784   LValue This;
11785   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11786   This.set({&VIE, Info.CurrentCall->Index});
11787 
11788   ArrayRef<const Expr*> Args;
11789 
11790   APValue Scratch;
11791   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11792     // Evaluate the call as a constant initializer, to allow the construction
11793     // of objects of non-literal types.
11794     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11795     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11796   } else {
11797     SourceLocation Loc = FD->getLocation();
11798     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11799                        Args, FD->getBody(), Info, Scratch, nullptr);
11800   }
11801 
11802   return Diags.empty();
11803 }
11804 
11805 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11806                                               const FunctionDecl *FD,
11807                                               SmallVectorImpl<
11808                                                 PartialDiagnosticAt> &Diags) {
11809   Expr::EvalStatus Status;
11810   Status.Diag = &Diags;
11811 
11812   EvalInfo Info(FD->getASTContext(), Status,
11813                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11814 
11815   // Fabricate a call stack frame to give the arguments a plausible cover story.
11816   ArrayRef<const Expr*> Args;
11817   ArgVector ArgValues(0);
11818   bool Success = EvaluateArgs(Args, ArgValues, Info);
11819   (void)Success;
11820   assert(Success &&
11821          "Failed to set up arguments for potential constant evaluation");
11822   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11823 
11824   APValue ResultScratch;
11825   Evaluate(ResultScratch, Info, E);
11826   return Diags.empty();
11827 }
11828 
11829 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11830                                  unsigned Type) const {
11831   if (!getType()->isPointerType())
11832     return false;
11833 
11834   Expr::EvalStatus Status;
11835   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11836   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
11837 }
11838