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/CurrentSourceLocExprScope.h"
41 #include "clang/AST/CXXInheritance.h"
42 #include "clang/AST/Expr.h"
43 #include "clang/AST/OSLog.h"
44 #include "clang/AST/RecordLayout.h"
45 #include "clang/AST/StmtVisitor.h"
46 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/FixedPoint.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "llvm/ADT/SmallBitVector.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <cstring>
54 #include <functional>
55 
56 #define DEBUG_TYPE "exprconstant"
57 
58 using namespace clang;
59 using llvm::APSInt;
60 using llvm::APFloat;
61 
62 static bool IsGlobalLValue(APValue::LValueBase B);
63 
64 namespace {
65   struct LValue;
66   struct CallStackFrame;
67   struct EvalInfo;
68 
69   using SourceLocExprScopeGuard =
70       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
71 
72   static QualType getType(APValue::LValueBase B) {
73     if (!B) return QualType();
74     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
75       // FIXME: It's unclear where we're supposed to take the type from, and
76       // this actually matters for arrays of unknown bound. Eg:
77       //
78       // extern int arr[]; void f() { extern int arr[3]; };
79       // constexpr int *p = &arr[1]; // valid?
80       //
81       // For now, we take the array bound from the most recent declaration.
82       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
83            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
84         QualType T = Redecl->getType();
85         if (!T->isIncompleteArrayType())
86           return T;
87       }
88       return D->getType();
89     }
90 
91     if (B.is<TypeInfoLValue>())
92       return B.getTypeInfoType();
93 
94     const Expr *Base = B.get<const Expr*>();
95 
96     // For a materialized temporary, the type of the temporary we materialized
97     // may not be the type of the expression.
98     if (const MaterializeTemporaryExpr *MTE =
99             dyn_cast<MaterializeTemporaryExpr>(Base)) {
100       SmallVector<const Expr *, 2> CommaLHSs;
101       SmallVector<SubobjectAdjustment, 2> Adjustments;
102       const Expr *Temp = MTE->GetTemporaryExpr();
103       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
104                                                                Adjustments);
105       // Keep any cv-qualifiers from the reference if we generated a temporary
106       // for it directly. Otherwise use the type after adjustment.
107       if (!Adjustments.empty())
108         return Inner->getType();
109     }
110 
111     return Base->getType();
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_or_null<FieldDecl>(E.getAsBaseOrMember().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_or_null<CXXRecordDecl>(E.getAsBaseOrMember().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 E.getAsBaseOrMember().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_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 truncate(ASTContext &Ctx, APValue::LValueBase Base,
295                   unsigned NewLength) {
296       if (Invalid)
297         return;
298 
299       assert(Base && "cannot truncate path for null pointer");
300       assert(NewLength <= Entries.size() && "not a truncation");
301 
302       if (NewLength == Entries.size())
303         return;
304       Entries.resize(NewLength);
305 
306       bool IsArray = false;
307       bool FirstIsUnsizedArray = false;
308       MostDerivedPathLength = findMostDerivedSubobject(
309           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
310           FirstIsUnsizedArray);
311       MostDerivedIsArrayElement = IsArray;
312       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
313     }
314 
315     void setInvalid() {
316       Invalid = true;
317       Entries.clear();
318     }
319 
320     /// Determine whether the most derived subobject is an array without a
321     /// known bound.
322     bool isMostDerivedAnUnsizedArray() const {
323       assert(!Invalid && "Calling this makes no sense on invalid designators");
324       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
325     }
326 
327     /// Determine what the most derived array's size is. Results in an assertion
328     /// failure if the most derived array lacks a size.
329     uint64_t getMostDerivedArraySize() const {
330       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
331       return MostDerivedArraySize;
332     }
333 
334     /// Determine whether this is a one-past-the-end pointer.
335     bool isOnePastTheEnd() const {
336       assert(!Invalid);
337       if (IsOnePastTheEnd)
338         return true;
339       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
340           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
341               MostDerivedArraySize)
342         return true;
343       return false;
344     }
345 
346     /// Get the range of valid index adjustments in the form
347     ///   {maximum value that can be subtracted from this pointer,
348     ///    maximum value that can be added to this pointer}
349     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
350       if (Invalid || isMostDerivedAnUnsizedArray())
351         return {0, 0};
352 
353       // [expr.add]p4: For the purposes of these operators, a pointer to a
354       // nonarray object behaves the same as a pointer to the first element of
355       // an array of length one with the type of the object as its element type.
356       bool IsArray = MostDerivedPathLength == Entries.size() &&
357                      MostDerivedIsArrayElement;
358       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
359                                     : (uint64_t)IsOnePastTheEnd;
360       uint64_t ArraySize =
361           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
362       return {ArrayIndex, ArraySize - ArrayIndex};
363     }
364 
365     /// Check that this refers to a valid subobject.
366     bool isValidSubobject() const {
367       if (Invalid)
368         return false;
369       return !isOnePastTheEnd();
370     }
371     /// Check that this refers to a valid subobject, and if not, produce a
372     /// relevant diagnostic and set the designator as invalid.
373     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
374 
375     /// Get the type of the designated object.
376     QualType getType(ASTContext &Ctx) const {
377       assert(!Invalid && "invalid designator has no subobject type");
378       return MostDerivedPathLength == Entries.size()
379                  ? MostDerivedType
380                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
381     }
382 
383     /// Update this designator to refer to the first element within this array.
384     void addArrayUnchecked(const ConstantArrayType *CAT) {
385       Entries.push_back(PathEntry::ArrayIndex(0));
386 
387       // This is a most-derived object.
388       MostDerivedType = CAT->getElementType();
389       MostDerivedIsArrayElement = true;
390       MostDerivedArraySize = CAT->getSize().getZExtValue();
391       MostDerivedPathLength = Entries.size();
392     }
393     /// Update this designator to refer to the first element within the array of
394     /// elements of type T. This is an array of unknown size.
395     void addUnsizedArrayUnchecked(QualType ElemTy) {
396       Entries.push_back(PathEntry::ArrayIndex(0));
397 
398       MostDerivedType = ElemTy;
399       MostDerivedIsArrayElement = true;
400       // The value in MostDerivedArraySize is undefined in this case. So, set it
401       // to an arbitrary value that's likely to loudly break things if it's
402       // used.
403       MostDerivedArraySize = AssumedSizeForUnsizedArray;
404       MostDerivedPathLength = Entries.size();
405     }
406     /// Update this designator to refer to the given base or member of this
407     /// object.
408     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
409       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
410 
411       // If this isn't a base class, it's a new most-derived object.
412       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
413         MostDerivedType = FD->getType();
414         MostDerivedIsArrayElement = false;
415         MostDerivedArraySize = 0;
416         MostDerivedPathLength = Entries.size();
417       }
418     }
419     /// Update this designator to refer to the given complex component.
420     void addComplexUnchecked(QualType EltTy, bool Imag) {
421       Entries.push_back(PathEntry::ArrayIndex(Imag));
422 
423       // This is technically a most-derived object, though in practice this
424       // is unlikely to matter.
425       MostDerivedType = EltTy;
426       MostDerivedIsArrayElement = true;
427       MostDerivedArraySize = 2;
428       MostDerivedPathLength = Entries.size();
429     }
430     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
431     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
432                                    const APSInt &N);
433     /// Add N to the address of this subobject.
434     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
435       if (Invalid || !N) return;
436       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
437       if (isMostDerivedAnUnsizedArray()) {
438         diagnoseUnsizedArrayPointerArithmetic(Info, E);
439         // Can't verify -- trust that the user is doing the right thing (or if
440         // not, trust that the caller will catch the bad behavior).
441         // FIXME: Should we reject if this overflows, at least?
442         Entries.back() = PathEntry::ArrayIndex(
443             Entries.back().getAsArrayIndex() + TruncatedN);
444         return;
445       }
446 
447       // [expr.add]p4: For the purposes of these operators, a pointer to a
448       // nonarray object behaves the same as a pointer to the first element of
449       // an array of length one with the type of the object as its element type.
450       bool IsArray = MostDerivedPathLength == Entries.size() &&
451                      MostDerivedIsArrayElement;
452       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
453                                     : (uint64_t)IsOnePastTheEnd;
454       uint64_t ArraySize =
455           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
456 
457       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
458         // Calculate the actual index in a wide enough type, so we can include
459         // it in the note.
460         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
461         (llvm::APInt&)N += ArrayIndex;
462         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
463         diagnosePointerArithmetic(Info, E, N);
464         setInvalid();
465         return;
466       }
467 
468       ArrayIndex += TruncatedN;
469       assert(ArrayIndex <= ArraySize &&
470              "bounds check succeeded for out-of-bounds index");
471 
472       if (IsArray)
473         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
474       else
475         IsOnePastTheEnd = (ArrayIndex != 0);
476     }
477   };
478 
479   /// A stack frame in the constexpr call stack.
480   struct CallStackFrame {
481     EvalInfo &Info;
482 
483     /// Parent - The caller of this stack frame.
484     CallStackFrame *Caller;
485 
486     /// Callee - The function which was called.
487     const FunctionDecl *Callee;
488 
489     /// This - The binding for the this pointer in this call, if any.
490     const LValue *This;
491 
492     /// Arguments - Parameter bindings for this function call, indexed by
493     /// parameters' function scope indices.
494     APValue *Arguments;
495 
496     /// Source location information about the default argument or default
497     /// initializer expression we're evaluating, if any.
498     CurrentSourceLocExprScope CurSourceLocExprScope;
499 
500     // Note that we intentionally use std::map here so that references to
501     // values are stable.
502     typedef std::pair<const void *, unsigned> MapKeyTy;
503     typedef std::map<MapKeyTy, APValue> MapTy;
504     /// Temporaries - Temporary lvalues materialized within this stack frame.
505     MapTy Temporaries;
506 
507     /// CallLoc - The location of the call expression for this call.
508     SourceLocation CallLoc;
509 
510     /// Index - The call index of this call.
511     unsigned Index;
512 
513     /// The stack of integers for tracking version numbers for temporaries.
514     SmallVector<unsigned, 2> TempVersionStack = {1};
515     unsigned CurTempVersion = TempVersionStack.back();
516 
517     unsigned getTempVersion() const { return TempVersionStack.back(); }
518 
519     void pushTempVersion() {
520       TempVersionStack.push_back(++CurTempVersion);
521     }
522 
523     void popTempVersion() {
524       TempVersionStack.pop_back();
525     }
526 
527     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
528     // on the overall stack usage of deeply-recursing constexpr evaluations.
529     // (We should cache this map rather than recomputing it repeatedly.)
530     // But let's try this and see how it goes; we can look into caching the map
531     // as a later change.
532 
533     /// LambdaCaptureFields - Mapping from captured variables/this to
534     /// corresponding data members in the closure class.
535     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
536     FieldDecl *LambdaThisCaptureField;
537 
538     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
539                    const FunctionDecl *Callee, const LValue *This,
540                    APValue *Arguments);
541     ~CallStackFrame();
542 
543     // Return the temporary for Key whose version number is Version.
544     APValue *getTemporary(const void *Key, unsigned Version) {
545       MapKeyTy KV(Key, Version);
546       auto LB = Temporaries.lower_bound(KV);
547       if (LB != Temporaries.end() && LB->first == KV)
548         return &LB->second;
549       // Pair (Key,Version) wasn't found in the map. Check that no elements
550       // in the map have 'Key' as their key.
551       assert((LB == Temporaries.end() || LB->first.first != Key) &&
552              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
553              "Element with key 'Key' found in map");
554       return nullptr;
555     }
556 
557     // Return the current temporary for Key in the map.
558     APValue *getCurrentTemporary(const void *Key) {
559       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
560       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
561         return &std::prev(UB)->second;
562       return nullptr;
563     }
564 
565     // Return the version number of the current temporary for Key.
566     unsigned getCurrentTemporaryVersion(const void *Key) const {
567       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
568       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
569         return std::prev(UB)->first.second;
570       return 0;
571     }
572 
573     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
574   };
575 
576   /// Temporarily override 'this'.
577   class ThisOverrideRAII {
578   public:
579     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
580         : Frame(Frame), OldThis(Frame.This) {
581       if (Enable)
582         Frame.This = NewThis;
583     }
584     ~ThisOverrideRAII() {
585       Frame.This = OldThis;
586     }
587   private:
588     CallStackFrame &Frame;
589     const LValue *OldThis;
590   };
591 
592   /// A partial diagnostic which we might know in advance that we are not going
593   /// to emit.
594   class OptionalDiagnostic {
595     PartialDiagnostic *Diag;
596 
597   public:
598     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
599       : Diag(Diag) {}
600 
601     template<typename T>
602     OptionalDiagnostic &operator<<(const T &v) {
603       if (Diag)
604         *Diag << v;
605       return *this;
606     }
607 
608     OptionalDiagnostic &operator<<(const APSInt &I) {
609       if (Diag) {
610         SmallVector<char, 32> Buffer;
611         I.toString(Buffer);
612         *Diag << StringRef(Buffer.data(), Buffer.size());
613       }
614       return *this;
615     }
616 
617     OptionalDiagnostic &operator<<(const APFloat &F) {
618       if (Diag) {
619         // FIXME: Force the precision of the source value down so we don't
620         // print digits which are usually useless (we don't really care here if
621         // we truncate a digit by accident in edge cases).  Ideally,
622         // APFloat::toString would automatically print the shortest
623         // representation which rounds to the correct value, but it's a bit
624         // tricky to implement.
625         unsigned precision =
626             llvm::APFloat::semanticsPrecision(F.getSemantics());
627         precision = (precision * 59 + 195) / 196;
628         SmallVector<char, 32> Buffer;
629         F.toString(Buffer, precision);
630         *Diag << StringRef(Buffer.data(), Buffer.size());
631       }
632       return *this;
633     }
634 
635     OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
636       if (Diag) {
637         SmallVector<char, 32> Buffer;
638         FX.toString(Buffer);
639         *Diag << StringRef(Buffer.data(), Buffer.size());
640       }
641       return *this;
642     }
643   };
644 
645   /// A cleanup, and a flag indicating whether it is lifetime-extended.
646   class Cleanup {
647     llvm::PointerIntPair<APValue*, 1, bool> Value;
648 
649   public:
650     Cleanup(APValue *Val, bool IsLifetimeExtended)
651         : Value(Val, IsLifetimeExtended) {}
652 
653     bool isLifetimeExtended() const { return Value.getInt(); }
654     void endLifetime() {
655       *Value.getPointer() = APValue();
656     }
657   };
658 
659   /// A reference to an object whose construction we are currently evaluating.
660   struct ObjectUnderConstruction {
661     APValue::LValueBase Base;
662     ArrayRef<APValue::LValuePathEntry> Path;
663     friend bool operator==(const ObjectUnderConstruction &LHS,
664                            const ObjectUnderConstruction &RHS) {
665       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
666     }
667     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
668       return llvm::hash_combine(Obj.Base, Obj.Path);
669     }
670   };
671   enum class ConstructionPhase { None, Bases, AfterBases };
672 }
673 
674 namespace llvm {
675 template<> struct DenseMapInfo<ObjectUnderConstruction> {
676   using Base = DenseMapInfo<APValue::LValueBase>;
677   static ObjectUnderConstruction getEmptyKey() {
678     return {Base::getEmptyKey(), {}}; }
679   static ObjectUnderConstruction getTombstoneKey() {
680     return {Base::getTombstoneKey(), {}};
681   }
682   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
683     return hash_value(Object);
684   }
685   static bool isEqual(const ObjectUnderConstruction &LHS,
686                       const ObjectUnderConstruction &RHS) {
687     return LHS == RHS;
688   }
689 };
690 }
691 
692 namespace {
693   /// EvalInfo - This is a private struct used by the evaluator to capture
694   /// information about a subexpression as it is folded.  It retains information
695   /// about the AST context, but also maintains information about the folded
696   /// expression.
697   ///
698   /// If an expression could be evaluated, it is still possible it is not a C
699   /// "integer constant expression" or constant expression.  If not, this struct
700   /// captures information about how and why not.
701   ///
702   /// One bit of information passed *into* the request for constant folding
703   /// indicates whether the subexpression is "evaluated" or not according to C
704   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
705   /// evaluate the expression regardless of what the RHS is, but C only allows
706   /// certain things in certain situations.
707   struct EvalInfo {
708     ASTContext &Ctx;
709 
710     /// EvalStatus - Contains information about the evaluation.
711     Expr::EvalStatus &EvalStatus;
712 
713     /// CurrentCall - The top of the constexpr call stack.
714     CallStackFrame *CurrentCall;
715 
716     /// CallStackDepth - The number of calls in the call stack right now.
717     unsigned CallStackDepth;
718 
719     /// NextCallIndex - The next call index to assign.
720     unsigned NextCallIndex;
721 
722     /// StepsLeft - The remaining number of evaluation steps we're permitted
723     /// to perform. This is essentially a limit for the number of statements
724     /// we will evaluate.
725     unsigned StepsLeft;
726 
727     /// BottomFrame - The frame in which evaluation started. This must be
728     /// initialized after CurrentCall and CallStackDepth.
729     CallStackFrame BottomFrame;
730 
731     /// A stack of values whose lifetimes end at the end of some surrounding
732     /// evaluation frame.
733     llvm::SmallVector<Cleanup, 16> CleanupStack;
734 
735     /// EvaluatingDecl - This is the declaration whose initializer is being
736     /// evaluated, if any.
737     APValue::LValueBase EvaluatingDecl;
738 
739     /// EvaluatingDeclValue - This is the value being constructed for the
740     /// declaration whose initializer is being evaluated, if any.
741     APValue *EvaluatingDeclValue;
742 
743     /// Set of objects that are currently being constructed.
744     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
745         ObjectsUnderConstruction;
746 
747     struct EvaluatingConstructorRAII {
748       EvalInfo &EI;
749       ObjectUnderConstruction Object;
750       bool DidInsert;
751       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
752                                 bool HasBases)
753           : EI(EI), Object(Object) {
754         DidInsert =
755             EI.ObjectsUnderConstruction
756                 .insert({Object, HasBases ? ConstructionPhase::Bases
757                                           : ConstructionPhase::AfterBases})
758                 .second;
759       }
760       void finishedConstructingBases() {
761         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
762       }
763       ~EvaluatingConstructorRAII() {
764         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
765       }
766     };
767 
768     ConstructionPhase
769     isEvaluatingConstructor(APValue::LValueBase Base,
770                             ArrayRef<APValue::LValuePathEntry> Path) {
771       return ObjectsUnderConstruction.lookup({Base, Path});
772     }
773 
774     /// If we're currently speculatively evaluating, the outermost call stack
775     /// depth at which we can mutate state, otherwise 0.
776     unsigned SpeculativeEvaluationDepth = 0;
777 
778     /// The current array initialization index, if we're performing array
779     /// initialization.
780     uint64_t ArrayInitIndex = -1;
781 
782     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
783     /// notes attached to it will also be stored, otherwise they will not be.
784     bool HasActiveDiagnostic;
785 
786     /// Have we emitted a diagnostic explaining why we couldn't constant
787     /// fold (not just why it's not strictly a constant expression)?
788     bool HasFoldFailureDiagnostic;
789 
790     /// Whether or not we're in a context where the front end requires a
791     /// constant value.
792     bool InConstantContext;
793 
794     enum EvaluationMode {
795       /// Evaluate as a constant expression. Stop if we find that the expression
796       /// is not a constant expression.
797       EM_ConstantExpression,
798 
799       /// Evaluate as a potential constant expression. Keep going if we hit a
800       /// construct that we can't evaluate yet (because we don't yet know the
801       /// value of something) but stop if we hit something that could never be
802       /// a constant expression.
803       EM_PotentialConstantExpression,
804 
805       /// Fold the expression to a constant. Stop if we hit a side-effect that
806       /// we can't model.
807       EM_ConstantFold,
808 
809       /// Evaluate the expression looking for integer overflow and similar
810       /// issues. Don't worry about side-effects, and try to visit all
811       /// subexpressions.
812       EM_EvaluateForOverflow,
813 
814       /// Evaluate in any way we know how. Don't worry about side-effects that
815       /// can't be modeled.
816       EM_IgnoreSideEffects,
817 
818       /// Evaluate as a constant expression. Stop if we find that the expression
819       /// is not a constant expression. Some expressions can be retried in the
820       /// optimizer if we don't constant fold them here, but in an unevaluated
821       /// context we try to fold them immediately since the optimizer never
822       /// gets a chance to look at it.
823       EM_ConstantExpressionUnevaluated,
824 
825       /// Evaluate as a potential constant expression. Keep going if we hit a
826       /// construct that we can't evaluate yet (because we don't yet know the
827       /// value of something) but stop if we hit something that could never be
828       /// a constant expression. Some expressions can be retried in the
829       /// optimizer if we don't constant fold them here, but in an unevaluated
830       /// context we try to fold them immediately since the optimizer never
831       /// gets a chance to look at it.
832       EM_PotentialConstantExpressionUnevaluated,
833     } EvalMode;
834 
835     /// Are we checking whether the expression is a potential constant
836     /// expression?
837     bool checkingPotentialConstantExpression() const {
838       return EvalMode == EM_PotentialConstantExpression ||
839              EvalMode == EM_PotentialConstantExpressionUnevaluated;
840     }
841 
842     /// Are we checking an expression for overflow?
843     // FIXME: We should check for any kind of undefined or suspicious behavior
844     // in such constructs, not just overflow.
845     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
846 
847     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
848       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
849         CallStackDepth(0), NextCallIndex(1),
850         StepsLeft(getLangOpts().ConstexprStepLimit),
851         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
852         EvaluatingDecl((const ValueDecl *)nullptr),
853         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
854         HasFoldFailureDiagnostic(false),
855         InConstantContext(false), EvalMode(Mode) {}
856 
857     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
858       EvaluatingDecl = Base;
859       EvaluatingDeclValue = &Value;
860     }
861 
862     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
863 
864     bool CheckCallLimit(SourceLocation Loc) {
865       // Don't perform any constexpr calls (other than the call we're checking)
866       // when checking a potential constant expression.
867       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
868         return false;
869       if (NextCallIndex == 0) {
870         // NextCallIndex has wrapped around.
871         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
872         return false;
873       }
874       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
875         return true;
876       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
877         << getLangOpts().ConstexprCallDepth;
878       return false;
879     }
880 
881     std::pair<CallStackFrame *, unsigned>
882     getCallFrameAndDepth(unsigned CallIndex) {
883       assert(CallIndex && "no call index in getCallFrameAndDepth");
884       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
885       // be null in this loop.
886       unsigned Depth = CallStackDepth;
887       CallStackFrame *Frame = CurrentCall;
888       while (Frame->Index > CallIndex) {
889         Frame = Frame->Caller;
890         --Depth;
891       }
892       if (Frame->Index == CallIndex)
893         return {Frame, Depth};
894       return {nullptr, 0};
895     }
896 
897     bool nextStep(const Stmt *S) {
898       if (!StepsLeft) {
899         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
900         return false;
901       }
902       --StepsLeft;
903       return true;
904     }
905 
906   private:
907     /// Add a diagnostic to the diagnostics list.
908     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
909       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
910       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
911       return EvalStatus.Diag->back().second;
912     }
913 
914     /// Add notes containing a call stack to the current point of evaluation.
915     void addCallStack(unsigned Limit);
916 
917   private:
918     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
919                             unsigned ExtraNotes, bool IsCCEDiag) {
920 
921       if (EvalStatus.Diag) {
922         // If we have a prior diagnostic, it will be noting that the expression
923         // isn't a constant expression. This diagnostic is more important,
924         // unless we require this evaluation to produce a constant expression.
925         //
926         // FIXME: We might want to show both diagnostics to the user in
927         // EM_ConstantFold mode.
928         if (!EvalStatus.Diag->empty()) {
929           switch (EvalMode) {
930           case EM_ConstantFold:
931           case EM_IgnoreSideEffects:
932           case EM_EvaluateForOverflow:
933             if (!HasFoldFailureDiagnostic)
934               break;
935             // We've already failed to fold something. Keep that diagnostic.
936             LLVM_FALLTHROUGH;
937           case EM_ConstantExpression:
938           case EM_PotentialConstantExpression:
939           case EM_ConstantExpressionUnevaluated:
940           case EM_PotentialConstantExpressionUnevaluated:
941             HasActiveDiagnostic = false;
942             return OptionalDiagnostic();
943           }
944         }
945 
946         unsigned CallStackNotes = CallStackDepth - 1;
947         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
948         if (Limit)
949           CallStackNotes = std::min(CallStackNotes, Limit + 1);
950         if (checkingPotentialConstantExpression())
951           CallStackNotes = 0;
952 
953         HasActiveDiagnostic = true;
954         HasFoldFailureDiagnostic = !IsCCEDiag;
955         EvalStatus.Diag->clear();
956         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
957         addDiag(Loc, DiagId);
958         if (!checkingPotentialConstantExpression())
959           addCallStack(Limit);
960         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
961       }
962       HasActiveDiagnostic = false;
963       return OptionalDiagnostic();
964     }
965   public:
966     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
967     OptionalDiagnostic
968     FFDiag(SourceLocation Loc,
969           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
970           unsigned ExtraNotes = 0) {
971       return Diag(Loc, DiagId, ExtraNotes, false);
972     }
973 
974     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
975                               = diag::note_invalid_subexpr_in_const_expr,
976                             unsigned ExtraNotes = 0) {
977       if (EvalStatus.Diag)
978         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
979       HasActiveDiagnostic = false;
980       return OptionalDiagnostic();
981     }
982 
983     /// Diagnose that the evaluation does not produce a C++11 core constant
984     /// expression.
985     ///
986     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
987     /// EM_PotentialConstantExpression mode and we produce one of these.
988     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
989                                  = diag::note_invalid_subexpr_in_const_expr,
990                                unsigned ExtraNotes = 0) {
991       // Don't override a previous diagnostic. Don't bother collecting
992       // diagnostics if we're evaluating for overflow.
993       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
994         HasActiveDiagnostic = false;
995         return OptionalDiagnostic();
996       }
997       return Diag(Loc, DiagId, ExtraNotes, true);
998     }
999     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1000                                  = diag::note_invalid_subexpr_in_const_expr,
1001                                unsigned ExtraNotes = 0) {
1002       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1003     }
1004     /// Add a note to a prior diagnostic.
1005     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1006       if (!HasActiveDiagnostic)
1007         return OptionalDiagnostic();
1008       return OptionalDiagnostic(&addDiag(Loc, DiagId));
1009     }
1010 
1011     /// Add a stack of notes to a prior diagnostic.
1012     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1013       if (HasActiveDiagnostic) {
1014         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1015                                 Diags.begin(), Diags.end());
1016       }
1017     }
1018 
1019     /// Should we continue evaluation after encountering a side-effect that we
1020     /// couldn't model?
1021     bool keepEvaluatingAfterSideEffect() {
1022       switch (EvalMode) {
1023       case EM_PotentialConstantExpression:
1024       case EM_PotentialConstantExpressionUnevaluated:
1025       case EM_EvaluateForOverflow:
1026       case EM_IgnoreSideEffects:
1027         return true;
1028 
1029       case EM_ConstantExpression:
1030       case EM_ConstantExpressionUnevaluated:
1031       case EM_ConstantFold:
1032         return false;
1033       }
1034       llvm_unreachable("Missed EvalMode case");
1035     }
1036 
1037     /// Note that we have had a side-effect, and determine whether we should
1038     /// keep evaluating.
1039     bool noteSideEffect() {
1040       EvalStatus.HasSideEffects = true;
1041       return keepEvaluatingAfterSideEffect();
1042     }
1043 
1044     /// Should we continue evaluation after encountering undefined behavior?
1045     bool keepEvaluatingAfterUndefinedBehavior() {
1046       switch (EvalMode) {
1047       case EM_EvaluateForOverflow:
1048       case EM_IgnoreSideEffects:
1049       case EM_ConstantFold:
1050         return true;
1051 
1052       case EM_PotentialConstantExpression:
1053       case EM_PotentialConstantExpressionUnevaluated:
1054       case EM_ConstantExpression:
1055       case EM_ConstantExpressionUnevaluated:
1056         return false;
1057       }
1058       llvm_unreachable("Missed EvalMode case");
1059     }
1060 
1061     /// Note that we hit something that was technically undefined behavior, but
1062     /// that we can evaluate past it (such as signed overflow or floating-point
1063     /// division by zero.)
1064     bool noteUndefinedBehavior() {
1065       EvalStatus.HasUndefinedBehavior = true;
1066       return keepEvaluatingAfterUndefinedBehavior();
1067     }
1068 
1069     /// Should we continue evaluation as much as possible after encountering a
1070     /// construct which can't be reduced to a value?
1071     bool keepEvaluatingAfterFailure() {
1072       if (!StepsLeft)
1073         return false;
1074 
1075       switch (EvalMode) {
1076       case EM_PotentialConstantExpression:
1077       case EM_PotentialConstantExpressionUnevaluated:
1078       case EM_EvaluateForOverflow:
1079         return true;
1080 
1081       case EM_ConstantExpression:
1082       case EM_ConstantExpressionUnevaluated:
1083       case EM_ConstantFold:
1084       case EM_IgnoreSideEffects:
1085         return false;
1086       }
1087       llvm_unreachable("Missed EvalMode case");
1088     }
1089 
1090     /// Notes that we failed to evaluate an expression that other expressions
1091     /// directly depend on, and determine if we should keep evaluating. This
1092     /// should only be called if we actually intend to keep evaluating.
1093     ///
1094     /// Call noteSideEffect() instead if we may be able to ignore the value that
1095     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1096     ///
1097     /// (Foo(), 1)      // use noteSideEffect
1098     /// (Foo() || true) // use noteSideEffect
1099     /// Foo() + 1       // use noteFailure
1100     LLVM_NODISCARD bool noteFailure() {
1101       // Failure when evaluating some expression often means there is some
1102       // subexpression whose evaluation was skipped. Therefore, (because we
1103       // don't track whether we skipped an expression when unwinding after an
1104       // evaluation failure) every evaluation failure that bubbles up from a
1105       // subexpression implies that a side-effect has potentially happened. We
1106       // skip setting the HasSideEffects flag to true until we decide to
1107       // continue evaluating after that point, which happens here.
1108       bool KeepGoing = keepEvaluatingAfterFailure();
1109       EvalStatus.HasSideEffects |= KeepGoing;
1110       return KeepGoing;
1111     }
1112 
1113     class ArrayInitLoopIndex {
1114       EvalInfo &Info;
1115       uint64_t OuterIndex;
1116 
1117     public:
1118       ArrayInitLoopIndex(EvalInfo &Info)
1119           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1120         Info.ArrayInitIndex = 0;
1121       }
1122       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1123 
1124       operator uint64_t&() { return Info.ArrayInitIndex; }
1125     };
1126   };
1127 
1128   /// Object used to treat all foldable expressions as constant expressions.
1129   struct FoldConstant {
1130     EvalInfo &Info;
1131     bool Enabled;
1132     bool HadNoPriorDiags;
1133     EvalInfo::EvaluationMode OldMode;
1134 
1135     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1136       : Info(Info),
1137         Enabled(Enabled),
1138         HadNoPriorDiags(Info.EvalStatus.Diag &&
1139                         Info.EvalStatus.Diag->empty() &&
1140                         !Info.EvalStatus.HasSideEffects),
1141         OldMode(Info.EvalMode) {
1142       if (Enabled &&
1143           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1144            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1145         Info.EvalMode = EvalInfo::EM_ConstantFold;
1146     }
1147     void keepDiagnostics() { Enabled = false; }
1148     ~FoldConstant() {
1149       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1150           !Info.EvalStatus.HasSideEffects)
1151         Info.EvalStatus.Diag->clear();
1152       Info.EvalMode = OldMode;
1153     }
1154   };
1155 
1156   /// RAII object used to set the current evaluation mode to ignore
1157   /// side-effects.
1158   struct IgnoreSideEffectsRAII {
1159     EvalInfo &Info;
1160     EvalInfo::EvaluationMode OldMode;
1161     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1162         : Info(Info), OldMode(Info.EvalMode) {
1163       if (!Info.checkingPotentialConstantExpression())
1164         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1165     }
1166 
1167     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1168   };
1169 
1170   /// RAII object used to optionally suppress diagnostics and side-effects from
1171   /// a speculative evaluation.
1172   class SpeculativeEvaluationRAII {
1173     EvalInfo *Info = nullptr;
1174     Expr::EvalStatus OldStatus;
1175     unsigned OldSpeculativeEvaluationDepth;
1176 
1177     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1178       Info = Other.Info;
1179       OldStatus = Other.OldStatus;
1180       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1181       Other.Info = nullptr;
1182     }
1183 
1184     void maybeRestoreState() {
1185       if (!Info)
1186         return;
1187 
1188       Info->EvalStatus = OldStatus;
1189       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1190     }
1191 
1192   public:
1193     SpeculativeEvaluationRAII() = default;
1194 
1195     SpeculativeEvaluationRAII(
1196         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1197         : Info(&Info), OldStatus(Info.EvalStatus),
1198           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1199       Info.EvalStatus.Diag = NewDiag;
1200       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1201     }
1202 
1203     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1204     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1205       moveFromAndCancel(std::move(Other));
1206     }
1207 
1208     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1209       maybeRestoreState();
1210       moveFromAndCancel(std::move(Other));
1211       return *this;
1212     }
1213 
1214     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1215   };
1216 
1217   /// RAII object wrapping a full-expression or block scope, and handling
1218   /// the ending of the lifetime of temporaries created within it.
1219   template<bool IsFullExpression>
1220   class ScopeRAII {
1221     EvalInfo &Info;
1222     unsigned OldStackSize;
1223   public:
1224     ScopeRAII(EvalInfo &Info)
1225         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1226       // Push a new temporary version. This is needed to distinguish between
1227       // temporaries created in different iterations of a loop.
1228       Info.CurrentCall->pushTempVersion();
1229     }
1230     ~ScopeRAII() {
1231       // Body moved to a static method to encourage the compiler to inline away
1232       // instances of this class.
1233       cleanup(Info, OldStackSize);
1234       Info.CurrentCall->popTempVersion();
1235     }
1236   private:
1237     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1238       unsigned NewEnd = OldStackSize;
1239       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1240            I != N; ++I) {
1241         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1242           // Full-expression cleanup of a lifetime-extended temporary: nothing
1243           // to do, just move this cleanup to the right place in the stack.
1244           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1245           ++NewEnd;
1246         } else {
1247           // End the lifetime of the object.
1248           Info.CleanupStack[I].endLifetime();
1249         }
1250       }
1251       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1252                               Info.CleanupStack.end());
1253     }
1254   };
1255   typedef ScopeRAII<false> BlockScopeRAII;
1256   typedef ScopeRAII<true> FullExpressionRAII;
1257 }
1258 
1259 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1260                                          CheckSubobjectKind CSK) {
1261   if (Invalid)
1262     return false;
1263   if (isOnePastTheEnd()) {
1264     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1265       << CSK;
1266     setInvalid();
1267     return false;
1268   }
1269   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1270   // must actually be at least one array element; even a VLA cannot have a
1271   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1272   return true;
1273 }
1274 
1275 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1276                                                                 const Expr *E) {
1277   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1278   // Do not set the designator as invalid: we can represent this situation,
1279   // and correct handling of __builtin_object_size requires us to do so.
1280 }
1281 
1282 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1283                                                     const Expr *E,
1284                                                     const APSInt &N) {
1285   // If we're complaining, we must be able to statically determine the size of
1286   // the most derived array.
1287   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1288     Info.CCEDiag(E, diag::note_constexpr_array_index)
1289       << N << /*array*/ 0
1290       << static_cast<unsigned>(getMostDerivedArraySize());
1291   else
1292     Info.CCEDiag(E, diag::note_constexpr_array_index)
1293       << N << /*non-array*/ 1;
1294   setInvalid();
1295 }
1296 
1297 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1298                                const FunctionDecl *Callee, const LValue *This,
1299                                APValue *Arguments)
1300     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1301       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1302   Info.CurrentCall = this;
1303   ++Info.CallStackDepth;
1304 }
1305 
1306 CallStackFrame::~CallStackFrame() {
1307   assert(Info.CurrentCall == this && "calls retired out of order");
1308   --Info.CallStackDepth;
1309   Info.CurrentCall = Caller;
1310 }
1311 
1312 APValue &CallStackFrame::createTemporary(const void *Key,
1313                                          bool IsLifetimeExtended) {
1314   unsigned Version = Info.CurrentCall->getTempVersion();
1315   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1316   assert(Result.isAbsent() && "temporary created multiple times");
1317   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1318   return Result;
1319 }
1320 
1321 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1322 
1323 void EvalInfo::addCallStack(unsigned Limit) {
1324   // Determine which calls to skip, if any.
1325   unsigned ActiveCalls = CallStackDepth - 1;
1326   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1327   if (Limit && Limit < ActiveCalls) {
1328     SkipStart = Limit / 2 + Limit % 2;
1329     SkipEnd = ActiveCalls - Limit / 2;
1330   }
1331 
1332   // Walk the call stack and add the diagnostics.
1333   unsigned CallIdx = 0;
1334   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1335        Frame = Frame->Caller, ++CallIdx) {
1336     // Skip this call?
1337     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1338       if (CallIdx == SkipStart) {
1339         // Note that we're skipping calls.
1340         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1341           << unsigned(ActiveCalls - Limit);
1342       }
1343       continue;
1344     }
1345 
1346     // Use a different note for an inheriting constructor, because from the
1347     // user's perspective it's not really a function at all.
1348     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1349       if (CD->isInheritingConstructor()) {
1350         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1351           << CD->getParent();
1352         continue;
1353       }
1354     }
1355 
1356     SmallVector<char, 128> Buffer;
1357     llvm::raw_svector_ostream Out(Buffer);
1358     describeCall(Frame, Out);
1359     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1360   }
1361 }
1362 
1363 /// Kinds of access we can perform on an object, for diagnostics. Note that
1364 /// we consider a member function call to be a kind of access, even though
1365 /// it is not formally an access of the object, because it has (largely) the
1366 /// same set of semantic restrictions.
1367 enum AccessKinds {
1368   AK_Read,
1369   AK_Assign,
1370   AK_Increment,
1371   AK_Decrement,
1372   AK_MemberCall,
1373   AK_DynamicCast,
1374   AK_TypeId,
1375 };
1376 
1377 static bool isModification(AccessKinds AK) {
1378   switch (AK) {
1379   case AK_Read:
1380   case AK_MemberCall:
1381   case AK_DynamicCast:
1382   case AK_TypeId:
1383     return false;
1384   case AK_Assign:
1385   case AK_Increment:
1386   case AK_Decrement:
1387     return true;
1388   }
1389   llvm_unreachable("unknown access kind");
1390 }
1391 
1392 /// Is this an access per the C++ definition?
1393 static bool isFormalAccess(AccessKinds AK) {
1394   return AK == AK_Read || isModification(AK);
1395 }
1396 
1397 namespace {
1398   struct ComplexValue {
1399   private:
1400     bool IsInt;
1401 
1402   public:
1403     APSInt IntReal, IntImag;
1404     APFloat FloatReal, FloatImag;
1405 
1406     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1407 
1408     void makeComplexFloat() { IsInt = false; }
1409     bool isComplexFloat() const { return !IsInt; }
1410     APFloat &getComplexFloatReal() { return FloatReal; }
1411     APFloat &getComplexFloatImag() { return FloatImag; }
1412 
1413     void makeComplexInt() { IsInt = true; }
1414     bool isComplexInt() const { return IsInt; }
1415     APSInt &getComplexIntReal() { return IntReal; }
1416     APSInt &getComplexIntImag() { return IntImag; }
1417 
1418     void moveInto(APValue &v) const {
1419       if (isComplexFloat())
1420         v = APValue(FloatReal, FloatImag);
1421       else
1422         v = APValue(IntReal, IntImag);
1423     }
1424     void setFrom(const APValue &v) {
1425       assert(v.isComplexFloat() || v.isComplexInt());
1426       if (v.isComplexFloat()) {
1427         makeComplexFloat();
1428         FloatReal = v.getComplexFloatReal();
1429         FloatImag = v.getComplexFloatImag();
1430       } else {
1431         makeComplexInt();
1432         IntReal = v.getComplexIntReal();
1433         IntImag = v.getComplexIntImag();
1434       }
1435     }
1436   };
1437 
1438   struct LValue {
1439     APValue::LValueBase Base;
1440     CharUnits Offset;
1441     SubobjectDesignator Designator;
1442     bool IsNullPtr : 1;
1443     bool InvalidBase : 1;
1444 
1445     const APValue::LValueBase getLValueBase() const { return Base; }
1446     CharUnits &getLValueOffset() { return Offset; }
1447     const CharUnits &getLValueOffset() const { return Offset; }
1448     SubobjectDesignator &getLValueDesignator() { return Designator; }
1449     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1450     bool isNullPointer() const { return IsNullPtr;}
1451 
1452     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1453     unsigned getLValueVersion() const { return Base.getVersion(); }
1454 
1455     void moveInto(APValue &V) const {
1456       if (Designator.Invalid)
1457         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1458       else {
1459         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1460         V = APValue(Base, Offset, Designator.Entries,
1461                     Designator.IsOnePastTheEnd, IsNullPtr);
1462       }
1463     }
1464     void setFrom(ASTContext &Ctx, const APValue &V) {
1465       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1466       Base = V.getLValueBase();
1467       Offset = V.getLValueOffset();
1468       InvalidBase = false;
1469       Designator = SubobjectDesignator(Ctx, V);
1470       IsNullPtr = V.isNullPointer();
1471     }
1472 
1473     void set(APValue::LValueBase B, bool BInvalid = false) {
1474 #ifndef NDEBUG
1475       // We only allow a few types of invalid bases. Enforce that here.
1476       if (BInvalid) {
1477         const auto *E = B.get<const Expr *>();
1478         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1479                "Unexpected type of invalid base");
1480       }
1481 #endif
1482 
1483       Base = B;
1484       Offset = CharUnits::fromQuantity(0);
1485       InvalidBase = BInvalid;
1486       Designator = SubobjectDesignator(getType(B));
1487       IsNullPtr = false;
1488     }
1489 
1490     void setNull(QualType PointerTy, uint64_t TargetVal) {
1491       Base = (Expr *)nullptr;
1492       Offset = CharUnits::fromQuantity(TargetVal);
1493       InvalidBase = false;
1494       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1495       IsNullPtr = true;
1496     }
1497 
1498     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1499       set(B, true);
1500     }
1501 
1502   private:
1503     // Check that this LValue is not based on a null pointer. If it is, produce
1504     // a diagnostic and mark the designator as invalid.
1505     template <typename GenDiagType>
1506     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1507       if (Designator.Invalid)
1508         return false;
1509       if (IsNullPtr) {
1510         GenDiag();
1511         Designator.setInvalid();
1512         return false;
1513       }
1514       return true;
1515     }
1516 
1517   public:
1518     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1519                           CheckSubobjectKind CSK) {
1520       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1521         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1522       });
1523     }
1524 
1525     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1526                                        AccessKinds AK) {
1527       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1528         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1529       });
1530     }
1531 
1532     // Check this LValue refers to an object. If not, set the designator to be
1533     // invalid and emit a diagnostic.
1534     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1535       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1536              Designator.checkSubobject(Info, E, CSK);
1537     }
1538 
1539     void addDecl(EvalInfo &Info, const Expr *E,
1540                  const Decl *D, bool Virtual = false) {
1541       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1542         Designator.addDeclUnchecked(D, Virtual);
1543     }
1544     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1545       if (!Designator.Entries.empty()) {
1546         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1547         Designator.setInvalid();
1548         return;
1549       }
1550       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1551         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1552         Designator.FirstEntryIsAnUnsizedArray = true;
1553         Designator.addUnsizedArrayUnchecked(ElemTy);
1554       }
1555     }
1556     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1557       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1558         Designator.addArrayUnchecked(CAT);
1559     }
1560     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1561       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1562         Designator.addComplexUnchecked(EltTy, Imag);
1563     }
1564     void clearIsNullPointer() {
1565       IsNullPtr = false;
1566     }
1567     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1568                               const APSInt &Index, CharUnits ElementSize) {
1569       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1570       // but we're not required to diagnose it and it's valid in C++.)
1571       if (!Index)
1572         return;
1573 
1574       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1575       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1576       // offsets.
1577       uint64_t Offset64 = Offset.getQuantity();
1578       uint64_t ElemSize64 = ElementSize.getQuantity();
1579       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1580       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1581 
1582       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1583         Designator.adjustIndex(Info, E, Index);
1584       clearIsNullPointer();
1585     }
1586     void adjustOffset(CharUnits N) {
1587       Offset += N;
1588       if (N.getQuantity())
1589         clearIsNullPointer();
1590     }
1591   };
1592 
1593   struct MemberPtr {
1594     MemberPtr() {}
1595     explicit MemberPtr(const ValueDecl *Decl) :
1596       DeclAndIsDerivedMember(Decl, false), Path() {}
1597 
1598     /// The member or (direct or indirect) field referred to by this member
1599     /// pointer, or 0 if this is a null member pointer.
1600     const ValueDecl *getDecl() const {
1601       return DeclAndIsDerivedMember.getPointer();
1602     }
1603     /// Is this actually a member of some type derived from the relevant class?
1604     bool isDerivedMember() const {
1605       return DeclAndIsDerivedMember.getInt();
1606     }
1607     /// Get the class which the declaration actually lives in.
1608     const CXXRecordDecl *getContainingRecord() const {
1609       return cast<CXXRecordDecl>(
1610           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1611     }
1612 
1613     void moveInto(APValue &V) const {
1614       V = APValue(getDecl(), isDerivedMember(), Path);
1615     }
1616     void setFrom(const APValue &V) {
1617       assert(V.isMemberPointer());
1618       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1619       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1620       Path.clear();
1621       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1622       Path.insert(Path.end(), P.begin(), P.end());
1623     }
1624 
1625     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1626     /// whether the member is a member of some class derived from the class type
1627     /// of the member pointer.
1628     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1629     /// Path - The path of base/derived classes from the member declaration's
1630     /// class (exclusive) to the class type of the member pointer (inclusive).
1631     SmallVector<const CXXRecordDecl*, 4> Path;
1632 
1633     /// Perform a cast towards the class of the Decl (either up or down the
1634     /// hierarchy).
1635     bool castBack(const CXXRecordDecl *Class) {
1636       assert(!Path.empty());
1637       const CXXRecordDecl *Expected;
1638       if (Path.size() >= 2)
1639         Expected = Path[Path.size() - 2];
1640       else
1641         Expected = getContainingRecord();
1642       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1643         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1644         // if B does not contain the original member and is not a base or
1645         // derived class of the class containing the original member, the result
1646         // of the cast is undefined.
1647         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1648         // (D::*). We consider that to be a language defect.
1649         return false;
1650       }
1651       Path.pop_back();
1652       return true;
1653     }
1654     /// Perform a base-to-derived member pointer cast.
1655     bool castToDerived(const CXXRecordDecl *Derived) {
1656       if (!getDecl())
1657         return true;
1658       if (!isDerivedMember()) {
1659         Path.push_back(Derived);
1660         return true;
1661       }
1662       if (!castBack(Derived))
1663         return false;
1664       if (Path.empty())
1665         DeclAndIsDerivedMember.setInt(false);
1666       return true;
1667     }
1668     /// Perform a derived-to-base member pointer cast.
1669     bool castToBase(const CXXRecordDecl *Base) {
1670       if (!getDecl())
1671         return true;
1672       if (Path.empty())
1673         DeclAndIsDerivedMember.setInt(true);
1674       if (isDerivedMember()) {
1675         Path.push_back(Base);
1676         return true;
1677       }
1678       return castBack(Base);
1679     }
1680   };
1681 
1682   /// Compare two member pointers, which are assumed to be of the same type.
1683   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1684     if (!LHS.getDecl() || !RHS.getDecl())
1685       return !LHS.getDecl() && !RHS.getDecl();
1686     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1687       return false;
1688     return LHS.Path == RHS.Path;
1689   }
1690 }
1691 
1692 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1693 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1694                             const LValue &This, const Expr *E,
1695                             bool AllowNonLiteralTypes = false);
1696 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1697                            bool InvalidBaseOK = false);
1698 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1699                             bool InvalidBaseOK = false);
1700 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1701                                   EvalInfo &Info);
1702 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1703 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1704 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1705                                     EvalInfo &Info);
1706 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1707 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1708 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1709                            EvalInfo &Info);
1710 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1711 
1712 /// Evaluate an integer or fixed point expression into an APResult.
1713 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1714                                         EvalInfo &Info);
1715 
1716 /// Evaluate only a fixed point expression into an APResult.
1717 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1718                                EvalInfo &Info);
1719 
1720 //===----------------------------------------------------------------------===//
1721 // Misc utilities
1722 //===----------------------------------------------------------------------===//
1723 
1724 /// A helper function to create a temporary and set an LValue.
1725 template <class KeyTy>
1726 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1727                                 LValue &LV, CallStackFrame &Frame) {
1728   LV.set({Key, Frame.Info.CurrentCall->Index,
1729           Frame.Info.CurrentCall->getTempVersion()});
1730   return Frame.createTemporary(Key, IsLifetimeExtended);
1731 }
1732 
1733 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1734 /// preserving its value (by extending by up to one bit as needed).
1735 static void negateAsSigned(APSInt &Int) {
1736   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1737     Int = Int.extend(Int.getBitWidth() + 1);
1738     Int.setIsSigned(true);
1739   }
1740   Int = -Int;
1741 }
1742 
1743 /// Produce a string describing the given constexpr call.
1744 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1745   unsigned ArgIndex = 0;
1746   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1747                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1748                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1749 
1750   if (!IsMemberCall)
1751     Out << *Frame->Callee << '(';
1752 
1753   if (Frame->This && IsMemberCall) {
1754     APValue Val;
1755     Frame->This->moveInto(Val);
1756     Val.printPretty(Out, Frame->Info.Ctx,
1757                     Frame->This->Designator.MostDerivedType);
1758     // FIXME: Add parens around Val if needed.
1759     Out << "->" << *Frame->Callee << '(';
1760     IsMemberCall = false;
1761   }
1762 
1763   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1764        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1765     if (ArgIndex > (unsigned)IsMemberCall)
1766       Out << ", ";
1767 
1768     const ParmVarDecl *Param = *I;
1769     const APValue &Arg = Frame->Arguments[ArgIndex];
1770     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1771 
1772     if (ArgIndex == 0 && IsMemberCall)
1773       Out << "->" << *Frame->Callee << '(';
1774   }
1775 
1776   Out << ')';
1777 }
1778 
1779 /// Evaluate an expression to see if it had side-effects, and discard its
1780 /// result.
1781 /// \return \c true if the caller should keep evaluating.
1782 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1783   APValue Scratch;
1784   if (!Evaluate(Scratch, Info, E))
1785     // We don't need the value, but we might have skipped a side effect here.
1786     return Info.noteSideEffect();
1787   return true;
1788 }
1789 
1790 /// Should this call expression be treated as a string literal?
1791 static bool IsStringLiteralCall(const CallExpr *E) {
1792   unsigned Builtin = E->getBuiltinCallee();
1793   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1794           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1795 }
1796 
1797 static bool IsGlobalLValue(APValue::LValueBase B) {
1798   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1799   // constant expression of pointer type that evaluates to...
1800 
1801   // ... a null pointer value, or a prvalue core constant expression of type
1802   // std::nullptr_t.
1803   if (!B) return true;
1804 
1805   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1806     // ... the address of an object with static storage duration,
1807     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1808       return VD->hasGlobalStorage();
1809     // ... the address of a function,
1810     return isa<FunctionDecl>(D);
1811   }
1812 
1813   if (B.is<TypeInfoLValue>())
1814     return true;
1815 
1816   const Expr *E = B.get<const Expr*>();
1817   switch (E->getStmtClass()) {
1818   default:
1819     return false;
1820   case Expr::CompoundLiteralExprClass: {
1821     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1822     return CLE->isFileScope() && CLE->isLValue();
1823   }
1824   case Expr::MaterializeTemporaryExprClass:
1825     // A materialized temporary might have been lifetime-extended to static
1826     // storage duration.
1827     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1828   // A string literal has static storage duration.
1829   case Expr::StringLiteralClass:
1830   case Expr::PredefinedExprClass:
1831   case Expr::ObjCStringLiteralClass:
1832   case Expr::ObjCEncodeExprClass:
1833   case Expr::CXXUuidofExprClass:
1834     return true;
1835   case Expr::ObjCBoxedExprClass:
1836     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1837   case Expr::CallExprClass:
1838     return IsStringLiteralCall(cast<CallExpr>(E));
1839   // For GCC compatibility, &&label has static storage duration.
1840   case Expr::AddrLabelExprClass:
1841     return true;
1842   // A Block literal expression may be used as the initialization value for
1843   // Block variables at global or local static scope.
1844   case Expr::BlockExprClass:
1845     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1846   case Expr::ImplicitValueInitExprClass:
1847     // FIXME:
1848     // We can never form an lvalue with an implicit value initialization as its
1849     // base through expression evaluation, so these only appear in one case: the
1850     // implicit variable declaration we invent when checking whether a constexpr
1851     // constructor can produce a constant expression. We must assume that such
1852     // an expression might be a global lvalue.
1853     return true;
1854   }
1855 }
1856 
1857 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1858   return LVal.Base.dyn_cast<const ValueDecl*>();
1859 }
1860 
1861 static bool IsLiteralLValue(const LValue &Value) {
1862   if (Value.getLValueCallIndex())
1863     return false;
1864   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1865   return E && !isa<MaterializeTemporaryExpr>(E);
1866 }
1867 
1868 static bool IsWeakLValue(const LValue &Value) {
1869   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1870   return Decl && Decl->isWeak();
1871 }
1872 
1873 static bool isZeroSized(const LValue &Value) {
1874   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1875   if (Decl && isa<VarDecl>(Decl)) {
1876     QualType Ty = Decl->getType();
1877     if (Ty->isArrayType())
1878       return Ty->isIncompleteType() ||
1879              Decl->getASTContext().getTypeSize(Ty) == 0;
1880   }
1881   return false;
1882 }
1883 
1884 static bool HasSameBase(const LValue &A, const LValue &B) {
1885   if (!A.getLValueBase())
1886     return !B.getLValueBase();
1887   if (!B.getLValueBase())
1888     return false;
1889 
1890   if (A.getLValueBase().getOpaqueValue() !=
1891       B.getLValueBase().getOpaqueValue()) {
1892     const Decl *ADecl = GetLValueBaseDecl(A);
1893     if (!ADecl)
1894       return false;
1895     const Decl *BDecl = GetLValueBaseDecl(B);
1896     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1897       return false;
1898   }
1899 
1900   return IsGlobalLValue(A.getLValueBase()) ||
1901          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1902           A.getLValueVersion() == B.getLValueVersion());
1903 }
1904 
1905 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1906   assert(Base && "no location for a null lvalue");
1907   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1908   if (VD)
1909     Info.Note(VD->getLocation(), diag::note_declared_at);
1910   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1911     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1912   // We have no information to show for a typeid(T) object.
1913 }
1914 
1915 /// Check that this reference or pointer core constant expression is a valid
1916 /// value for an address or reference constant expression. Return true if we
1917 /// can fold this expression, whether or not it's a constant expression.
1918 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1919                                           QualType Type, const LValue &LVal,
1920                                           Expr::ConstExprUsage Usage) {
1921   bool IsReferenceType = Type->isReferenceType();
1922 
1923   APValue::LValueBase Base = LVal.getLValueBase();
1924   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1925 
1926   // Check that the object is a global. Note that the fake 'this' object we
1927   // manufacture when checking potential constant expressions is conservatively
1928   // assumed to be global here.
1929   if (!IsGlobalLValue(Base)) {
1930     if (Info.getLangOpts().CPlusPlus11) {
1931       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1932       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1933         << IsReferenceType << !Designator.Entries.empty()
1934         << !!VD << VD;
1935       NoteLValueLocation(Info, Base);
1936     } else {
1937       Info.FFDiag(Loc);
1938     }
1939     // Don't allow references to temporaries to escape.
1940     return false;
1941   }
1942   assert((Info.checkingPotentialConstantExpression() ||
1943           LVal.getLValueCallIndex() == 0) &&
1944          "have call index for global lvalue");
1945 
1946   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1947     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1948       // Check if this is a thread-local variable.
1949       if (Var->getTLSKind())
1950         return false;
1951 
1952       // A dllimport variable never acts like a constant.
1953       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1954         return false;
1955     }
1956     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1957       // __declspec(dllimport) must be handled very carefully:
1958       // We must never initialize an expression with the thunk in C++.
1959       // Doing otherwise would allow the same id-expression to yield
1960       // different addresses for the same function in different translation
1961       // units.  However, this means that we must dynamically initialize the
1962       // expression with the contents of the import address table at runtime.
1963       //
1964       // The C language has no notion of ODR; furthermore, it has no notion of
1965       // dynamic initialization.  This means that we are permitted to
1966       // perform initialization with the address of the thunk.
1967       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1968           FD->hasAttr<DLLImportAttr>())
1969         return false;
1970     }
1971   }
1972 
1973   // Allow address constant expressions to be past-the-end pointers. This is
1974   // an extension: the standard requires them to point to an object.
1975   if (!IsReferenceType)
1976     return true;
1977 
1978   // A reference constant expression must refer to an object.
1979   if (!Base) {
1980     // FIXME: diagnostic
1981     Info.CCEDiag(Loc);
1982     return true;
1983   }
1984 
1985   // Does this refer one past the end of some object?
1986   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1987     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1988     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1989       << !Designator.Entries.empty() << !!VD << VD;
1990     NoteLValueLocation(Info, Base);
1991   }
1992 
1993   return true;
1994 }
1995 
1996 /// Member pointers are constant expressions unless they point to a
1997 /// non-virtual dllimport member function.
1998 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1999                                                  SourceLocation Loc,
2000                                                  QualType Type,
2001                                                  const APValue &Value,
2002                                                  Expr::ConstExprUsage Usage) {
2003   const ValueDecl *Member = Value.getMemberPointerDecl();
2004   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2005   if (!FD)
2006     return true;
2007   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2008          !FD->hasAttr<DLLImportAttr>();
2009 }
2010 
2011 /// Check that this core constant expression is of literal type, and if not,
2012 /// produce an appropriate diagnostic.
2013 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2014                              const LValue *This = nullptr) {
2015   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2016     return true;
2017 
2018   // C++1y: A constant initializer for an object o [...] may also invoke
2019   // constexpr constructors for o and its subobjects even if those objects
2020   // are of non-literal class types.
2021   //
2022   // C++11 missed this detail for aggregates, so classes like this:
2023   //   struct foo_t { union { int i; volatile int j; } u; };
2024   // are not (obviously) initializable like so:
2025   //   __attribute__((__require_constant_initialization__))
2026   //   static const foo_t x = {{0}};
2027   // because "i" is a subobject with non-literal initialization (due to the
2028   // volatile member of the union). See:
2029   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2030   // Therefore, we use the C++1y behavior.
2031   if (This && Info.EvaluatingDecl == This->getLValueBase())
2032     return true;
2033 
2034   // Prvalue constant expressions must be of literal types.
2035   if (Info.getLangOpts().CPlusPlus11)
2036     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2037       << E->getType();
2038   else
2039     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2040   return false;
2041 }
2042 
2043 /// Check that this core constant expression value is a valid value for a
2044 /// constant expression. If not, report an appropriate diagnostic. Does not
2045 /// check that the expression is of literal type.
2046 static bool
2047 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2048                         const APValue &Value,
2049                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2050                         SourceLocation SubobjectLoc = SourceLocation()) {
2051   if (!Value.hasValue()) {
2052     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2053       << true << Type;
2054     if (SubobjectLoc.isValid())
2055       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2056     return false;
2057   }
2058 
2059   // We allow _Atomic(T) to be initialized from anything that T can be
2060   // initialized from.
2061   if (const AtomicType *AT = Type->getAs<AtomicType>())
2062     Type = AT->getValueType();
2063 
2064   // Core issue 1454: For a literal constant expression of array or class type,
2065   // each subobject of its value shall have been initialized by a constant
2066   // expression.
2067   if (Value.isArray()) {
2068     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2069     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2070       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2071                                    Value.getArrayInitializedElt(I), Usage,
2072                                    SubobjectLoc))
2073         return false;
2074     }
2075     if (!Value.hasArrayFiller())
2076       return true;
2077     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2078                                    Usage, SubobjectLoc);
2079   }
2080   if (Value.isUnion() && Value.getUnionField()) {
2081     return CheckConstantExpression(Info, DiagLoc,
2082                                    Value.getUnionField()->getType(),
2083                                    Value.getUnionValue(), Usage,
2084                                    Value.getUnionField()->getLocation());
2085   }
2086   if (Value.isStruct()) {
2087     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2088     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2089       unsigned BaseIndex = 0;
2090       for (const CXXBaseSpecifier &BS : CD->bases()) {
2091         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2092                                      Value.getStructBase(BaseIndex), Usage,
2093                                      BS.getBeginLoc()))
2094           return false;
2095         ++BaseIndex;
2096       }
2097     }
2098     for (const auto *I : RD->fields()) {
2099       if (I->isUnnamedBitfield())
2100         continue;
2101 
2102       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2103                                    Value.getStructField(I->getFieldIndex()),
2104                                    Usage, I->getLocation()))
2105         return false;
2106     }
2107   }
2108 
2109   if (Value.isLValue()) {
2110     LValue LVal;
2111     LVal.setFrom(Info.Ctx, Value);
2112     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2113   }
2114 
2115   if (Value.isMemberPointer())
2116     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2117 
2118   // Everything else is fine.
2119   return true;
2120 }
2121 
2122 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2123   // A null base expression indicates a null pointer.  These are always
2124   // evaluatable, and they are false unless the offset is zero.
2125   if (!Value.getLValueBase()) {
2126     Result = !Value.getLValueOffset().isZero();
2127     return true;
2128   }
2129 
2130   // We have a non-null base.  These are generally known to be true, but if it's
2131   // a weak declaration it can be null at runtime.
2132   Result = true;
2133   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2134   return !Decl || !Decl->isWeak();
2135 }
2136 
2137 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2138   switch (Val.getKind()) {
2139   case APValue::None:
2140   case APValue::Indeterminate:
2141     return false;
2142   case APValue::Int:
2143     Result = Val.getInt().getBoolValue();
2144     return true;
2145   case APValue::FixedPoint:
2146     Result = Val.getFixedPoint().getBoolValue();
2147     return true;
2148   case APValue::Float:
2149     Result = !Val.getFloat().isZero();
2150     return true;
2151   case APValue::ComplexInt:
2152     Result = Val.getComplexIntReal().getBoolValue() ||
2153              Val.getComplexIntImag().getBoolValue();
2154     return true;
2155   case APValue::ComplexFloat:
2156     Result = !Val.getComplexFloatReal().isZero() ||
2157              !Val.getComplexFloatImag().isZero();
2158     return true;
2159   case APValue::LValue:
2160     return EvalPointerValueAsBool(Val, Result);
2161   case APValue::MemberPointer:
2162     Result = Val.getMemberPointerDecl();
2163     return true;
2164   case APValue::Vector:
2165   case APValue::Array:
2166   case APValue::Struct:
2167   case APValue::Union:
2168   case APValue::AddrLabelDiff:
2169     return false;
2170   }
2171 
2172   llvm_unreachable("unknown APValue kind");
2173 }
2174 
2175 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2176                                        EvalInfo &Info) {
2177   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2178   APValue Val;
2179   if (!Evaluate(Val, Info, E))
2180     return false;
2181   return HandleConversionToBool(Val, Result);
2182 }
2183 
2184 template<typename T>
2185 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2186                            const T &SrcValue, QualType DestType) {
2187   Info.CCEDiag(E, diag::note_constexpr_overflow)
2188     << SrcValue << DestType;
2189   return Info.noteUndefinedBehavior();
2190 }
2191 
2192 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2193                                  QualType SrcType, const APFloat &Value,
2194                                  QualType DestType, APSInt &Result) {
2195   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2196   // Determine whether we are converting to unsigned or signed.
2197   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2198 
2199   Result = APSInt(DestWidth, !DestSigned);
2200   bool ignored;
2201   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2202       & APFloat::opInvalidOp)
2203     return HandleOverflow(Info, E, Value, DestType);
2204   return true;
2205 }
2206 
2207 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2208                                    QualType SrcType, QualType DestType,
2209                                    APFloat &Result) {
2210   APFloat Value = Result;
2211   bool ignored;
2212   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2213                      APFloat::rmNearestTiesToEven, &ignored)
2214       & APFloat::opOverflow)
2215     return HandleOverflow(Info, E, Value, DestType);
2216   return true;
2217 }
2218 
2219 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2220                                  QualType DestType, QualType SrcType,
2221                                  const APSInt &Value) {
2222   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2223   // Figure out if this is a truncate, extend or noop cast.
2224   // If the input is signed, do a sign extend, noop, or truncate.
2225   APSInt Result = Value.extOrTrunc(DestWidth);
2226   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2227   if (DestType->isBooleanType())
2228     Result = Value.getBoolValue();
2229   return Result;
2230 }
2231 
2232 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2233                                  QualType SrcType, const APSInt &Value,
2234                                  QualType DestType, APFloat &Result) {
2235   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2236   if (Result.convertFromAPInt(Value, Value.isSigned(),
2237                               APFloat::rmNearestTiesToEven)
2238       & APFloat::opOverflow)
2239     return HandleOverflow(Info, E, Value, DestType);
2240   return true;
2241 }
2242 
2243 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2244                                   APValue &Value, const FieldDecl *FD) {
2245   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2246 
2247   if (!Value.isInt()) {
2248     // Trying to store a pointer-cast-to-integer into a bitfield.
2249     // FIXME: In this case, we should provide the diagnostic for casting
2250     // a pointer to an integer.
2251     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2252     Info.FFDiag(E);
2253     return false;
2254   }
2255 
2256   APSInt &Int = Value.getInt();
2257   unsigned OldBitWidth = Int.getBitWidth();
2258   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2259   if (NewBitWidth < OldBitWidth)
2260     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2261   return true;
2262 }
2263 
2264 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2265                                   llvm::APInt &Res) {
2266   APValue SVal;
2267   if (!Evaluate(SVal, Info, E))
2268     return false;
2269   if (SVal.isInt()) {
2270     Res = SVal.getInt();
2271     return true;
2272   }
2273   if (SVal.isFloat()) {
2274     Res = SVal.getFloat().bitcastToAPInt();
2275     return true;
2276   }
2277   if (SVal.isVector()) {
2278     QualType VecTy = E->getType();
2279     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2280     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2281     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2282     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2283     Res = llvm::APInt::getNullValue(VecSize);
2284     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2285       APValue &Elt = SVal.getVectorElt(i);
2286       llvm::APInt EltAsInt;
2287       if (Elt.isInt()) {
2288         EltAsInt = Elt.getInt();
2289       } else if (Elt.isFloat()) {
2290         EltAsInt = Elt.getFloat().bitcastToAPInt();
2291       } else {
2292         // Don't try to handle vectors of anything other than int or float
2293         // (not sure if it's possible to hit this case).
2294         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2295         return false;
2296       }
2297       unsigned BaseEltSize = EltAsInt.getBitWidth();
2298       if (BigEndian)
2299         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2300       else
2301         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2302     }
2303     return true;
2304   }
2305   // Give up if the input isn't an int, float, or vector.  For example, we
2306   // reject "(v4i16)(intptr_t)&a".
2307   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2308   return false;
2309 }
2310 
2311 /// Perform the given integer operation, which is known to need at most BitWidth
2312 /// bits, and check for overflow in the original type (if that type was not an
2313 /// unsigned type).
2314 template<typename Operation>
2315 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2316                                  const APSInt &LHS, const APSInt &RHS,
2317                                  unsigned BitWidth, Operation Op,
2318                                  APSInt &Result) {
2319   if (LHS.isUnsigned()) {
2320     Result = Op(LHS, RHS);
2321     return true;
2322   }
2323 
2324   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2325   Result = Value.trunc(LHS.getBitWidth());
2326   if (Result.extend(BitWidth) != Value) {
2327     if (Info.checkingForOverflow())
2328       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2329                                        diag::warn_integer_constant_overflow)
2330           << Result.toString(10) << E->getType();
2331     else
2332       return HandleOverflow(Info, E, Value, E->getType());
2333   }
2334   return true;
2335 }
2336 
2337 /// Perform the given binary integer operation.
2338 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2339                               BinaryOperatorKind Opcode, APSInt RHS,
2340                               APSInt &Result) {
2341   switch (Opcode) {
2342   default:
2343     Info.FFDiag(E);
2344     return false;
2345   case BO_Mul:
2346     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2347                                 std::multiplies<APSInt>(), Result);
2348   case BO_Add:
2349     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2350                                 std::plus<APSInt>(), Result);
2351   case BO_Sub:
2352     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2353                                 std::minus<APSInt>(), Result);
2354   case BO_And: Result = LHS & RHS; return true;
2355   case BO_Xor: Result = LHS ^ RHS; return true;
2356   case BO_Or:  Result = LHS | RHS; return true;
2357   case BO_Div:
2358   case BO_Rem:
2359     if (RHS == 0) {
2360       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2361       return false;
2362     }
2363     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2364     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2365     // this operation and gives the two's complement result.
2366     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2367         LHS.isSigned() && LHS.isMinSignedValue())
2368       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2369                             E->getType());
2370     return true;
2371   case BO_Shl: {
2372     if (Info.getLangOpts().OpenCL)
2373       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2374       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2375                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2376                     RHS.isUnsigned());
2377     else if (RHS.isSigned() && RHS.isNegative()) {
2378       // During constant-folding, a negative shift is an opposite shift. Such
2379       // a shift is not a constant expression.
2380       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2381       RHS = -RHS;
2382       goto shift_right;
2383     }
2384   shift_left:
2385     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2386     // the shifted type.
2387     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2388     if (SA != RHS) {
2389       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2390         << RHS << E->getType() << LHS.getBitWidth();
2391     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2392       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2393       // operand, and must not overflow the corresponding unsigned type.
2394       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2395       // E1 x 2^E2 module 2^N.
2396       if (LHS.isNegative())
2397         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2398       else if (LHS.countLeadingZeros() < SA)
2399         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2400     }
2401     Result = LHS << SA;
2402     return true;
2403   }
2404   case BO_Shr: {
2405     if (Info.getLangOpts().OpenCL)
2406       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2407       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2408                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2409                     RHS.isUnsigned());
2410     else if (RHS.isSigned() && RHS.isNegative()) {
2411       // During constant-folding, a negative shift is an opposite shift. Such a
2412       // shift is not a constant expression.
2413       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2414       RHS = -RHS;
2415       goto shift_left;
2416     }
2417   shift_right:
2418     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2419     // shifted type.
2420     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2421     if (SA != RHS)
2422       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2423         << RHS << E->getType() << LHS.getBitWidth();
2424     Result = LHS >> SA;
2425     return true;
2426   }
2427 
2428   case BO_LT: Result = LHS < RHS; return true;
2429   case BO_GT: Result = LHS > RHS; return true;
2430   case BO_LE: Result = LHS <= RHS; return true;
2431   case BO_GE: Result = LHS >= RHS; return true;
2432   case BO_EQ: Result = LHS == RHS; return true;
2433   case BO_NE: Result = LHS != RHS; return true;
2434   case BO_Cmp:
2435     llvm_unreachable("BO_Cmp should be handled elsewhere");
2436   }
2437 }
2438 
2439 /// Perform the given binary floating-point operation, in-place, on LHS.
2440 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2441                                   APFloat &LHS, BinaryOperatorKind Opcode,
2442                                   const APFloat &RHS) {
2443   switch (Opcode) {
2444   default:
2445     Info.FFDiag(E);
2446     return false;
2447   case BO_Mul:
2448     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2449     break;
2450   case BO_Add:
2451     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2452     break;
2453   case BO_Sub:
2454     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2455     break;
2456   case BO_Div:
2457     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2458     break;
2459   }
2460 
2461   if (LHS.isInfinity() || LHS.isNaN()) {
2462     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2463     return Info.noteUndefinedBehavior();
2464   }
2465   return true;
2466 }
2467 
2468 /// Cast an lvalue referring to a base subobject to a derived class, by
2469 /// truncating the lvalue's path to the given length.
2470 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2471                                const RecordDecl *TruncatedType,
2472                                unsigned TruncatedElements) {
2473   SubobjectDesignator &D = Result.Designator;
2474 
2475   // Check we actually point to a derived class object.
2476   if (TruncatedElements == D.Entries.size())
2477     return true;
2478   assert(TruncatedElements >= D.MostDerivedPathLength &&
2479          "not casting to a derived class");
2480   if (!Result.checkSubobject(Info, E, CSK_Derived))
2481     return false;
2482 
2483   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2484   const RecordDecl *RD = TruncatedType;
2485   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2486     if (RD->isInvalidDecl()) return false;
2487     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2488     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2489     if (isVirtualBaseClass(D.Entries[I]))
2490       Result.Offset -= Layout.getVBaseClassOffset(Base);
2491     else
2492       Result.Offset -= Layout.getBaseClassOffset(Base);
2493     RD = Base;
2494   }
2495   D.Entries.resize(TruncatedElements);
2496   return true;
2497 }
2498 
2499 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2500                                    const CXXRecordDecl *Derived,
2501                                    const CXXRecordDecl *Base,
2502                                    const ASTRecordLayout *RL = nullptr) {
2503   if (!RL) {
2504     if (Derived->isInvalidDecl()) return false;
2505     RL = &Info.Ctx.getASTRecordLayout(Derived);
2506   }
2507 
2508   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2509   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2510   return true;
2511 }
2512 
2513 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2514                              const CXXRecordDecl *DerivedDecl,
2515                              const CXXBaseSpecifier *Base) {
2516   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2517 
2518   if (!Base->isVirtual())
2519     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2520 
2521   SubobjectDesignator &D = Obj.Designator;
2522   if (D.Invalid)
2523     return false;
2524 
2525   // Extract most-derived object and corresponding type.
2526   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2527   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2528     return false;
2529 
2530   // Find the virtual base class.
2531   if (DerivedDecl->isInvalidDecl()) return false;
2532   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2533   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2534   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2535   return true;
2536 }
2537 
2538 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2539                                  QualType Type, LValue &Result) {
2540   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2541                                      PathE = E->path_end();
2542        PathI != PathE; ++PathI) {
2543     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2544                           *PathI))
2545       return false;
2546     Type = (*PathI)->getType();
2547   }
2548   return true;
2549 }
2550 
2551 /// Cast an lvalue referring to a derived class to a known base subobject.
2552 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2553                             const CXXRecordDecl *DerivedRD,
2554                             const CXXRecordDecl *BaseRD) {
2555   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2556                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2557   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2558     llvm_unreachable("Class must be derived from the passed in base class!");
2559 
2560   for (CXXBasePathElement &Elem : Paths.front())
2561     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2562       return false;
2563   return true;
2564 }
2565 
2566 /// Update LVal to refer to the given field, which must be a member of the type
2567 /// currently described by LVal.
2568 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2569                                const FieldDecl *FD,
2570                                const ASTRecordLayout *RL = nullptr) {
2571   if (!RL) {
2572     if (FD->getParent()->isInvalidDecl()) return false;
2573     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2574   }
2575 
2576   unsigned I = FD->getFieldIndex();
2577   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2578   LVal.addDecl(Info, E, FD);
2579   return true;
2580 }
2581 
2582 /// Update LVal to refer to the given indirect field.
2583 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2584                                        LValue &LVal,
2585                                        const IndirectFieldDecl *IFD) {
2586   for (const auto *C : IFD->chain())
2587     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2588       return false;
2589   return true;
2590 }
2591 
2592 /// Get the size of the given type in char units.
2593 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2594                          QualType Type, CharUnits &Size) {
2595   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2596   // extension.
2597   if (Type->isVoidType() || Type->isFunctionType()) {
2598     Size = CharUnits::One();
2599     return true;
2600   }
2601 
2602   if (Type->isDependentType()) {
2603     Info.FFDiag(Loc);
2604     return false;
2605   }
2606 
2607   if (!Type->isConstantSizeType()) {
2608     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2609     // FIXME: Better diagnostic.
2610     Info.FFDiag(Loc);
2611     return false;
2612   }
2613 
2614   Size = Info.Ctx.getTypeSizeInChars(Type);
2615   return true;
2616 }
2617 
2618 /// Update a pointer value to model pointer arithmetic.
2619 /// \param Info - Information about the ongoing evaluation.
2620 /// \param E - The expression being evaluated, for diagnostic purposes.
2621 /// \param LVal - The pointer value to be updated.
2622 /// \param EltTy - The pointee type represented by LVal.
2623 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2624 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2625                                         LValue &LVal, QualType EltTy,
2626                                         APSInt Adjustment) {
2627   CharUnits SizeOfPointee;
2628   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2629     return false;
2630 
2631   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2632   return true;
2633 }
2634 
2635 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2636                                         LValue &LVal, QualType EltTy,
2637                                         int64_t Adjustment) {
2638   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2639                                      APSInt::get(Adjustment));
2640 }
2641 
2642 /// Update an lvalue to refer to a component of a complex number.
2643 /// \param Info - Information about the ongoing evaluation.
2644 /// \param LVal - The lvalue to be updated.
2645 /// \param EltTy - The complex number's component type.
2646 /// \param Imag - False for the real component, true for the imaginary.
2647 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2648                                        LValue &LVal, QualType EltTy,
2649                                        bool Imag) {
2650   if (Imag) {
2651     CharUnits SizeOfComponent;
2652     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2653       return false;
2654     LVal.Offset += SizeOfComponent;
2655   }
2656   LVal.addComplex(Info, E, EltTy, Imag);
2657   return true;
2658 }
2659 
2660 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2661                                            QualType Type, const LValue &LVal,
2662                                            APValue &RVal);
2663 
2664 /// Try to evaluate the initializer for a variable declaration.
2665 ///
2666 /// \param Info   Information about the ongoing evaluation.
2667 /// \param E      An expression to be used when printing diagnostics.
2668 /// \param VD     The variable whose initializer should be obtained.
2669 /// \param Frame  The frame in which the variable was created. Must be null
2670 ///               if this variable is not local to the evaluation.
2671 /// \param Result Filled in with a pointer to the value of the variable.
2672 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2673                                 const VarDecl *VD, CallStackFrame *Frame,
2674                                 APValue *&Result, const LValue *LVal) {
2675 
2676   // If this is a parameter to an active constexpr function call, perform
2677   // argument substitution.
2678   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2679     // Assume arguments of a potential constant expression are unknown
2680     // constant expressions.
2681     if (Info.checkingPotentialConstantExpression())
2682       return false;
2683     if (!Frame || !Frame->Arguments) {
2684       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2685       return false;
2686     }
2687     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2688     return true;
2689   }
2690 
2691   // If this is a local variable, dig out its value.
2692   if (Frame) {
2693     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2694                   : Frame->getCurrentTemporary(VD);
2695     if (!Result) {
2696       // Assume variables referenced within a lambda's call operator that were
2697       // not declared within the call operator are captures and during checking
2698       // of a potential constant expression, assume they are unknown constant
2699       // expressions.
2700       assert(isLambdaCallOperator(Frame->Callee) &&
2701              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2702              "missing value for local variable");
2703       if (Info.checkingPotentialConstantExpression())
2704         return false;
2705       // FIXME: implement capture evaluation during constant expr evaluation.
2706       Info.FFDiag(E->getBeginLoc(),
2707                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2708           << "captures not currently allowed";
2709       return false;
2710     }
2711     return true;
2712   }
2713 
2714   // Dig out the initializer, and use the declaration which it's attached to.
2715   const Expr *Init = VD->getAnyInitializer(VD);
2716   if (!Init || Init->isValueDependent()) {
2717     // If we're checking a potential constant expression, the variable could be
2718     // initialized later.
2719     if (!Info.checkingPotentialConstantExpression())
2720       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2721     return false;
2722   }
2723 
2724   // If we're currently evaluating the initializer of this declaration, use that
2725   // in-flight value.
2726   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2727     Result = Info.EvaluatingDeclValue;
2728     return true;
2729   }
2730 
2731   // Never evaluate the initializer of a weak variable. We can't be sure that
2732   // this is the definition which will be used.
2733   if (VD->isWeak()) {
2734     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2735     return false;
2736   }
2737 
2738   // Check that we can fold the initializer. In C++, we will have already done
2739   // this in the cases where it matters for conformance.
2740   SmallVector<PartialDiagnosticAt, 8> Notes;
2741   if (!VD->evaluateValue(Notes)) {
2742     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2743               Notes.size() + 1) << VD;
2744     Info.Note(VD->getLocation(), diag::note_declared_at);
2745     Info.addNotes(Notes);
2746     return false;
2747   } else if (!VD->checkInitIsICE()) {
2748     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2749                  Notes.size() + 1) << VD;
2750     Info.Note(VD->getLocation(), diag::note_declared_at);
2751     Info.addNotes(Notes);
2752   }
2753 
2754   Result = VD->getEvaluatedValue();
2755   return true;
2756 }
2757 
2758 static bool IsConstNonVolatile(QualType T) {
2759   Qualifiers Quals = T.getQualifiers();
2760   return Quals.hasConst() && !Quals.hasVolatile();
2761 }
2762 
2763 /// Get the base index of the given base class within an APValue representing
2764 /// the given derived class.
2765 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2766                              const CXXRecordDecl *Base) {
2767   Base = Base->getCanonicalDecl();
2768   unsigned Index = 0;
2769   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2770          E = Derived->bases_end(); I != E; ++I, ++Index) {
2771     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2772       return Index;
2773   }
2774 
2775   llvm_unreachable("base class missing from derived class's bases list");
2776 }
2777 
2778 /// Extract the value of a character from a string literal.
2779 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2780                                             uint64_t Index) {
2781   assert(!isa<SourceLocExpr>(Lit) &&
2782          "SourceLocExpr should have already been converted to a StringLiteral");
2783 
2784   // FIXME: Support MakeStringConstant
2785   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2786     std::string Str;
2787     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2788     assert(Index <= Str.size() && "Index too large");
2789     return APSInt::getUnsigned(Str.c_str()[Index]);
2790   }
2791 
2792   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2793     Lit = PE->getFunctionName();
2794   const StringLiteral *S = cast<StringLiteral>(Lit);
2795   const ConstantArrayType *CAT =
2796       Info.Ctx.getAsConstantArrayType(S->getType());
2797   assert(CAT && "string literal isn't an array");
2798   QualType CharType = CAT->getElementType();
2799   assert(CharType->isIntegerType() && "unexpected character type");
2800 
2801   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2802                CharType->isUnsignedIntegerType());
2803   if (Index < S->getLength())
2804     Value = S->getCodeUnit(Index);
2805   return Value;
2806 }
2807 
2808 // Expand a string literal into an array of characters.
2809 //
2810 // FIXME: This is inefficient; we should probably introduce something similar
2811 // to the LLVM ConstantDataArray to make this cheaper.
2812 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2813                                 APValue &Result) {
2814   const ConstantArrayType *CAT =
2815       Info.Ctx.getAsConstantArrayType(S->getType());
2816   assert(CAT && "string literal isn't an array");
2817   QualType CharType = CAT->getElementType();
2818   assert(CharType->isIntegerType() && "unexpected character type");
2819 
2820   unsigned Elts = CAT->getSize().getZExtValue();
2821   Result = APValue(APValue::UninitArray(),
2822                    std::min(S->getLength(), Elts), Elts);
2823   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2824                CharType->isUnsignedIntegerType());
2825   if (Result.hasArrayFiller())
2826     Result.getArrayFiller() = APValue(Value);
2827   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2828     Value = S->getCodeUnit(I);
2829     Result.getArrayInitializedElt(I) = APValue(Value);
2830   }
2831 }
2832 
2833 // Expand an array so that it has more than Index filled elements.
2834 static void expandArray(APValue &Array, unsigned Index) {
2835   unsigned Size = Array.getArraySize();
2836   assert(Index < Size);
2837 
2838   // Always at least double the number of elements for which we store a value.
2839   unsigned OldElts = Array.getArrayInitializedElts();
2840   unsigned NewElts = std::max(Index+1, OldElts * 2);
2841   NewElts = std::min(Size, std::max(NewElts, 8u));
2842 
2843   // Copy the data across.
2844   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2845   for (unsigned I = 0; I != OldElts; ++I)
2846     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2847   for (unsigned I = OldElts; I != NewElts; ++I)
2848     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2849   if (NewValue.hasArrayFiller())
2850     NewValue.getArrayFiller() = Array.getArrayFiller();
2851   Array.swap(NewValue);
2852 }
2853 
2854 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2855 /// conversion. If it's of class type, we may assume that the copy operation
2856 /// is trivial. Note that this is never true for a union type with fields
2857 /// (because the copy always "reads" the active member) and always true for
2858 /// a non-class type.
2859 static bool isReadByLvalueToRvalueConversion(QualType T) {
2860   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2861   if (!RD || (RD->isUnion() && !RD->field_empty()))
2862     return true;
2863   if (RD->isEmpty())
2864     return false;
2865 
2866   for (auto *Field : RD->fields())
2867     if (isReadByLvalueToRvalueConversion(Field->getType()))
2868       return true;
2869 
2870   for (auto &BaseSpec : RD->bases())
2871     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2872       return true;
2873 
2874   return false;
2875 }
2876 
2877 /// Diagnose an attempt to read from any unreadable field within the specified
2878 /// type, which might be a class type.
2879 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2880                                      QualType T) {
2881   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2882   if (!RD)
2883     return false;
2884 
2885   if (!RD->hasMutableFields())
2886     return false;
2887 
2888   for (auto *Field : RD->fields()) {
2889     // If we're actually going to read this field in some way, then it can't
2890     // be mutable. If we're in a union, then assigning to a mutable field
2891     // (even an empty one) can change the active member, so that's not OK.
2892     // FIXME: Add core issue number for the union case.
2893     if (Field->isMutable() &&
2894         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2895       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2896       Info.Note(Field->getLocation(), diag::note_declared_at);
2897       return true;
2898     }
2899 
2900     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2901       return true;
2902   }
2903 
2904   for (auto &BaseSpec : RD->bases())
2905     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2906       return true;
2907 
2908   // All mutable fields were empty, and thus not actually read.
2909   return false;
2910 }
2911 
2912 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2913                                         APValue::LValueBase Base) {
2914   // A temporary we created.
2915   if (Base.getCallIndex())
2916     return true;
2917 
2918   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2919   if (!Evaluating)
2920     return false;
2921 
2922   // The variable whose initializer we're evaluating.
2923   if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2924     if (declaresSameEntity(Evaluating, BaseD))
2925       return true;
2926 
2927   // A temporary lifetime-extended by the variable whose initializer we're
2928   // evaluating.
2929   if (auto *BaseE = Base.dyn_cast<const Expr *>())
2930     if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2931       if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2932         return true;
2933 
2934   return false;
2935 }
2936 
2937 namespace {
2938 /// A handle to a complete object (an object that is not a subobject of
2939 /// another object).
2940 struct CompleteObject {
2941   /// The identity of the object.
2942   APValue::LValueBase Base;
2943   /// The value of the complete object.
2944   APValue *Value;
2945   /// The type of the complete object.
2946   QualType Type;
2947 
2948   CompleteObject() : Value(nullptr) {}
2949   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2950       : Base(Base), Value(Value), Type(Type) {}
2951 
2952   bool mayReadMutableMembers(EvalInfo &Info) const {
2953     // In C++14 onwards, it is permitted to read a mutable member whose
2954     // lifetime began within the evaluation.
2955     // FIXME: Should we also allow this in C++11?
2956     if (!Info.getLangOpts().CPlusPlus14)
2957       return false;
2958     return lifetimeStartedInEvaluation(Info, Base);
2959   }
2960 
2961   explicit operator bool() const { return !Type.isNull(); }
2962 };
2963 } // end anonymous namespace
2964 
2965 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2966                                  bool IsMutable = false) {
2967   // C++ [basic.type.qualifier]p1:
2968   // - A const object is an object of type const T or a non-mutable subobject
2969   //   of a const object.
2970   if (ObjType.isConstQualified() && !IsMutable)
2971     SubobjType.addConst();
2972   // - A volatile object is an object of type const T or a subobject of a
2973   //   volatile object.
2974   if (ObjType.isVolatileQualified())
2975     SubobjType.addVolatile();
2976   return SubobjType;
2977 }
2978 
2979 /// Find the designated sub-object of an rvalue.
2980 template<typename SubobjectHandler>
2981 typename SubobjectHandler::result_type
2982 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2983               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2984   if (Sub.Invalid)
2985     // A diagnostic will have already been produced.
2986     return handler.failed();
2987   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2988     if (Info.getLangOpts().CPlusPlus11)
2989       Info.FFDiag(E, Sub.isOnePastTheEnd()
2990                          ? diag::note_constexpr_access_past_end
2991                          : diag::note_constexpr_access_unsized_array)
2992           << handler.AccessKind;
2993     else
2994       Info.FFDiag(E);
2995     return handler.failed();
2996   }
2997 
2998   APValue *O = Obj.Value;
2999   QualType ObjType = Obj.Type;
3000   const FieldDecl *LastField = nullptr;
3001   const FieldDecl *VolatileField = nullptr;
3002 
3003   // Walk the designator's path to find the subobject.
3004   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3005     // Reading an indeterminate value is undefined, but assigning over one is OK.
3006     if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
3007       if (!Info.checkingPotentialConstantExpression())
3008         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3009             << handler.AccessKind << O->isIndeterminate();
3010       return handler.failed();
3011     }
3012 
3013     // C++ [class.ctor]p5:
3014     //    const and volatile semantics are not applied on an object under
3015     //    construction.
3016     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3017         ObjType->isRecordType() &&
3018         Info.isEvaluatingConstructor(
3019             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3020                                          Sub.Entries.begin() + I)) !=
3021                           ConstructionPhase::None) {
3022       ObjType = Info.Ctx.getCanonicalType(ObjType);
3023       ObjType.removeLocalConst();
3024       ObjType.removeLocalVolatile();
3025     }
3026 
3027     // If this is our last pass, check that the final object type is OK.
3028     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3029       // Accesses to volatile objects are prohibited.
3030       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3031         if (Info.getLangOpts().CPlusPlus) {
3032           int DiagKind;
3033           SourceLocation Loc;
3034           const NamedDecl *Decl = nullptr;
3035           if (VolatileField) {
3036             DiagKind = 2;
3037             Loc = VolatileField->getLocation();
3038             Decl = VolatileField;
3039           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3040             DiagKind = 1;
3041             Loc = VD->getLocation();
3042             Decl = VD;
3043           } else {
3044             DiagKind = 0;
3045             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3046               Loc = E->getExprLoc();
3047           }
3048           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3049               << handler.AccessKind << DiagKind << Decl;
3050           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3051         } else {
3052           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3053         }
3054         return handler.failed();
3055       }
3056 
3057       // If we are reading an object of class type, there may still be more
3058       // things we need to check: if there are any mutable subobjects, we
3059       // cannot perform this read. (This only happens when performing a trivial
3060       // copy or assignment.)
3061       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3062           !Obj.mayReadMutableMembers(Info) &&
3063           diagnoseUnreadableFields(Info, E, ObjType))
3064         return handler.failed();
3065     }
3066 
3067     if (I == N) {
3068       if (!handler.found(*O, ObjType))
3069         return false;
3070 
3071       // If we modified a bit-field, truncate it to the right width.
3072       if (isModification(handler.AccessKind) &&
3073           LastField && LastField->isBitField() &&
3074           !truncateBitfieldValue(Info, E, *O, LastField))
3075         return false;
3076 
3077       return true;
3078     }
3079 
3080     LastField = nullptr;
3081     if (ObjType->isArrayType()) {
3082       // Next subobject is an array element.
3083       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3084       assert(CAT && "vla in literal type?");
3085       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3086       if (CAT->getSize().ule(Index)) {
3087         // Note, it should not be possible to form a pointer with a valid
3088         // designator which points more than one past the end of the array.
3089         if (Info.getLangOpts().CPlusPlus11)
3090           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3091             << handler.AccessKind;
3092         else
3093           Info.FFDiag(E);
3094         return handler.failed();
3095       }
3096 
3097       ObjType = CAT->getElementType();
3098 
3099       if (O->getArrayInitializedElts() > Index)
3100         O = &O->getArrayInitializedElt(Index);
3101       else if (handler.AccessKind != AK_Read) {
3102         expandArray(*O, Index);
3103         O = &O->getArrayInitializedElt(Index);
3104       } else
3105         O = &O->getArrayFiller();
3106     } else if (ObjType->isAnyComplexType()) {
3107       // Next subobject is a complex number.
3108       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3109       if (Index > 1) {
3110         if (Info.getLangOpts().CPlusPlus11)
3111           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3112             << handler.AccessKind;
3113         else
3114           Info.FFDiag(E);
3115         return handler.failed();
3116       }
3117 
3118       ObjType = getSubobjectType(
3119           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3120 
3121       assert(I == N - 1 && "extracting subobject of scalar?");
3122       if (O->isComplexInt()) {
3123         return handler.found(Index ? O->getComplexIntImag()
3124                                    : O->getComplexIntReal(), ObjType);
3125       } else {
3126         assert(O->isComplexFloat());
3127         return handler.found(Index ? O->getComplexFloatImag()
3128                                    : O->getComplexFloatReal(), ObjType);
3129       }
3130     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3131       if (Field->isMutable() && handler.AccessKind == AK_Read &&
3132           !Obj.mayReadMutableMembers(Info)) {
3133         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3134           << Field;
3135         Info.Note(Field->getLocation(), diag::note_declared_at);
3136         return handler.failed();
3137       }
3138 
3139       // Next subobject is a class, struct or union field.
3140       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3141       if (RD->isUnion()) {
3142         const FieldDecl *UnionField = O->getUnionField();
3143         if (!UnionField ||
3144             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3145           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3146             << handler.AccessKind << Field << !UnionField << UnionField;
3147           return handler.failed();
3148         }
3149         O = &O->getUnionValue();
3150       } else
3151         O = &O->getStructField(Field->getFieldIndex());
3152 
3153       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3154       LastField = Field;
3155       if (Field->getType().isVolatileQualified())
3156         VolatileField = Field;
3157     } else {
3158       // Next subobject is a base class.
3159       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3160       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3161       O = &O->getStructBase(getBaseIndex(Derived, Base));
3162 
3163       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3164     }
3165   }
3166 }
3167 
3168 namespace {
3169 struct ExtractSubobjectHandler {
3170   EvalInfo &Info;
3171   APValue &Result;
3172 
3173   static const AccessKinds AccessKind = AK_Read;
3174 
3175   typedef bool result_type;
3176   bool failed() { return false; }
3177   bool found(APValue &Subobj, QualType SubobjType) {
3178     Result = Subobj;
3179     return true;
3180   }
3181   bool found(APSInt &Value, QualType SubobjType) {
3182     Result = APValue(Value);
3183     return true;
3184   }
3185   bool found(APFloat &Value, QualType SubobjType) {
3186     Result = APValue(Value);
3187     return true;
3188   }
3189 };
3190 } // end anonymous namespace
3191 
3192 const AccessKinds ExtractSubobjectHandler::AccessKind;
3193 
3194 /// Extract the designated sub-object of an rvalue.
3195 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3196                              const CompleteObject &Obj,
3197                              const SubobjectDesignator &Sub,
3198                              APValue &Result) {
3199   ExtractSubobjectHandler Handler = { Info, Result };
3200   return findSubobject(Info, E, Obj, Sub, Handler);
3201 }
3202 
3203 namespace {
3204 struct ModifySubobjectHandler {
3205   EvalInfo &Info;
3206   APValue &NewVal;
3207   const Expr *E;
3208 
3209   typedef bool result_type;
3210   static const AccessKinds AccessKind = AK_Assign;
3211 
3212   bool checkConst(QualType QT) {
3213     // Assigning to a const object has undefined behavior.
3214     if (QT.isConstQualified()) {
3215       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3216       return false;
3217     }
3218     return true;
3219   }
3220 
3221   bool failed() { return false; }
3222   bool found(APValue &Subobj, QualType SubobjType) {
3223     if (!checkConst(SubobjType))
3224       return false;
3225     // We've been given ownership of NewVal, so just swap it in.
3226     Subobj.swap(NewVal);
3227     return true;
3228   }
3229   bool found(APSInt &Value, QualType SubobjType) {
3230     if (!checkConst(SubobjType))
3231       return false;
3232     if (!NewVal.isInt()) {
3233       // Maybe trying to write a cast pointer value into a complex?
3234       Info.FFDiag(E);
3235       return false;
3236     }
3237     Value = NewVal.getInt();
3238     return true;
3239   }
3240   bool found(APFloat &Value, QualType SubobjType) {
3241     if (!checkConst(SubobjType))
3242       return false;
3243     Value = NewVal.getFloat();
3244     return true;
3245   }
3246 };
3247 } // end anonymous namespace
3248 
3249 const AccessKinds ModifySubobjectHandler::AccessKind;
3250 
3251 /// Update the designated sub-object of an rvalue to the given value.
3252 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3253                             const CompleteObject &Obj,
3254                             const SubobjectDesignator &Sub,
3255                             APValue &NewVal) {
3256   ModifySubobjectHandler Handler = { Info, NewVal, E };
3257   return findSubobject(Info, E, Obj, Sub, Handler);
3258 }
3259 
3260 /// Find the position where two subobject designators diverge, or equivalently
3261 /// the length of the common initial subsequence.
3262 static unsigned FindDesignatorMismatch(QualType ObjType,
3263                                        const SubobjectDesignator &A,
3264                                        const SubobjectDesignator &B,
3265                                        bool &WasArrayIndex) {
3266   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3267   for (/**/; I != N; ++I) {
3268     if (!ObjType.isNull() &&
3269         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3270       // Next subobject is an array element.
3271       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3272         WasArrayIndex = true;
3273         return I;
3274       }
3275       if (ObjType->isAnyComplexType())
3276         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3277       else
3278         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3279     } else {
3280       if (A.Entries[I].getAsBaseOrMember() !=
3281           B.Entries[I].getAsBaseOrMember()) {
3282         WasArrayIndex = false;
3283         return I;
3284       }
3285       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3286         // Next subobject is a field.
3287         ObjType = FD->getType();
3288       else
3289         // Next subobject is a base class.
3290         ObjType = QualType();
3291     }
3292   }
3293   WasArrayIndex = false;
3294   return I;
3295 }
3296 
3297 /// Determine whether the given subobject designators refer to elements of the
3298 /// same array object.
3299 static bool AreElementsOfSameArray(QualType ObjType,
3300                                    const SubobjectDesignator &A,
3301                                    const SubobjectDesignator &B) {
3302   if (A.Entries.size() != B.Entries.size())
3303     return false;
3304 
3305   bool IsArray = A.MostDerivedIsArrayElement;
3306   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3307     // A is a subobject of the array element.
3308     return false;
3309 
3310   // If A (and B) designates an array element, the last entry will be the array
3311   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3312   // of length 1' case, and the entire path must match.
3313   bool WasArrayIndex;
3314   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3315   return CommonLength >= A.Entries.size() - IsArray;
3316 }
3317 
3318 /// Find the complete object to which an LValue refers.
3319 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3320                                          AccessKinds AK, const LValue &LVal,
3321                                          QualType LValType) {
3322   if (LVal.InvalidBase) {
3323     Info.FFDiag(E);
3324     return CompleteObject();
3325   }
3326 
3327   if (!LVal.Base) {
3328     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3329     return CompleteObject();
3330   }
3331 
3332   CallStackFrame *Frame = nullptr;
3333   unsigned Depth = 0;
3334   if (LVal.getLValueCallIndex()) {
3335     std::tie(Frame, Depth) =
3336         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3337     if (!Frame) {
3338       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3339         << AK << LVal.Base.is<const ValueDecl*>();
3340       NoteLValueLocation(Info, LVal.Base);
3341       return CompleteObject();
3342     }
3343   }
3344 
3345   bool IsAccess = isFormalAccess(AK);
3346 
3347   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3348   // is not a constant expression (even if the object is non-volatile). We also
3349   // apply this rule to C++98, in order to conform to the expected 'volatile'
3350   // semantics.
3351   if (IsAccess && LValType.isVolatileQualified()) {
3352     if (Info.getLangOpts().CPlusPlus)
3353       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3354         << AK << LValType;
3355     else
3356       Info.FFDiag(E);
3357     return CompleteObject();
3358   }
3359 
3360   // Compute value storage location and type of base object.
3361   APValue *BaseVal = nullptr;
3362   QualType BaseType = getType(LVal.Base);
3363 
3364   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3365     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3366     // In C++11, constexpr, non-volatile variables initialized with constant
3367     // expressions are constant expressions too. Inside constexpr functions,
3368     // parameters are constant expressions even if they're non-const.
3369     // In C++1y, objects local to a constant expression (those with a Frame) are
3370     // both readable and writable inside constant expressions.
3371     // In C, such things can also be folded, although they are not ICEs.
3372     const VarDecl *VD = dyn_cast<VarDecl>(D);
3373     if (VD) {
3374       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3375         VD = VDef;
3376     }
3377     if (!VD || VD->isInvalidDecl()) {
3378       Info.FFDiag(E);
3379       return CompleteObject();
3380     }
3381 
3382     // Unless we're looking at a local variable or argument in a constexpr call,
3383     // the variable we're reading must be const.
3384     if (!Frame) {
3385       if (Info.getLangOpts().CPlusPlus14 &&
3386           declaresSameEntity(
3387               VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3388         // OK, we can read and modify an object if we're in the process of
3389         // evaluating its initializer, because its lifetime began in this
3390         // evaluation.
3391       } else if (isModification(AK)) {
3392         // All the remaining cases do not permit modification of the object.
3393         Info.FFDiag(E, diag::note_constexpr_modify_global);
3394         return CompleteObject();
3395       } else if (VD->isConstexpr()) {
3396         // OK, we can read this variable.
3397       } else if (BaseType->isIntegralOrEnumerationType()) {
3398         // In OpenCL if a variable is in constant address space it is a const
3399         // value.
3400         if (!(BaseType.isConstQualified() ||
3401               (Info.getLangOpts().OpenCL &&
3402                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3403           if (!IsAccess)
3404             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3405           if (Info.getLangOpts().CPlusPlus) {
3406             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3407             Info.Note(VD->getLocation(), diag::note_declared_at);
3408           } else {
3409             Info.FFDiag(E);
3410           }
3411           return CompleteObject();
3412         }
3413       } else if (!IsAccess) {
3414         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3415       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3416         // We support folding of const floating-point types, in order to make
3417         // static const data members of such types (supported as an extension)
3418         // more useful.
3419         if (Info.getLangOpts().CPlusPlus11) {
3420           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3421           Info.Note(VD->getLocation(), diag::note_declared_at);
3422         } else {
3423           Info.CCEDiag(E);
3424         }
3425       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3426         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3427         // Keep evaluating to see what we can do.
3428       } else {
3429         // FIXME: Allow folding of values of any literal type in all languages.
3430         if (Info.checkingPotentialConstantExpression() &&
3431             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3432           // The definition of this variable could be constexpr. We can't
3433           // access it right now, but may be able to in future.
3434         } else if (Info.getLangOpts().CPlusPlus11) {
3435           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3436           Info.Note(VD->getLocation(), diag::note_declared_at);
3437         } else {
3438           Info.FFDiag(E);
3439         }
3440         return CompleteObject();
3441       }
3442     }
3443 
3444     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3445       return CompleteObject();
3446   } else {
3447     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3448 
3449     if (!Frame) {
3450       if (const MaterializeTemporaryExpr *MTE =
3451               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3452         assert(MTE->getStorageDuration() == SD_Static &&
3453                "should have a frame for a non-global materialized temporary");
3454 
3455         // Per C++1y [expr.const]p2:
3456         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3457         //   - a [...] glvalue of integral or enumeration type that refers to
3458         //     a non-volatile const object [...]
3459         //   [...]
3460         //   - a [...] glvalue of literal type that refers to a non-volatile
3461         //     object whose lifetime began within the evaluation of e.
3462         //
3463         // C++11 misses the 'began within the evaluation of e' check and
3464         // instead allows all temporaries, including things like:
3465         //   int &&r = 1;
3466         //   int x = ++r;
3467         //   constexpr int k = r;
3468         // Therefore we use the C++14 rules in C++11 too.
3469         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3470         const ValueDecl *ED = MTE->getExtendingDecl();
3471         if (!(BaseType.isConstQualified() &&
3472               BaseType->isIntegralOrEnumerationType()) &&
3473             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3474           if (!IsAccess)
3475             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3476           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3477           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3478           return CompleteObject();
3479         }
3480 
3481         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3482         assert(BaseVal && "got reference to unevaluated temporary");
3483       } else {
3484         if (!IsAccess)
3485           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3486         APValue Val;
3487         LVal.moveInto(Val);
3488         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3489             << AK
3490             << Val.getAsString(Info.Ctx,
3491                                Info.Ctx.getLValueReferenceType(LValType));
3492         NoteLValueLocation(Info, LVal.Base);
3493         return CompleteObject();
3494       }
3495     } else {
3496       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3497       assert(BaseVal && "missing value for temporary");
3498     }
3499   }
3500 
3501   // In C++14, we can't safely access any mutable state when we might be
3502   // evaluating after an unmodeled side effect.
3503   //
3504   // FIXME: Not all local state is mutable. Allow local constant subobjects
3505   // to be read here (but take care with 'mutable' fields).
3506   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3507        Info.EvalStatus.HasSideEffects) ||
3508       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3509     return CompleteObject();
3510 
3511   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3512 }
3513 
3514 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3515 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3516 /// glvalue referred to by an entity of reference type.
3517 ///
3518 /// \param Info - Information about the ongoing evaluation.
3519 /// \param Conv - The expression for which we are performing the conversion.
3520 ///               Used for diagnostics.
3521 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3522 ///               case of a non-class type).
3523 /// \param LVal - The glvalue on which we are attempting to perform this action.
3524 /// \param RVal - The produced value will be placed here.
3525 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3526                                            QualType Type,
3527                                            const LValue &LVal, APValue &RVal) {
3528   if (LVal.Designator.Invalid)
3529     return false;
3530 
3531   // Check for special cases where there is no existing APValue to look at.
3532   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3533 
3534   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3535     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3536       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3537       // initializer until now for such expressions. Such an expression can't be
3538       // an ICE in C, so this only matters for fold.
3539       if (Type.isVolatileQualified()) {
3540         Info.FFDiag(Conv);
3541         return false;
3542       }
3543       APValue Lit;
3544       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3545         return false;
3546       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3547       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3548     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3549       // Special-case character extraction so we don't have to construct an
3550       // APValue for the whole string.
3551       assert(LVal.Designator.Entries.size() <= 1 &&
3552              "Can only read characters from string literals");
3553       if (LVal.Designator.Entries.empty()) {
3554         // Fail for now for LValue to RValue conversion of an array.
3555         // (This shouldn't show up in C/C++, but it could be triggered by a
3556         // weird EvaluateAsRValue call from a tool.)
3557         Info.FFDiag(Conv);
3558         return false;
3559       }
3560       if (LVal.Designator.isOnePastTheEnd()) {
3561         if (Info.getLangOpts().CPlusPlus11)
3562           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3563         else
3564           Info.FFDiag(Conv);
3565         return false;
3566       }
3567       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3568       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3569       return true;
3570     }
3571   }
3572 
3573   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3574   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3575 }
3576 
3577 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3578 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3579                              QualType LValType, APValue &Val) {
3580   if (LVal.Designator.Invalid)
3581     return false;
3582 
3583   if (!Info.getLangOpts().CPlusPlus14) {
3584     Info.FFDiag(E);
3585     return false;
3586   }
3587 
3588   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3589   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3590 }
3591 
3592 namespace {
3593 struct CompoundAssignSubobjectHandler {
3594   EvalInfo &Info;
3595   const Expr *E;
3596   QualType PromotedLHSType;
3597   BinaryOperatorKind Opcode;
3598   const APValue &RHS;
3599 
3600   static const AccessKinds AccessKind = AK_Assign;
3601 
3602   typedef bool result_type;
3603 
3604   bool checkConst(QualType QT) {
3605     // Assigning to a const object has undefined behavior.
3606     if (QT.isConstQualified()) {
3607       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3608       return false;
3609     }
3610     return true;
3611   }
3612 
3613   bool failed() { return false; }
3614   bool found(APValue &Subobj, QualType SubobjType) {
3615     switch (Subobj.getKind()) {
3616     case APValue::Int:
3617       return found(Subobj.getInt(), SubobjType);
3618     case APValue::Float:
3619       return found(Subobj.getFloat(), SubobjType);
3620     case APValue::ComplexInt:
3621     case APValue::ComplexFloat:
3622       // FIXME: Implement complex compound assignment.
3623       Info.FFDiag(E);
3624       return false;
3625     case APValue::LValue:
3626       return foundPointer(Subobj, SubobjType);
3627     default:
3628       // FIXME: can this happen?
3629       Info.FFDiag(E);
3630       return false;
3631     }
3632   }
3633   bool found(APSInt &Value, QualType SubobjType) {
3634     if (!checkConst(SubobjType))
3635       return false;
3636 
3637     if (!SubobjType->isIntegerType()) {
3638       // We don't support compound assignment on integer-cast-to-pointer
3639       // values.
3640       Info.FFDiag(E);
3641       return false;
3642     }
3643 
3644     if (RHS.isInt()) {
3645       APSInt LHS =
3646           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3647       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3648         return false;
3649       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3650       return true;
3651     } else if (RHS.isFloat()) {
3652       APFloat FValue(0.0);
3653       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3654                                   FValue) &&
3655              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3656              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3657                                   Value);
3658     }
3659 
3660     Info.FFDiag(E);
3661     return false;
3662   }
3663   bool found(APFloat &Value, QualType SubobjType) {
3664     return checkConst(SubobjType) &&
3665            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3666                                   Value) &&
3667            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3668            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3669   }
3670   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3671     if (!checkConst(SubobjType))
3672       return false;
3673 
3674     QualType PointeeType;
3675     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3676       PointeeType = PT->getPointeeType();
3677 
3678     if (PointeeType.isNull() || !RHS.isInt() ||
3679         (Opcode != BO_Add && Opcode != BO_Sub)) {
3680       Info.FFDiag(E);
3681       return false;
3682     }
3683 
3684     APSInt Offset = RHS.getInt();
3685     if (Opcode == BO_Sub)
3686       negateAsSigned(Offset);
3687 
3688     LValue LVal;
3689     LVal.setFrom(Info.Ctx, Subobj);
3690     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3691       return false;
3692     LVal.moveInto(Subobj);
3693     return true;
3694   }
3695 };
3696 } // end anonymous namespace
3697 
3698 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3699 
3700 /// Perform a compound assignment of LVal <op>= RVal.
3701 static bool handleCompoundAssignment(
3702     EvalInfo &Info, const Expr *E,
3703     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3704     BinaryOperatorKind Opcode, const APValue &RVal) {
3705   if (LVal.Designator.Invalid)
3706     return false;
3707 
3708   if (!Info.getLangOpts().CPlusPlus14) {
3709     Info.FFDiag(E);
3710     return false;
3711   }
3712 
3713   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3714   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3715                                              RVal };
3716   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3717 }
3718 
3719 namespace {
3720 struct IncDecSubobjectHandler {
3721   EvalInfo &Info;
3722   const UnaryOperator *E;
3723   AccessKinds AccessKind;
3724   APValue *Old;
3725 
3726   typedef bool result_type;
3727 
3728   bool checkConst(QualType QT) {
3729     // Assigning to a const object has undefined behavior.
3730     if (QT.isConstQualified()) {
3731       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3732       return false;
3733     }
3734     return true;
3735   }
3736 
3737   bool failed() { return false; }
3738   bool found(APValue &Subobj, QualType SubobjType) {
3739     // Stash the old value. Also clear Old, so we don't clobber it later
3740     // if we're post-incrementing a complex.
3741     if (Old) {
3742       *Old = Subobj;
3743       Old = nullptr;
3744     }
3745 
3746     switch (Subobj.getKind()) {
3747     case APValue::Int:
3748       return found(Subobj.getInt(), SubobjType);
3749     case APValue::Float:
3750       return found(Subobj.getFloat(), SubobjType);
3751     case APValue::ComplexInt:
3752       return found(Subobj.getComplexIntReal(),
3753                    SubobjType->castAs<ComplexType>()->getElementType()
3754                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3755     case APValue::ComplexFloat:
3756       return found(Subobj.getComplexFloatReal(),
3757                    SubobjType->castAs<ComplexType>()->getElementType()
3758                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3759     case APValue::LValue:
3760       return foundPointer(Subobj, SubobjType);
3761     default:
3762       // FIXME: can this happen?
3763       Info.FFDiag(E);
3764       return false;
3765     }
3766   }
3767   bool found(APSInt &Value, QualType SubobjType) {
3768     if (!checkConst(SubobjType))
3769       return false;
3770 
3771     if (!SubobjType->isIntegerType()) {
3772       // We don't support increment / decrement on integer-cast-to-pointer
3773       // values.
3774       Info.FFDiag(E);
3775       return false;
3776     }
3777 
3778     if (Old) *Old = APValue(Value);
3779 
3780     // bool arithmetic promotes to int, and the conversion back to bool
3781     // doesn't reduce mod 2^n, so special-case it.
3782     if (SubobjType->isBooleanType()) {
3783       if (AccessKind == AK_Increment)
3784         Value = 1;
3785       else
3786         Value = !Value;
3787       return true;
3788     }
3789 
3790     bool WasNegative = Value.isNegative();
3791     if (AccessKind == AK_Increment) {
3792       ++Value;
3793 
3794       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3795         APSInt ActualValue(Value, /*IsUnsigned*/true);
3796         return HandleOverflow(Info, E, ActualValue, SubobjType);
3797       }
3798     } else {
3799       --Value;
3800 
3801       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3802         unsigned BitWidth = Value.getBitWidth();
3803         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3804         ActualValue.setBit(BitWidth);
3805         return HandleOverflow(Info, E, ActualValue, SubobjType);
3806       }
3807     }
3808     return true;
3809   }
3810   bool found(APFloat &Value, QualType SubobjType) {
3811     if (!checkConst(SubobjType))
3812       return false;
3813 
3814     if (Old) *Old = APValue(Value);
3815 
3816     APFloat One(Value.getSemantics(), 1);
3817     if (AccessKind == AK_Increment)
3818       Value.add(One, APFloat::rmNearestTiesToEven);
3819     else
3820       Value.subtract(One, APFloat::rmNearestTiesToEven);
3821     return true;
3822   }
3823   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3824     if (!checkConst(SubobjType))
3825       return false;
3826 
3827     QualType PointeeType;
3828     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3829       PointeeType = PT->getPointeeType();
3830     else {
3831       Info.FFDiag(E);
3832       return false;
3833     }
3834 
3835     LValue LVal;
3836     LVal.setFrom(Info.Ctx, Subobj);
3837     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3838                                      AccessKind == AK_Increment ? 1 : -1))
3839       return false;
3840     LVal.moveInto(Subobj);
3841     return true;
3842   }
3843 };
3844 } // end anonymous namespace
3845 
3846 /// Perform an increment or decrement on LVal.
3847 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3848                          QualType LValType, bool IsIncrement, APValue *Old) {
3849   if (LVal.Designator.Invalid)
3850     return false;
3851 
3852   if (!Info.getLangOpts().CPlusPlus14) {
3853     Info.FFDiag(E);
3854     return false;
3855   }
3856 
3857   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3858   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3859   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3860   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3861 }
3862 
3863 /// Build an lvalue for the object argument of a member function call.
3864 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3865                                    LValue &This) {
3866   if (Object->getType()->isPointerType())
3867     return EvaluatePointer(Object, This, Info);
3868 
3869   if (Object->isGLValue())
3870     return EvaluateLValue(Object, This, Info);
3871 
3872   if (Object->getType()->isLiteralType(Info.Ctx))
3873     return EvaluateTemporary(Object, This, Info);
3874 
3875   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3876   return false;
3877 }
3878 
3879 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3880 /// lvalue referring to the result.
3881 ///
3882 /// \param Info - Information about the ongoing evaluation.
3883 /// \param LV - An lvalue referring to the base of the member pointer.
3884 /// \param RHS - The member pointer expression.
3885 /// \param IncludeMember - Specifies whether the member itself is included in
3886 ///        the resulting LValue subobject designator. This is not possible when
3887 ///        creating a bound member function.
3888 /// \return The field or method declaration to which the member pointer refers,
3889 ///         or 0 if evaluation fails.
3890 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3891                                                   QualType LVType,
3892                                                   LValue &LV,
3893                                                   const Expr *RHS,
3894                                                   bool IncludeMember = true) {
3895   MemberPtr MemPtr;
3896   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3897     return nullptr;
3898 
3899   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3900   // member value, the behavior is undefined.
3901   if (!MemPtr.getDecl()) {
3902     // FIXME: Specific diagnostic.
3903     Info.FFDiag(RHS);
3904     return nullptr;
3905   }
3906 
3907   if (MemPtr.isDerivedMember()) {
3908     // This is a member of some derived class. Truncate LV appropriately.
3909     // The end of the derived-to-base path for the base object must match the
3910     // derived-to-base path for the member pointer.
3911     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3912         LV.Designator.Entries.size()) {
3913       Info.FFDiag(RHS);
3914       return nullptr;
3915     }
3916     unsigned PathLengthToMember =
3917         LV.Designator.Entries.size() - MemPtr.Path.size();
3918     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3919       const CXXRecordDecl *LVDecl = getAsBaseClass(
3920           LV.Designator.Entries[PathLengthToMember + I]);
3921       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3922       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3923         Info.FFDiag(RHS);
3924         return nullptr;
3925       }
3926     }
3927 
3928     // Truncate the lvalue to the appropriate derived class.
3929     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3930                             PathLengthToMember))
3931       return nullptr;
3932   } else if (!MemPtr.Path.empty()) {
3933     // Extend the LValue path with the member pointer's path.
3934     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3935                                   MemPtr.Path.size() + IncludeMember);
3936 
3937     // Walk down to the appropriate base class.
3938     if (const PointerType *PT = LVType->getAs<PointerType>())
3939       LVType = PT->getPointeeType();
3940     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3941     assert(RD && "member pointer access on non-class-type expression");
3942     // The first class in the path is that of the lvalue.
3943     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3944       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3945       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3946         return nullptr;
3947       RD = Base;
3948     }
3949     // Finally cast to the class containing the member.
3950     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3951                                 MemPtr.getContainingRecord()))
3952       return nullptr;
3953   }
3954 
3955   // Add the member. Note that we cannot build bound member functions here.
3956   if (IncludeMember) {
3957     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3958       if (!HandleLValueMember(Info, RHS, LV, FD))
3959         return nullptr;
3960     } else if (const IndirectFieldDecl *IFD =
3961                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3962       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3963         return nullptr;
3964     } else {
3965       llvm_unreachable("can't construct reference to bound member function");
3966     }
3967   }
3968 
3969   return MemPtr.getDecl();
3970 }
3971 
3972 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3973                                                   const BinaryOperator *BO,
3974                                                   LValue &LV,
3975                                                   bool IncludeMember = true) {
3976   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3977 
3978   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3979     if (Info.noteFailure()) {
3980       MemberPtr MemPtr;
3981       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3982     }
3983     return nullptr;
3984   }
3985 
3986   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3987                                    BO->getRHS(), IncludeMember);
3988 }
3989 
3990 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3991 /// the provided lvalue, which currently refers to the base object.
3992 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3993                                     LValue &Result) {
3994   SubobjectDesignator &D = Result.Designator;
3995   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3996     return false;
3997 
3998   QualType TargetQT = E->getType();
3999   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4000     TargetQT = PT->getPointeeType();
4001 
4002   // Check this cast lands within the final derived-to-base subobject path.
4003   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4004     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4005       << D.MostDerivedType << TargetQT;
4006     return false;
4007   }
4008 
4009   // Check the type of the final cast. We don't need to check the path,
4010   // since a cast can only be formed if the path is unique.
4011   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4012   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4013   const CXXRecordDecl *FinalType;
4014   if (NewEntriesSize == D.MostDerivedPathLength)
4015     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4016   else
4017     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4018   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4019     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4020       << D.MostDerivedType << TargetQT;
4021     return false;
4022   }
4023 
4024   // Truncate the lvalue to the appropriate derived class.
4025   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4026 }
4027 
4028 namespace {
4029 enum EvalStmtResult {
4030   /// Evaluation failed.
4031   ESR_Failed,
4032   /// Hit a 'return' statement.
4033   ESR_Returned,
4034   /// Evaluation succeeded.
4035   ESR_Succeeded,
4036   /// Hit a 'continue' statement.
4037   ESR_Continue,
4038   /// Hit a 'break' statement.
4039   ESR_Break,
4040   /// Still scanning for 'case' or 'default' statement.
4041   ESR_CaseNotFound
4042 };
4043 }
4044 
4045 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4046   // We don't need to evaluate the initializer for a static local.
4047   if (!VD->hasLocalStorage())
4048     return true;
4049 
4050   LValue Result;
4051   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4052 
4053   const Expr *InitE = VD->getInit();
4054   if (!InitE) {
4055     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4056         << false << VD->getType();
4057     Val = APValue();
4058     return false;
4059   }
4060 
4061   if (InitE->isValueDependent())
4062     return false;
4063 
4064   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4065     // Wipe out any partially-computed value, to allow tracking that this
4066     // evaluation failed.
4067     Val = APValue();
4068     return false;
4069   }
4070 
4071   return true;
4072 }
4073 
4074 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4075   bool OK = true;
4076 
4077   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4078     OK &= EvaluateVarDecl(Info, VD);
4079 
4080   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4081     for (auto *BD : DD->bindings())
4082       if (auto *VD = BD->getHoldingVar())
4083         OK &= EvaluateDecl(Info, VD);
4084 
4085   return OK;
4086 }
4087 
4088 
4089 /// Evaluate a condition (either a variable declaration or an expression).
4090 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4091                          const Expr *Cond, bool &Result) {
4092   FullExpressionRAII Scope(Info);
4093   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4094     return false;
4095   return EvaluateAsBooleanCondition(Cond, Result, Info);
4096 }
4097 
4098 namespace {
4099 /// A location where the result (returned value) of evaluating a
4100 /// statement should be stored.
4101 struct StmtResult {
4102   /// The APValue that should be filled in with the returned value.
4103   APValue &Value;
4104   /// The location containing the result, if any (used to support RVO).
4105   const LValue *Slot;
4106 };
4107 
4108 struct TempVersionRAII {
4109   CallStackFrame &Frame;
4110 
4111   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4112     Frame.pushTempVersion();
4113   }
4114 
4115   ~TempVersionRAII() {
4116     Frame.popTempVersion();
4117   }
4118 };
4119 
4120 }
4121 
4122 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4123                                    const Stmt *S,
4124                                    const SwitchCase *SC = nullptr);
4125 
4126 /// Evaluate the body of a loop, and translate the result as appropriate.
4127 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4128                                        const Stmt *Body,
4129                                        const SwitchCase *Case = nullptr) {
4130   BlockScopeRAII Scope(Info);
4131   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4132   case ESR_Break:
4133     return ESR_Succeeded;
4134   case ESR_Succeeded:
4135   case ESR_Continue:
4136     return ESR_Continue;
4137   case ESR_Failed:
4138   case ESR_Returned:
4139   case ESR_CaseNotFound:
4140     return ESR;
4141   }
4142   llvm_unreachable("Invalid EvalStmtResult!");
4143 }
4144 
4145 /// Evaluate a switch statement.
4146 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4147                                      const SwitchStmt *SS) {
4148   BlockScopeRAII Scope(Info);
4149 
4150   // Evaluate the switch condition.
4151   APSInt Value;
4152   {
4153     FullExpressionRAII Scope(Info);
4154     if (const Stmt *Init = SS->getInit()) {
4155       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4156       if (ESR != ESR_Succeeded)
4157         return ESR;
4158     }
4159     if (SS->getConditionVariable() &&
4160         !EvaluateDecl(Info, SS->getConditionVariable()))
4161       return ESR_Failed;
4162     if (!EvaluateInteger(SS->getCond(), Value, Info))
4163       return ESR_Failed;
4164   }
4165 
4166   // Find the switch case corresponding to the value of the condition.
4167   // FIXME: Cache this lookup.
4168   const SwitchCase *Found = nullptr;
4169   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4170        SC = SC->getNextSwitchCase()) {
4171     if (isa<DefaultStmt>(SC)) {
4172       Found = SC;
4173       continue;
4174     }
4175 
4176     const CaseStmt *CS = cast<CaseStmt>(SC);
4177     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4178     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4179                               : LHS;
4180     if (LHS <= Value && Value <= RHS) {
4181       Found = SC;
4182       break;
4183     }
4184   }
4185 
4186   if (!Found)
4187     return ESR_Succeeded;
4188 
4189   // Search the switch body for the switch case and evaluate it from there.
4190   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4191   case ESR_Break:
4192     return ESR_Succeeded;
4193   case ESR_Succeeded:
4194   case ESR_Continue:
4195   case ESR_Failed:
4196   case ESR_Returned:
4197     return ESR;
4198   case ESR_CaseNotFound:
4199     // This can only happen if the switch case is nested within a statement
4200     // expression. We have no intention of supporting that.
4201     Info.FFDiag(Found->getBeginLoc(),
4202                 diag::note_constexpr_stmt_expr_unsupported);
4203     return ESR_Failed;
4204   }
4205   llvm_unreachable("Invalid EvalStmtResult!");
4206 }
4207 
4208 // Evaluate a statement.
4209 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4210                                    const Stmt *S, const SwitchCase *Case) {
4211   if (!Info.nextStep(S))
4212     return ESR_Failed;
4213 
4214   // If we're hunting down a 'case' or 'default' label, recurse through
4215   // substatements until we hit the label.
4216   if (Case) {
4217     // FIXME: We don't start the lifetime of objects whose initialization we
4218     // jump over. However, such objects must be of class type with a trivial
4219     // default constructor that initialize all subobjects, so must be empty,
4220     // so this almost never matters.
4221     switch (S->getStmtClass()) {
4222     case Stmt::CompoundStmtClass:
4223       // FIXME: Precompute which substatement of a compound statement we
4224       // would jump to, and go straight there rather than performing a
4225       // linear scan each time.
4226     case Stmt::LabelStmtClass:
4227     case Stmt::AttributedStmtClass:
4228     case Stmt::DoStmtClass:
4229       break;
4230 
4231     case Stmt::CaseStmtClass:
4232     case Stmt::DefaultStmtClass:
4233       if (Case == S)
4234         Case = nullptr;
4235       break;
4236 
4237     case Stmt::IfStmtClass: {
4238       // FIXME: Precompute which side of an 'if' we would jump to, and go
4239       // straight there rather than scanning both sides.
4240       const IfStmt *IS = cast<IfStmt>(S);
4241 
4242       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4243       // preceded by our switch label.
4244       BlockScopeRAII Scope(Info);
4245 
4246       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4247       if (ESR != ESR_CaseNotFound || !IS->getElse())
4248         return ESR;
4249       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4250     }
4251 
4252     case Stmt::WhileStmtClass: {
4253       EvalStmtResult ESR =
4254           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4255       if (ESR != ESR_Continue)
4256         return ESR;
4257       break;
4258     }
4259 
4260     case Stmt::ForStmtClass: {
4261       const ForStmt *FS = cast<ForStmt>(S);
4262       EvalStmtResult ESR =
4263           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4264       if (ESR != ESR_Continue)
4265         return ESR;
4266       if (FS->getInc()) {
4267         FullExpressionRAII IncScope(Info);
4268         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4269           return ESR_Failed;
4270       }
4271       break;
4272     }
4273 
4274     case Stmt::DeclStmtClass:
4275       // FIXME: If the variable has initialization that can't be jumped over,
4276       // bail out of any immediately-surrounding compound-statement too.
4277     default:
4278       return ESR_CaseNotFound;
4279     }
4280   }
4281 
4282   switch (S->getStmtClass()) {
4283   default:
4284     if (const Expr *E = dyn_cast<Expr>(S)) {
4285       // Don't bother evaluating beyond an expression-statement which couldn't
4286       // be evaluated.
4287       FullExpressionRAII Scope(Info);
4288       if (!EvaluateIgnoredValue(Info, E))
4289         return ESR_Failed;
4290       return ESR_Succeeded;
4291     }
4292 
4293     Info.FFDiag(S->getBeginLoc());
4294     return ESR_Failed;
4295 
4296   case Stmt::NullStmtClass:
4297     return ESR_Succeeded;
4298 
4299   case Stmt::DeclStmtClass: {
4300     const DeclStmt *DS = cast<DeclStmt>(S);
4301     for (const auto *DclIt : DS->decls()) {
4302       // Each declaration initialization is its own full-expression.
4303       // FIXME: This isn't quite right; if we're performing aggregate
4304       // initialization, each braced subexpression is its own full-expression.
4305       FullExpressionRAII Scope(Info);
4306       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4307         return ESR_Failed;
4308     }
4309     return ESR_Succeeded;
4310   }
4311 
4312   case Stmt::ReturnStmtClass: {
4313     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4314     FullExpressionRAII Scope(Info);
4315     if (RetExpr &&
4316         !(Result.Slot
4317               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4318               : Evaluate(Result.Value, Info, RetExpr)))
4319       return ESR_Failed;
4320     return ESR_Returned;
4321   }
4322 
4323   case Stmt::CompoundStmtClass: {
4324     BlockScopeRAII Scope(Info);
4325 
4326     const CompoundStmt *CS = cast<CompoundStmt>(S);
4327     for (const auto *BI : CS->body()) {
4328       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4329       if (ESR == ESR_Succeeded)
4330         Case = nullptr;
4331       else if (ESR != ESR_CaseNotFound)
4332         return ESR;
4333     }
4334     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4335   }
4336 
4337   case Stmt::IfStmtClass: {
4338     const IfStmt *IS = cast<IfStmt>(S);
4339 
4340     // Evaluate the condition, as either a var decl or as an expression.
4341     BlockScopeRAII Scope(Info);
4342     if (const Stmt *Init = IS->getInit()) {
4343       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4344       if (ESR != ESR_Succeeded)
4345         return ESR;
4346     }
4347     bool Cond;
4348     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4349       return ESR_Failed;
4350 
4351     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4352       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4353       if (ESR != ESR_Succeeded)
4354         return ESR;
4355     }
4356     return ESR_Succeeded;
4357   }
4358 
4359   case Stmt::WhileStmtClass: {
4360     const WhileStmt *WS = cast<WhileStmt>(S);
4361     while (true) {
4362       BlockScopeRAII Scope(Info);
4363       bool Continue;
4364       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4365                         Continue))
4366         return ESR_Failed;
4367       if (!Continue)
4368         break;
4369 
4370       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4371       if (ESR != ESR_Continue)
4372         return ESR;
4373     }
4374     return ESR_Succeeded;
4375   }
4376 
4377   case Stmt::DoStmtClass: {
4378     const DoStmt *DS = cast<DoStmt>(S);
4379     bool Continue;
4380     do {
4381       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4382       if (ESR != ESR_Continue)
4383         return ESR;
4384       Case = nullptr;
4385 
4386       FullExpressionRAII CondScope(Info);
4387       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4388         return ESR_Failed;
4389     } while (Continue);
4390     return ESR_Succeeded;
4391   }
4392 
4393   case Stmt::ForStmtClass: {
4394     const ForStmt *FS = cast<ForStmt>(S);
4395     BlockScopeRAII Scope(Info);
4396     if (FS->getInit()) {
4397       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4398       if (ESR != ESR_Succeeded)
4399         return ESR;
4400     }
4401     while (true) {
4402       BlockScopeRAII Scope(Info);
4403       bool Continue = true;
4404       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4405                                          FS->getCond(), Continue))
4406         return ESR_Failed;
4407       if (!Continue)
4408         break;
4409 
4410       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4411       if (ESR != ESR_Continue)
4412         return ESR;
4413 
4414       if (FS->getInc()) {
4415         FullExpressionRAII IncScope(Info);
4416         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4417           return ESR_Failed;
4418       }
4419     }
4420     return ESR_Succeeded;
4421   }
4422 
4423   case Stmt::CXXForRangeStmtClass: {
4424     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4425     BlockScopeRAII Scope(Info);
4426 
4427     // Evaluate the init-statement if present.
4428     if (FS->getInit()) {
4429       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4430       if (ESR != ESR_Succeeded)
4431         return ESR;
4432     }
4433 
4434     // Initialize the __range variable.
4435     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4436     if (ESR != ESR_Succeeded)
4437       return ESR;
4438 
4439     // Create the __begin and __end iterators.
4440     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4441     if (ESR != ESR_Succeeded)
4442       return ESR;
4443     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4444     if (ESR != ESR_Succeeded)
4445       return ESR;
4446 
4447     while (true) {
4448       // Condition: __begin != __end.
4449       {
4450         bool Continue = true;
4451         FullExpressionRAII CondExpr(Info);
4452         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4453           return ESR_Failed;
4454         if (!Continue)
4455           break;
4456       }
4457 
4458       // User's variable declaration, initialized by *__begin.
4459       BlockScopeRAII InnerScope(Info);
4460       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4461       if (ESR != ESR_Succeeded)
4462         return ESR;
4463 
4464       // Loop body.
4465       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4466       if (ESR != ESR_Continue)
4467         return ESR;
4468 
4469       // Increment: ++__begin
4470       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4471         return ESR_Failed;
4472     }
4473 
4474     return ESR_Succeeded;
4475   }
4476 
4477   case Stmt::SwitchStmtClass:
4478     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4479 
4480   case Stmt::ContinueStmtClass:
4481     return ESR_Continue;
4482 
4483   case Stmt::BreakStmtClass:
4484     return ESR_Break;
4485 
4486   case Stmt::LabelStmtClass:
4487     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4488 
4489   case Stmt::AttributedStmtClass:
4490     // As a general principle, C++11 attributes can be ignored without
4491     // any semantic impact.
4492     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4493                         Case);
4494 
4495   case Stmt::CaseStmtClass:
4496   case Stmt::DefaultStmtClass:
4497     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4498   case Stmt::CXXTryStmtClass:
4499     // Evaluate try blocks by evaluating all sub statements.
4500     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4501   }
4502 }
4503 
4504 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4505 /// default constructor. If so, we'll fold it whether or not it's marked as
4506 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4507 /// so we need special handling.
4508 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4509                                            const CXXConstructorDecl *CD,
4510                                            bool IsValueInitialization) {
4511   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4512     return false;
4513 
4514   // Value-initialization does not call a trivial default constructor, so such a
4515   // call is a core constant expression whether or not the constructor is
4516   // constexpr.
4517   if (!CD->isConstexpr() && !IsValueInitialization) {
4518     if (Info.getLangOpts().CPlusPlus11) {
4519       // FIXME: If DiagDecl is an implicitly-declared special member function,
4520       // we should be much more explicit about why it's not constexpr.
4521       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4522         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4523       Info.Note(CD->getLocation(), diag::note_declared_at);
4524     } else {
4525       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4526     }
4527   }
4528   return true;
4529 }
4530 
4531 /// CheckConstexprFunction - Check that a function can be called in a constant
4532 /// expression.
4533 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4534                                    const FunctionDecl *Declaration,
4535                                    const FunctionDecl *Definition,
4536                                    const Stmt *Body) {
4537   // Potential constant expressions can contain calls to declared, but not yet
4538   // defined, constexpr functions.
4539   if (Info.checkingPotentialConstantExpression() && !Definition &&
4540       Declaration->isConstexpr())
4541     return false;
4542 
4543   // Bail out if the function declaration itself is invalid.  We will
4544   // have produced a relevant diagnostic while parsing it, so just
4545   // note the problematic sub-expression.
4546   if (Declaration->isInvalidDecl()) {
4547     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4548     return false;
4549   }
4550 
4551   // DR1872: An instantiated virtual constexpr function can't be called in a
4552   // constant expression (prior to C++20). We can still constant-fold such a
4553   // call.
4554   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4555       cast<CXXMethodDecl>(Declaration)->isVirtual())
4556     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4557 
4558   if (Definition && Definition->isInvalidDecl()) {
4559     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4560     return false;
4561   }
4562 
4563   // Can we evaluate this function call?
4564   if (Definition && Definition->isConstexpr() && Body)
4565     return true;
4566 
4567   if (Info.getLangOpts().CPlusPlus11) {
4568     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4569 
4570     // If this function is not constexpr because it is an inherited
4571     // non-constexpr constructor, diagnose that directly.
4572     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4573     if (CD && CD->isInheritingConstructor()) {
4574       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4575       if (!Inherited->isConstexpr())
4576         DiagDecl = CD = Inherited;
4577     }
4578 
4579     // FIXME: If DiagDecl is an implicitly-declared special member function
4580     // or an inheriting constructor, we should be much more explicit about why
4581     // it's not constexpr.
4582     if (CD && CD->isInheritingConstructor())
4583       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4584         << CD->getInheritedConstructor().getConstructor()->getParent();
4585     else
4586       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4587         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4588     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4589   } else {
4590     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4591   }
4592   return false;
4593 }
4594 
4595 namespace {
4596 struct CheckDynamicTypeHandler {
4597   AccessKinds AccessKind;
4598   typedef bool result_type;
4599   bool failed() { return false; }
4600   bool found(APValue &Subobj, QualType SubobjType) { return true; }
4601   bool found(APSInt &Value, QualType SubobjType) { return true; }
4602   bool found(APFloat &Value, QualType SubobjType) { return true; }
4603 };
4604 } // end anonymous namespace
4605 
4606 /// Check that we can access the notional vptr of an object / determine its
4607 /// dynamic type.
4608 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4609                              AccessKinds AK, bool Polymorphic) {
4610   if (This.Designator.Invalid)
4611     return false;
4612 
4613   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4614 
4615   if (!Obj)
4616     return false;
4617 
4618   if (!Obj.Value) {
4619     // The object is not usable in constant expressions, so we can't inspect
4620     // its value to see if it's in-lifetime or what the active union members
4621     // are. We can still check for a one-past-the-end lvalue.
4622     if (This.Designator.isOnePastTheEnd() ||
4623         This.Designator.isMostDerivedAnUnsizedArray()) {
4624       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4625                          ? diag::note_constexpr_access_past_end
4626                          : diag::note_constexpr_access_unsized_array)
4627           << AK;
4628       return false;
4629     } else if (Polymorphic) {
4630       // Conservatively refuse to perform a polymorphic operation if we would
4631       // not be able to read a notional 'vptr' value.
4632       APValue Val;
4633       This.moveInto(Val);
4634       QualType StarThisType =
4635           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4636       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4637           << AK << Val.getAsString(Info.Ctx, StarThisType);
4638       return false;
4639     }
4640     return true;
4641   }
4642 
4643   CheckDynamicTypeHandler Handler{AK};
4644   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4645 }
4646 
4647 /// Check that the pointee of the 'this' pointer in a member function call is
4648 /// either within its lifetime or in its period of construction or destruction.
4649 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4650                                                  const LValue &This) {
4651   return checkDynamicType(Info, E, This, AK_MemberCall, false);
4652 }
4653 
4654 struct DynamicType {
4655   /// The dynamic class type of the object.
4656   const CXXRecordDecl *Type;
4657   /// The corresponding path length in the lvalue.
4658   unsigned PathLength;
4659 };
4660 
4661 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4662                                              unsigned PathLength) {
4663   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4664       Designator.Entries.size() && "invalid path length");
4665   return (PathLength == Designator.MostDerivedPathLength)
4666              ? Designator.MostDerivedType->getAsCXXRecordDecl()
4667              : getAsBaseClass(Designator.Entries[PathLength - 1]);
4668 }
4669 
4670 /// Determine the dynamic type of an object.
4671 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4672                                                 LValue &This, AccessKinds AK) {
4673   // If we don't have an lvalue denoting an object of class type, there is no
4674   // meaningful dynamic type. (We consider objects of non-class type to have no
4675   // dynamic type.)
4676   if (!checkDynamicType(Info, E, This, AK, true))
4677     return None;
4678 
4679   // Refuse to compute a dynamic type in the presence of virtual bases. This
4680   // shouldn't happen other than in constant-folding situations, since literal
4681   // types can't have virtual bases.
4682   //
4683   // Note that consumers of DynamicType assume that the type has no virtual
4684   // bases, and will need modifications if this restriction is relaxed.
4685   const CXXRecordDecl *Class =
4686       This.Designator.MostDerivedType->getAsCXXRecordDecl();
4687   if (!Class || Class->getNumVBases()) {
4688     Info.FFDiag(E);
4689     return None;
4690   }
4691 
4692   // FIXME: For very deep class hierarchies, it might be beneficial to use a
4693   // binary search here instead. But the overwhelmingly common case is that
4694   // we're not in the middle of a constructor, so it probably doesn't matter
4695   // in practice.
4696   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4697   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4698        PathLength <= Path.size(); ++PathLength) {
4699     switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4700                                          Path.slice(0, PathLength))) {
4701     case ConstructionPhase::Bases:
4702       // We're constructing a base class. This is not the dynamic type.
4703       break;
4704 
4705     case ConstructionPhase::None:
4706     case ConstructionPhase::AfterBases:
4707       // We've finished constructing the base classes, so this is the dynamic
4708       // type.
4709       return DynamicType{getBaseClassType(This.Designator, PathLength),
4710                          PathLength};
4711     }
4712   }
4713 
4714   // CWG issue 1517: we're constructing a base class of the object described by
4715   // 'This', so that object has not yet begun its period of construction and
4716   // any polymorphic operation on it results in undefined behavior.
4717   Info.FFDiag(E);
4718   return None;
4719 }
4720 
4721 /// Perform virtual dispatch.
4722 static const CXXMethodDecl *HandleVirtualDispatch(
4723     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4724     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4725   Optional<DynamicType> DynType =
4726       ComputeDynamicType(Info, E, This, AK_MemberCall);
4727   if (!DynType)
4728     return nullptr;
4729 
4730   // Find the final overrider. It must be declared in one of the classes on the
4731   // path from the dynamic type to the static type.
4732   // FIXME: If we ever allow literal types to have virtual base classes, that
4733   // won't be true.
4734   const CXXMethodDecl *Callee = Found;
4735   unsigned PathLength = DynType->PathLength;
4736   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4737     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4738     const CXXMethodDecl *Overrider =
4739         Found->getCorrespondingMethodDeclaredInClass(Class, false);
4740     if (Overrider) {
4741       Callee = Overrider;
4742       break;
4743     }
4744   }
4745 
4746   // C++2a [class.abstract]p6:
4747   //   the effect of making a virtual call to a pure virtual function [...] is
4748   //   undefined
4749   if (Callee->isPure()) {
4750     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4751     Info.Note(Callee->getLocation(), diag::note_declared_at);
4752     return nullptr;
4753   }
4754 
4755   // If necessary, walk the rest of the path to determine the sequence of
4756   // covariant adjustment steps to apply.
4757   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4758                                        Found->getReturnType())) {
4759     CovariantAdjustmentPath.push_back(Callee->getReturnType());
4760     for (unsigned CovariantPathLength = PathLength + 1;
4761          CovariantPathLength != This.Designator.Entries.size();
4762          ++CovariantPathLength) {
4763       const CXXRecordDecl *NextClass =
4764           getBaseClassType(This.Designator, CovariantPathLength);
4765       const CXXMethodDecl *Next =
4766           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4767       if (Next && !Info.Ctx.hasSameUnqualifiedType(
4768                       Next->getReturnType(), CovariantAdjustmentPath.back()))
4769         CovariantAdjustmentPath.push_back(Next->getReturnType());
4770     }
4771     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4772                                          CovariantAdjustmentPath.back()))
4773       CovariantAdjustmentPath.push_back(Found->getReturnType());
4774   }
4775 
4776   // Perform 'this' adjustment.
4777   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4778     return nullptr;
4779 
4780   return Callee;
4781 }
4782 
4783 /// Perform the adjustment from a value returned by a virtual function to
4784 /// a value of the statically expected type, which may be a pointer or
4785 /// reference to a base class of the returned type.
4786 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4787                                             APValue &Result,
4788                                             ArrayRef<QualType> Path) {
4789   assert(Result.isLValue() &&
4790          "unexpected kind of APValue for covariant return");
4791   if (Result.isNullPointer())
4792     return true;
4793 
4794   LValue LVal;
4795   LVal.setFrom(Info.Ctx, Result);
4796 
4797   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4798   for (unsigned I = 1; I != Path.size(); ++I) {
4799     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4800     assert(OldClass && NewClass && "unexpected kind of covariant return");
4801     if (OldClass != NewClass &&
4802         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4803       return false;
4804     OldClass = NewClass;
4805   }
4806 
4807   LVal.moveInto(Result);
4808   return true;
4809 }
4810 
4811 /// Determine whether \p Base, which is known to be a direct base class of
4812 /// \p Derived, is a public base class.
4813 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4814                               const CXXRecordDecl *Base) {
4815   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4816     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4817     if (BaseClass && declaresSameEntity(BaseClass, Base))
4818       return BaseSpec.getAccessSpecifier() == AS_public;
4819   }
4820   llvm_unreachable("Base is not a direct base of Derived");
4821 }
4822 
4823 /// Apply the given dynamic cast operation on the provided lvalue.
4824 ///
4825 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4826 /// to find a suitable target subobject.
4827 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4828                               LValue &Ptr) {
4829   // We can't do anything with a non-symbolic pointer value.
4830   SubobjectDesignator &D = Ptr.Designator;
4831   if (D.Invalid)
4832     return false;
4833 
4834   // C++ [expr.dynamic.cast]p6:
4835   //   If v is a null pointer value, the result is a null pointer value.
4836   if (Ptr.isNullPointer() && !E->isGLValue())
4837     return true;
4838 
4839   // For all the other cases, we need the pointer to point to an object within
4840   // its lifetime / period of construction / destruction, and we need to know
4841   // its dynamic type.
4842   Optional<DynamicType> DynType =
4843       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4844   if (!DynType)
4845     return false;
4846 
4847   // C++ [expr.dynamic.cast]p7:
4848   //   If T is "pointer to cv void", then the result is a pointer to the most
4849   //   derived object
4850   if (E->getType()->isVoidPointerType())
4851     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4852 
4853   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4854   assert(C && "dynamic_cast target is not void pointer nor class");
4855   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4856 
4857   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4858     // C++ [expr.dynamic.cast]p9:
4859     if (!E->isGLValue()) {
4860       //   The value of a failed cast to pointer type is the null pointer value
4861       //   of the required result type.
4862       auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4863       Ptr.setNull(E->getType(), TargetVal);
4864       return true;
4865     }
4866 
4867     //   A failed cast to reference type throws [...] std::bad_cast.
4868     unsigned DiagKind;
4869     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4870                    DynType->Type->isDerivedFrom(C)))
4871       DiagKind = 0;
4872     else if (!Paths || Paths->begin() == Paths->end())
4873       DiagKind = 1;
4874     else if (Paths->isAmbiguous(CQT))
4875       DiagKind = 2;
4876     else {
4877       assert(Paths->front().Access != AS_public && "why did the cast fail?");
4878       DiagKind = 3;
4879     }
4880     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4881         << DiagKind << Ptr.Designator.getType(Info.Ctx)
4882         << Info.Ctx.getRecordType(DynType->Type)
4883         << E->getType().getUnqualifiedType();
4884     return false;
4885   };
4886 
4887   // Runtime check, phase 1:
4888   //   Walk from the base subobject towards the derived object looking for the
4889   //   target type.
4890   for (int PathLength = Ptr.Designator.Entries.size();
4891        PathLength >= (int)DynType->PathLength; --PathLength) {
4892     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4893     if (declaresSameEntity(Class, C))
4894       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4895     // We can only walk across public inheritance edges.
4896     if (PathLength > (int)DynType->PathLength &&
4897         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4898                            Class))
4899       return RuntimeCheckFailed(nullptr);
4900   }
4901 
4902   // Runtime check, phase 2:
4903   //   Search the dynamic type for an unambiguous public base of type C.
4904   CXXBasePaths Paths(/*FindAmbiguities=*/true,
4905                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
4906   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4907       Paths.front().Access == AS_public) {
4908     // Downcast to the dynamic type...
4909     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4910       return false;
4911     // ... then upcast to the chosen base class subobject.
4912     for (CXXBasePathElement &Elem : Paths.front())
4913       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4914         return false;
4915     return true;
4916   }
4917 
4918   // Otherwise, the runtime check fails.
4919   return RuntimeCheckFailed(&Paths);
4920 }
4921 
4922 namespace {
4923 struct StartLifetimeOfUnionMemberHandler {
4924   const FieldDecl *Field;
4925 
4926   static const AccessKinds AccessKind = AK_Assign;
4927 
4928   APValue getDefaultInitValue(QualType SubobjType) {
4929     if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4930       if (RD->isUnion())
4931         return APValue((const FieldDecl*)nullptr);
4932 
4933       APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4934                      std::distance(RD->field_begin(), RD->field_end()));
4935 
4936       unsigned Index = 0;
4937       for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4938              End = RD->bases_end(); I != End; ++I, ++Index)
4939         Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4940 
4941       for (const auto *I : RD->fields()) {
4942         if (I->isUnnamedBitfield())
4943           continue;
4944         Struct.getStructField(I->getFieldIndex()) =
4945             getDefaultInitValue(I->getType());
4946       }
4947       return Struct;
4948     }
4949 
4950     if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4951             SubobjType->getAsArrayTypeUnsafe())) {
4952       APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4953       if (Array.hasArrayFiller())
4954         Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4955       return Array;
4956     }
4957 
4958     return APValue::IndeterminateValue();
4959   }
4960 
4961   typedef bool result_type;
4962   bool failed() { return false; }
4963   bool found(APValue &Subobj, QualType SubobjType) {
4964     // We are supposed to perform no initialization but begin the lifetime of
4965     // the object. We interpret that as meaning to do what default
4966     // initialization of the object would do if all constructors involved were
4967     // trivial:
4968     //  * All base, non-variant member, and array element subobjects' lifetimes
4969     //    begin
4970     //  * No variant members' lifetimes begin
4971     //  * All scalar subobjects whose lifetimes begin have indeterminate values
4972     assert(SubobjType->isUnionType());
4973     if (!declaresSameEntity(Subobj.getUnionField(), Field))
4974       Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4975     return true;
4976   }
4977   bool found(APSInt &Value, QualType SubobjType) {
4978     llvm_unreachable("wrong value kind for union object");
4979   }
4980   bool found(APFloat &Value, QualType SubobjType) {
4981     llvm_unreachable("wrong value kind for union object");
4982   }
4983 };
4984 } // end anonymous namespace
4985 
4986 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4987 
4988 /// Handle a builtin simple-assignment or a call to a trivial assignment
4989 /// operator whose left-hand side might involve a union member access. If it
4990 /// does, implicitly start the lifetime of any accessed union elements per
4991 /// C++20 [class.union]5.
4992 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4993                                           const LValue &LHS) {
4994   if (LHS.InvalidBase || LHS.Designator.Invalid)
4995     return false;
4996 
4997   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4998   // C++ [class.union]p5:
4999   //   define the set S(E) of subexpressions of E as follows:
5000   unsigned PathLength = LHS.Designator.Entries.size();
5001   for (const Expr *E = LHSExpr; E != nullptr;) {
5002     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5003     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5004       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5005       if (!FD)
5006         break;
5007 
5008       //    ... and also contains A.B if B names a union member
5009       if (FD->getParent()->isUnion())
5010         UnionPathLengths.push_back({PathLength - 1, FD});
5011 
5012       E = ME->getBase();
5013       --PathLength;
5014       assert(declaresSameEntity(FD,
5015                                 LHS.Designator.Entries[PathLength]
5016                                     .getAsBaseOrMember().getPointer()));
5017 
5018       //   -- If E is of the form A[B] and is interpreted as a built-in array
5019       //      subscripting operator, S(E) is [S(the array operand, if any)].
5020     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5021       // Step over an ArrayToPointerDecay implicit cast.
5022       auto *Base = ASE->getBase()->IgnoreImplicit();
5023       if (!Base->getType()->isArrayType())
5024         break;
5025 
5026       E = Base;
5027       --PathLength;
5028 
5029     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5030       // Step over a derived-to-base conversion.
5031       E = ICE->getSubExpr();
5032       if (ICE->getCastKind() == CK_NoOp)
5033         continue;
5034       if (ICE->getCastKind() != CK_DerivedToBase &&
5035           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5036         break;
5037       // Walk path backwards as we walk up from the base to the derived class.
5038       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5039         --PathLength;
5040         (void)Elt;
5041         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5042                                   LHS.Designator.Entries[PathLength]
5043                                       .getAsBaseOrMember().getPointer()));
5044       }
5045 
5046     //   -- Otherwise, S(E) is empty.
5047     } else {
5048       break;
5049     }
5050   }
5051 
5052   // Common case: no unions' lifetimes are started.
5053   if (UnionPathLengths.empty())
5054     return true;
5055 
5056   //   if modification of X [would access an inactive union member], an object
5057   //   of the type of X is implicitly created
5058   CompleteObject Obj =
5059       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5060   if (!Obj)
5061     return false;
5062   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5063            llvm::reverse(UnionPathLengths)) {
5064     // Form a designator for the union object.
5065     SubobjectDesignator D = LHS.Designator;
5066     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5067 
5068     StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5069     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5070       return false;
5071   }
5072 
5073   return true;
5074 }
5075 
5076 /// Determine if a class has any fields that might need to be copied by a
5077 /// trivial copy or move operation.
5078 static bool hasFields(const CXXRecordDecl *RD) {
5079   if (!RD || RD->isEmpty())
5080     return false;
5081   for (auto *FD : RD->fields()) {
5082     if (FD->isUnnamedBitfield())
5083       continue;
5084     return true;
5085   }
5086   for (auto &Base : RD->bases())
5087     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5088       return true;
5089   return false;
5090 }
5091 
5092 namespace {
5093 typedef SmallVector<APValue, 8> ArgVector;
5094 }
5095 
5096 /// EvaluateArgs - Evaluate the arguments to a function call.
5097 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5098                          EvalInfo &Info, const FunctionDecl *Callee) {
5099   bool Success = true;
5100   llvm::SmallBitVector ForbiddenNullArgs;
5101   if (Callee->hasAttr<NonNullAttr>()) {
5102     ForbiddenNullArgs.resize(Args.size());
5103     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5104       if (!Attr->args_size()) {
5105         ForbiddenNullArgs.set();
5106         break;
5107       } else
5108         for (auto Idx : Attr->args()) {
5109           unsigned ASTIdx = Idx.getASTIndex();
5110           if (ASTIdx >= Args.size())
5111             continue;
5112           ForbiddenNullArgs[ASTIdx] = 1;
5113         }
5114     }
5115   }
5116   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5117        I != E; ++I) {
5118     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5119       // If we're checking for a potential constant expression, evaluate all
5120       // initializers even if some of them fail.
5121       if (!Info.noteFailure())
5122         return false;
5123       Success = false;
5124     } else if (!ForbiddenNullArgs.empty() &&
5125                ForbiddenNullArgs[I - Args.begin()] &&
5126                ArgValues[I - Args.begin()].isNullPointer()) {
5127       Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5128       if (!Info.noteFailure())
5129         return false;
5130       Success = false;
5131     }
5132   }
5133   return Success;
5134 }
5135 
5136 /// Evaluate a function call.
5137 static bool HandleFunctionCall(SourceLocation CallLoc,
5138                                const FunctionDecl *Callee, const LValue *This,
5139                                ArrayRef<const Expr*> Args, const Stmt *Body,
5140                                EvalInfo &Info, APValue &Result,
5141                                const LValue *ResultSlot) {
5142   ArgVector ArgValues(Args.size());
5143   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5144     return false;
5145 
5146   if (!Info.CheckCallLimit(CallLoc))
5147     return false;
5148 
5149   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5150 
5151   // For a trivial copy or move assignment, perform an APValue copy. This is
5152   // essential for unions, where the operations performed by the assignment
5153   // operator cannot be represented as statements.
5154   //
5155   // Skip this for non-union classes with no fields; in that case, the defaulted
5156   // copy/move does not actually read the object.
5157   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5158   if (MD && MD->isDefaulted() &&
5159       (MD->getParent()->isUnion() ||
5160        (MD->isTrivial() && hasFields(MD->getParent())))) {
5161     assert(This &&
5162            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5163     LValue RHS;
5164     RHS.setFrom(Info.Ctx, ArgValues[0]);
5165     APValue RHSValue;
5166     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5167                                         RHS, RHSValue))
5168       return false;
5169     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5170         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5171       return false;
5172     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5173                           RHSValue))
5174       return false;
5175     This->moveInto(Result);
5176     return true;
5177   } else if (MD && isLambdaCallOperator(MD)) {
5178     // We're in a lambda; determine the lambda capture field maps unless we're
5179     // just constexpr checking a lambda's call operator. constexpr checking is
5180     // done before the captures have been added to the closure object (unless
5181     // we're inferring constexpr-ness), so we don't have access to them in this
5182     // case. But since we don't need the captures to constexpr check, we can
5183     // just ignore them.
5184     if (!Info.checkingPotentialConstantExpression())
5185       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5186                                         Frame.LambdaThisCaptureField);
5187   }
5188 
5189   StmtResult Ret = {Result, ResultSlot};
5190   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5191   if (ESR == ESR_Succeeded) {
5192     if (Callee->getReturnType()->isVoidType())
5193       return true;
5194     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5195   }
5196   return ESR == ESR_Returned;
5197 }
5198 
5199 /// Evaluate a constructor call.
5200 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5201                                   APValue *ArgValues,
5202                                   const CXXConstructorDecl *Definition,
5203                                   EvalInfo &Info, APValue &Result) {
5204   SourceLocation CallLoc = E->getExprLoc();
5205   if (!Info.CheckCallLimit(CallLoc))
5206     return false;
5207 
5208   const CXXRecordDecl *RD = Definition->getParent();
5209   if (RD->getNumVBases()) {
5210     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5211     return false;
5212   }
5213 
5214   EvalInfo::EvaluatingConstructorRAII EvalObj(
5215       Info,
5216       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5217       RD->getNumBases());
5218   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5219 
5220   // FIXME: Creating an APValue just to hold a nonexistent return value is
5221   // wasteful.
5222   APValue RetVal;
5223   StmtResult Ret = {RetVal, nullptr};
5224 
5225   // If it's a delegating constructor, delegate.
5226   if (Definition->isDelegatingConstructor()) {
5227     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5228     {
5229       FullExpressionRAII InitScope(Info);
5230       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5231         return false;
5232     }
5233     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5234   }
5235 
5236   // For a trivial copy or move constructor, perform an APValue copy. This is
5237   // essential for unions (or classes with anonymous union members), where the
5238   // operations performed by the constructor cannot be represented by
5239   // ctor-initializers.
5240   //
5241   // Skip this for empty non-union classes; we should not perform an
5242   // lvalue-to-rvalue conversion on them because their copy constructor does not
5243   // actually read them.
5244   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5245       (Definition->getParent()->isUnion() ||
5246        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5247     LValue RHS;
5248     RHS.setFrom(Info.Ctx, ArgValues[0]);
5249     return handleLValueToRValueConversion(
5250         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5251         RHS, Result);
5252   }
5253 
5254   // Reserve space for the struct members.
5255   if (!RD->isUnion() && !Result.hasValue())
5256     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5257                      std::distance(RD->field_begin(), RD->field_end()));
5258 
5259   if (RD->isInvalidDecl()) return false;
5260   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5261 
5262   // A scope for temporaries lifetime-extended by reference members.
5263   BlockScopeRAII LifetimeExtendedScope(Info);
5264 
5265   bool Success = true;
5266   unsigned BasesSeen = 0;
5267 #ifndef NDEBUG
5268   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5269 #endif
5270   for (const auto *I : Definition->inits()) {
5271     LValue Subobject = This;
5272     LValue SubobjectParent = This;
5273     APValue *Value = &Result;
5274 
5275     // Determine the subobject to initialize.
5276     FieldDecl *FD = nullptr;
5277     if (I->isBaseInitializer()) {
5278       QualType BaseType(I->getBaseClass(), 0);
5279 #ifndef NDEBUG
5280       // Non-virtual base classes are initialized in the order in the class
5281       // definition. We have already checked for virtual base classes.
5282       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5283       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5284              "base class initializers not in expected order");
5285       ++BaseIt;
5286 #endif
5287       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5288                                   BaseType->getAsCXXRecordDecl(), &Layout))
5289         return false;
5290       Value = &Result.getStructBase(BasesSeen++);
5291     } else if ((FD = I->getMember())) {
5292       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5293         return false;
5294       if (RD->isUnion()) {
5295         Result = APValue(FD);
5296         Value = &Result.getUnionValue();
5297       } else {
5298         Value = &Result.getStructField(FD->getFieldIndex());
5299       }
5300     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5301       // Walk the indirect field decl's chain to find the object to initialize,
5302       // and make sure we've initialized every step along it.
5303       auto IndirectFieldChain = IFD->chain();
5304       for (auto *C : IndirectFieldChain) {
5305         FD = cast<FieldDecl>(C);
5306         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5307         // Switch the union field if it differs. This happens if we had
5308         // preceding zero-initialization, and we're now initializing a union
5309         // subobject other than the first.
5310         // FIXME: In this case, the values of the other subobjects are
5311         // specified, since zero-initialization sets all padding bits to zero.
5312         if (!Value->hasValue() ||
5313             (Value->isUnion() && Value->getUnionField() != FD)) {
5314           if (CD->isUnion())
5315             *Value = APValue(FD);
5316           else
5317             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5318                              std::distance(CD->field_begin(), CD->field_end()));
5319         }
5320         // Store Subobject as its parent before updating it for the last element
5321         // in the chain.
5322         if (C == IndirectFieldChain.back())
5323           SubobjectParent = Subobject;
5324         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5325           return false;
5326         if (CD->isUnion())
5327           Value = &Value->getUnionValue();
5328         else
5329           Value = &Value->getStructField(FD->getFieldIndex());
5330       }
5331     } else {
5332       llvm_unreachable("unknown base initializer kind");
5333     }
5334 
5335     // Need to override This for implicit field initializers as in this case
5336     // This refers to innermost anonymous struct/union containing initializer,
5337     // not to currently constructed class.
5338     const Expr *Init = I->getInit();
5339     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5340                                   isa<CXXDefaultInitExpr>(Init));
5341     FullExpressionRAII InitScope(Info);
5342     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5343         (FD && FD->isBitField() &&
5344          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5345       // If we're checking for a potential constant expression, evaluate all
5346       // initializers even if some of them fail.
5347       if (!Info.noteFailure())
5348         return false;
5349       Success = false;
5350     }
5351 
5352     // This is the point at which the dynamic type of the object becomes this
5353     // class type.
5354     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5355       EvalObj.finishedConstructingBases();
5356   }
5357 
5358   return Success &&
5359          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5360 }
5361 
5362 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5363                                   ArrayRef<const Expr*> Args,
5364                                   const CXXConstructorDecl *Definition,
5365                                   EvalInfo &Info, APValue &Result) {
5366   ArgVector ArgValues(Args.size());
5367   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5368     return false;
5369 
5370   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5371                                Info, Result);
5372 }
5373 
5374 //===----------------------------------------------------------------------===//
5375 // Generic Evaluation
5376 //===----------------------------------------------------------------------===//
5377 namespace {
5378 
5379 template <class Derived>
5380 class ExprEvaluatorBase
5381   : public ConstStmtVisitor<Derived, bool> {
5382 private:
5383   Derived &getDerived() { return static_cast<Derived&>(*this); }
5384   bool DerivedSuccess(const APValue &V, const Expr *E) {
5385     return getDerived().Success(V, E);
5386   }
5387   bool DerivedZeroInitialization(const Expr *E) {
5388     return getDerived().ZeroInitialization(E);
5389   }
5390 
5391   // Check whether a conditional operator with a non-constant condition is a
5392   // potential constant expression. If neither arm is a potential constant
5393   // expression, then the conditional operator is not either.
5394   template<typename ConditionalOperator>
5395   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5396     assert(Info.checkingPotentialConstantExpression());
5397 
5398     // Speculatively evaluate both arms.
5399     SmallVector<PartialDiagnosticAt, 8> Diag;
5400     {
5401       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5402       StmtVisitorTy::Visit(E->getFalseExpr());
5403       if (Diag.empty())
5404         return;
5405     }
5406 
5407     {
5408       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5409       Diag.clear();
5410       StmtVisitorTy::Visit(E->getTrueExpr());
5411       if (Diag.empty())
5412         return;
5413     }
5414 
5415     Error(E, diag::note_constexpr_conditional_never_const);
5416   }
5417 
5418 
5419   template<typename ConditionalOperator>
5420   bool HandleConditionalOperator(const ConditionalOperator *E) {
5421     bool BoolResult;
5422     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5423       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5424         CheckPotentialConstantConditional(E);
5425         return false;
5426       }
5427       if (Info.noteFailure()) {
5428         StmtVisitorTy::Visit(E->getTrueExpr());
5429         StmtVisitorTy::Visit(E->getFalseExpr());
5430       }
5431       return false;
5432     }
5433 
5434     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5435     return StmtVisitorTy::Visit(EvalExpr);
5436   }
5437 
5438 protected:
5439   EvalInfo &Info;
5440   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5441   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5442 
5443   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5444     return Info.CCEDiag(E, D);
5445   }
5446 
5447   bool ZeroInitialization(const Expr *E) { return Error(E); }
5448 
5449 public:
5450   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5451 
5452   EvalInfo &getEvalInfo() { return Info; }
5453 
5454   /// Report an evaluation error. This should only be called when an error is
5455   /// first discovered. When propagating an error, just return false.
5456   bool Error(const Expr *E, diag::kind D) {
5457     Info.FFDiag(E, D);
5458     return false;
5459   }
5460   bool Error(const Expr *E) {
5461     return Error(E, diag::note_invalid_subexpr_in_const_expr);
5462   }
5463 
5464   bool VisitStmt(const Stmt *) {
5465     llvm_unreachable("Expression evaluator should not be called on stmts");
5466   }
5467   bool VisitExpr(const Expr *E) {
5468     return Error(E);
5469   }
5470 
5471   bool VisitConstantExpr(const ConstantExpr *E)
5472     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5473   bool VisitParenExpr(const ParenExpr *E)
5474     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5475   bool VisitUnaryExtension(const UnaryOperator *E)
5476     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5477   bool VisitUnaryPlus(const UnaryOperator *E)
5478     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5479   bool VisitChooseExpr(const ChooseExpr *E)
5480     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5481   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5482     { return StmtVisitorTy::Visit(E->getResultExpr()); }
5483   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5484     { return StmtVisitorTy::Visit(E->getReplacement()); }
5485   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5486     TempVersionRAII RAII(*Info.CurrentCall);
5487     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5488     return StmtVisitorTy::Visit(E->getExpr());
5489   }
5490   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5491     TempVersionRAII RAII(*Info.CurrentCall);
5492     // The initializer may not have been parsed yet, or might be erroneous.
5493     if (!E->getExpr())
5494       return Error(E);
5495     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5496     return StmtVisitorTy::Visit(E->getExpr());
5497   }
5498 
5499   // We cannot create any objects for which cleanups are required, so there is
5500   // nothing to do here; all cleanups must come from unevaluated subexpressions.
5501   bool VisitExprWithCleanups(const ExprWithCleanups *E)
5502     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5503 
5504   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5505     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5506     return static_cast<Derived*>(this)->VisitCastExpr(E);
5507   }
5508   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5509     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5510       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5511     return static_cast<Derived*>(this)->VisitCastExpr(E);
5512   }
5513 
5514   bool VisitBinaryOperator(const BinaryOperator *E) {
5515     switch (E->getOpcode()) {
5516     default:
5517       return Error(E);
5518 
5519     case BO_Comma:
5520       VisitIgnoredValue(E->getLHS());
5521       return StmtVisitorTy::Visit(E->getRHS());
5522 
5523     case BO_PtrMemD:
5524     case BO_PtrMemI: {
5525       LValue Obj;
5526       if (!HandleMemberPointerAccess(Info, E, Obj))
5527         return false;
5528       APValue Result;
5529       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5530         return false;
5531       return DerivedSuccess(Result, E);
5532     }
5533     }
5534   }
5535 
5536   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
5537     // Evaluate and cache the common expression. We treat it as a temporary,
5538     // even though it's not quite the same thing.
5539     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
5540                   Info, E->getCommon()))
5541       return false;
5542 
5543     return HandleConditionalOperator(E);
5544   }
5545 
5546   bool VisitConditionalOperator(const ConditionalOperator *E) {
5547     bool IsBcpCall = false;
5548     // If the condition (ignoring parens) is a __builtin_constant_p call,
5549     // the result is a constant expression if it can be folded without
5550     // side-effects. This is an important GNU extension. See GCC PR38377
5551     // for discussion.
5552     if (const CallExpr *CallCE =
5553           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
5554       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
5555         IsBcpCall = true;
5556 
5557     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5558     // constant expression; we can't check whether it's potentially foldable.
5559     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
5560       return false;
5561 
5562     FoldConstant Fold(Info, IsBcpCall);
5563     if (!HandleConditionalOperator(E)) {
5564       Fold.keepDiagnostics();
5565       return false;
5566     }
5567 
5568     return true;
5569   }
5570 
5571   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
5572     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
5573       return DerivedSuccess(*Value, E);
5574 
5575     const Expr *Source = E->getSourceExpr();
5576     if (!Source)
5577       return Error(E);
5578     if (Source == E) { // sanity checking.
5579       assert(0 && "OpaqueValueExpr recursively refers to itself");
5580       return Error(E);
5581     }
5582     return StmtVisitorTy::Visit(Source);
5583   }
5584 
5585   bool VisitCallExpr(const CallExpr *E) {
5586     APValue Result;
5587     if (!handleCallExpr(E, Result, nullptr))
5588       return false;
5589     return DerivedSuccess(Result, E);
5590   }
5591 
5592   bool handleCallExpr(const CallExpr *E, APValue &Result,
5593                      const LValue *ResultSlot) {
5594     const Expr *Callee = E->getCallee()->IgnoreParens();
5595     QualType CalleeType = Callee->getType();
5596 
5597     const FunctionDecl *FD = nullptr;
5598     LValue *This = nullptr, ThisVal;
5599     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5600     bool HasQualifier = false;
5601 
5602     // Extract function decl and 'this' pointer from the callee.
5603     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
5604       const CXXMethodDecl *Member = nullptr;
5605       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5606         // Explicit bound member calls, such as x.f() or p->g();
5607         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
5608           return false;
5609         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5610         if (!Member)
5611           return Error(Callee);
5612         This = &ThisVal;
5613         HasQualifier = ME->hasQualifier();
5614       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5615         // Indirect bound member calls ('.*' or '->*').
5616         Member = dyn_cast_or_null<CXXMethodDecl>(
5617             HandleMemberPointerAccess(Info, BE, ThisVal, false));
5618         if (!Member)
5619           return Error(Callee);
5620         This = &ThisVal;
5621       } else
5622         return Error(Callee);
5623       FD = Member;
5624     } else if (CalleeType->isFunctionPointerType()) {
5625       LValue Call;
5626       if (!EvaluatePointer(Callee, Call, Info))
5627         return false;
5628 
5629       if (!Call.getLValueOffset().isZero())
5630         return Error(Callee);
5631       FD = dyn_cast_or_null<FunctionDecl>(
5632                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
5633       if (!FD)
5634         return Error(Callee);
5635       // Don't call function pointers which have been cast to some other type.
5636       // Per DR (no number yet), the caller and callee can differ in noexcept.
5637       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5638         CalleeType->getPointeeType(), FD->getType())) {
5639         return Error(E);
5640       }
5641 
5642       // Overloaded operator calls to member functions are represented as normal
5643       // calls with '*this' as the first argument.
5644       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5645       if (MD && !MD->isStatic()) {
5646         // FIXME: When selecting an implicit conversion for an overloaded
5647         // operator delete, we sometimes try to evaluate calls to conversion
5648         // operators without a 'this' parameter!
5649         if (Args.empty())
5650           return Error(E);
5651 
5652         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
5653           return false;
5654         This = &ThisVal;
5655         Args = Args.slice(1);
5656       } else if (MD && MD->isLambdaStaticInvoker()) {
5657         // Map the static invoker for the lambda back to the call operator.
5658         // Conveniently, we don't have to slice out the 'this' argument (as is
5659         // being done for the non-static case), since a static member function
5660         // doesn't have an implicit argument passed in.
5661         const CXXRecordDecl *ClosureClass = MD->getParent();
5662         assert(
5663             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5664             "Number of captures must be zero for conversion to function-ptr");
5665 
5666         const CXXMethodDecl *LambdaCallOp =
5667             ClosureClass->getLambdaCallOperator();
5668 
5669         // Set 'FD', the function that will be called below, to the call
5670         // operator.  If the closure object represents a generic lambda, find
5671         // the corresponding specialization of the call operator.
5672 
5673         if (ClosureClass->isGenericLambda()) {
5674           assert(MD->isFunctionTemplateSpecialization() &&
5675                  "A generic lambda's static-invoker function must be a "
5676                  "template specialization");
5677           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5678           FunctionTemplateDecl *CallOpTemplate =
5679               LambdaCallOp->getDescribedFunctionTemplate();
5680           void *InsertPos = nullptr;
5681           FunctionDecl *CorrespondingCallOpSpecialization =
5682               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5683           assert(CorrespondingCallOpSpecialization &&
5684                  "We must always have a function call operator specialization "
5685                  "that corresponds to our static invoker specialization");
5686           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5687         } else
5688           FD = LambdaCallOp;
5689       }
5690     } else
5691       return Error(E);
5692 
5693     SmallVector<QualType, 4> CovariantAdjustmentPath;
5694     if (This) {
5695       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
5696       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5697         // Perform virtual dispatch, if necessary.
5698         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5699                                    CovariantAdjustmentPath);
5700         if (!FD)
5701           return false;
5702       } else {
5703         // Check that the 'this' pointer points to an object of the right type.
5704         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5705           return false;
5706       }
5707     }
5708 
5709     const FunctionDecl *Definition = nullptr;
5710     Stmt *Body = FD->getBody(Definition);
5711 
5712     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5713         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
5714                             Result, ResultSlot))
5715       return false;
5716 
5717     if (!CovariantAdjustmentPath.empty() &&
5718         !HandleCovariantReturnAdjustment(Info, E, Result,
5719                                          CovariantAdjustmentPath))
5720       return false;
5721 
5722     return true;
5723   }
5724 
5725   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5726     return StmtVisitorTy::Visit(E->getInitializer());
5727   }
5728   bool VisitInitListExpr(const InitListExpr *E) {
5729     if (E->getNumInits() == 0)
5730       return DerivedZeroInitialization(E);
5731     if (E->getNumInits() == 1)
5732       return StmtVisitorTy::Visit(E->getInit(0));
5733     return Error(E);
5734   }
5735   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5736     return DerivedZeroInitialization(E);
5737   }
5738   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5739     return DerivedZeroInitialization(E);
5740   }
5741   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5742     return DerivedZeroInitialization(E);
5743   }
5744 
5745   /// A member expression where the object is a prvalue is itself a prvalue.
5746   bool VisitMemberExpr(const MemberExpr *E) {
5747     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5748            "missing temporary materialization conversion");
5749     assert(!E->isArrow() && "missing call to bound member function?");
5750 
5751     APValue Val;
5752     if (!Evaluate(Val, Info, E->getBase()))
5753       return false;
5754 
5755     QualType BaseTy = E->getBase()->getType();
5756 
5757     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5758     if (!FD) return Error(E);
5759     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5760     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5761            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5762 
5763     // Note: there is no lvalue base here. But this case should only ever
5764     // happen in C or in C++98, where we cannot be evaluating a constexpr
5765     // constructor, which is the only case the base matters.
5766     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
5767     SubobjectDesignator Designator(BaseTy);
5768     Designator.addDeclUnchecked(FD);
5769 
5770     APValue Result;
5771     return extractSubobject(Info, E, Obj, Designator, Result) &&
5772            DerivedSuccess(Result, E);
5773   }
5774 
5775   bool VisitCastExpr(const CastExpr *E) {
5776     switch (E->getCastKind()) {
5777     default:
5778       break;
5779 
5780     case CK_AtomicToNonAtomic: {
5781       APValue AtomicVal;
5782       // This does not need to be done in place even for class/array types:
5783       // atomic-to-non-atomic conversion implies copying the object
5784       // representation.
5785       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5786         return false;
5787       return DerivedSuccess(AtomicVal, E);
5788     }
5789 
5790     case CK_NoOp:
5791     case CK_UserDefinedConversion:
5792       return StmtVisitorTy::Visit(E->getSubExpr());
5793 
5794     case CK_LValueToRValue: {
5795       LValue LVal;
5796       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5797         return false;
5798       APValue RVal;
5799       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5800       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5801                                           LVal, RVal))
5802         return false;
5803       return DerivedSuccess(RVal, E);
5804     }
5805     }
5806 
5807     return Error(E);
5808   }
5809 
5810   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5811     return VisitUnaryPostIncDec(UO);
5812   }
5813   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5814     return VisitUnaryPostIncDec(UO);
5815   }
5816   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5817     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5818       return Error(UO);
5819 
5820     LValue LVal;
5821     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5822       return false;
5823     APValue RVal;
5824     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5825                       UO->isIncrementOp(), &RVal))
5826       return false;
5827     return DerivedSuccess(RVal, UO);
5828   }
5829 
5830   bool VisitStmtExpr(const StmtExpr *E) {
5831     // We will have checked the full-expressions inside the statement expression
5832     // when they were completed, and don't need to check them again now.
5833     if (Info.checkingForOverflow())
5834       return Error(E);
5835 
5836     BlockScopeRAII Scope(Info);
5837     const CompoundStmt *CS = E->getSubStmt();
5838     if (CS->body_empty())
5839       return true;
5840 
5841     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5842                                            BE = CS->body_end();
5843          /**/; ++BI) {
5844       if (BI + 1 == BE) {
5845         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5846         if (!FinalExpr) {
5847           Info.FFDiag((*BI)->getBeginLoc(),
5848                       diag::note_constexpr_stmt_expr_unsupported);
5849           return false;
5850         }
5851         return this->Visit(FinalExpr);
5852       }
5853 
5854       APValue ReturnValue;
5855       StmtResult Result = { ReturnValue, nullptr };
5856       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5857       if (ESR != ESR_Succeeded) {
5858         // FIXME: If the statement-expression terminated due to 'return',
5859         // 'break', or 'continue', it would be nice to propagate that to
5860         // the outer statement evaluation rather than bailing out.
5861         if (ESR != ESR_Failed)
5862           Info.FFDiag((*BI)->getBeginLoc(),
5863                       diag::note_constexpr_stmt_expr_unsupported);
5864         return false;
5865       }
5866     }
5867 
5868     llvm_unreachable("Return from function from the loop above.");
5869   }
5870 
5871   /// Visit a value which is evaluated, but whose value is ignored.
5872   void VisitIgnoredValue(const Expr *E) {
5873     EvaluateIgnoredValue(Info, E);
5874   }
5875 
5876   /// Potentially visit a MemberExpr's base expression.
5877   void VisitIgnoredBaseExpression(const Expr *E) {
5878     // While MSVC doesn't evaluate the base expression, it does diagnose the
5879     // presence of side-effecting behavior.
5880     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5881       return;
5882     VisitIgnoredValue(E);
5883   }
5884 };
5885 
5886 } // namespace
5887 
5888 //===----------------------------------------------------------------------===//
5889 // Common base class for lvalue and temporary evaluation.
5890 //===----------------------------------------------------------------------===//
5891 namespace {
5892 template<class Derived>
5893 class LValueExprEvaluatorBase
5894   : public ExprEvaluatorBase<Derived> {
5895 protected:
5896   LValue &Result;
5897   bool InvalidBaseOK;
5898   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5899   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5900 
5901   bool Success(APValue::LValueBase B) {
5902     Result.set(B);
5903     return true;
5904   }
5905 
5906   bool evaluatePointer(const Expr *E, LValue &Result) {
5907     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5908   }
5909 
5910 public:
5911   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5912       : ExprEvaluatorBaseTy(Info), Result(Result),
5913         InvalidBaseOK(InvalidBaseOK) {}
5914 
5915   bool Success(const APValue &V, const Expr *E) {
5916     Result.setFrom(this->Info.Ctx, V);
5917     return true;
5918   }
5919 
5920   bool VisitMemberExpr(const MemberExpr *E) {
5921     // Handle non-static data members.
5922     QualType BaseTy;
5923     bool EvalOK;
5924     if (E->isArrow()) {
5925       EvalOK = evaluatePointer(E->getBase(), Result);
5926       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5927     } else if (E->getBase()->isRValue()) {
5928       assert(E->getBase()->getType()->isRecordType());
5929       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5930       BaseTy = E->getBase()->getType();
5931     } else {
5932       EvalOK = this->Visit(E->getBase());
5933       BaseTy = E->getBase()->getType();
5934     }
5935     if (!EvalOK) {
5936       if (!InvalidBaseOK)
5937         return false;
5938       Result.setInvalid(E);
5939       return true;
5940     }
5941 
5942     const ValueDecl *MD = E->getMemberDecl();
5943     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5944       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5945              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5946       (void)BaseTy;
5947       if (!HandleLValueMember(this->Info, E, Result, FD))
5948         return false;
5949     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5950       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5951         return false;
5952     } else
5953       return this->Error(E);
5954 
5955     if (MD->getType()->isReferenceType()) {
5956       APValue RefValue;
5957       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5958                                           RefValue))
5959         return false;
5960       return Success(RefValue, E);
5961     }
5962     return true;
5963   }
5964 
5965   bool VisitBinaryOperator(const BinaryOperator *E) {
5966     switch (E->getOpcode()) {
5967     default:
5968       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5969 
5970     case BO_PtrMemD:
5971     case BO_PtrMemI:
5972       return HandleMemberPointerAccess(this->Info, E, Result);
5973     }
5974   }
5975 
5976   bool VisitCastExpr(const CastExpr *E) {
5977     switch (E->getCastKind()) {
5978     default:
5979       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5980 
5981     case CK_DerivedToBase:
5982     case CK_UncheckedDerivedToBase:
5983       if (!this->Visit(E->getSubExpr()))
5984         return false;
5985 
5986       // Now figure out the necessary offset to add to the base LV to get from
5987       // the derived class to the base class.
5988       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5989                                   Result);
5990     }
5991   }
5992 };
5993 }
5994 
5995 //===----------------------------------------------------------------------===//
5996 // LValue Evaluation
5997 //
5998 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5999 // function designators (in C), decl references to void objects (in C), and
6000 // temporaries (if building with -Wno-address-of-temporary).
6001 //
6002 // LValue evaluation produces values comprising a base expression of one of the
6003 // following types:
6004 // - Declarations
6005 //  * VarDecl
6006 //  * FunctionDecl
6007 // - Literals
6008 //  * CompoundLiteralExpr in C (and in global scope in C++)
6009 //  * StringLiteral
6010 //  * PredefinedExpr
6011 //  * ObjCStringLiteralExpr
6012 //  * ObjCEncodeExpr
6013 //  * AddrLabelExpr
6014 //  * BlockExpr
6015 //  * CallExpr for a MakeStringConstant builtin
6016 // - typeid(T) expressions, as TypeInfoLValues
6017 // - Locals and temporaries
6018 //  * MaterializeTemporaryExpr
6019 //  * Any Expr, with a CallIndex indicating the function in which the temporary
6020 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
6021 //    from the AST (FIXME).
6022 //  * A MaterializeTemporaryExpr that has static storage duration, with no
6023 //    CallIndex, for a lifetime-extended temporary.
6024 // plus an offset in bytes.
6025 //===----------------------------------------------------------------------===//
6026 namespace {
6027 class LValueExprEvaluator
6028   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6029 public:
6030   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6031     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6032 
6033   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6034   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6035 
6036   bool VisitDeclRefExpr(const DeclRefExpr *E);
6037   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6038   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6039   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6040   bool VisitMemberExpr(const MemberExpr *E);
6041   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6042   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6043   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6044   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6045   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6046   bool VisitUnaryDeref(const UnaryOperator *E);
6047   bool VisitUnaryReal(const UnaryOperator *E);
6048   bool VisitUnaryImag(const UnaryOperator *E);
6049   bool VisitUnaryPreInc(const UnaryOperator *UO) {
6050     return VisitUnaryPreIncDec(UO);
6051   }
6052   bool VisitUnaryPreDec(const UnaryOperator *UO) {
6053     return VisitUnaryPreIncDec(UO);
6054   }
6055   bool VisitBinAssign(const BinaryOperator *BO);
6056   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6057 
6058   bool VisitCastExpr(const CastExpr *E) {
6059     switch (E->getCastKind()) {
6060     default:
6061       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6062 
6063     case CK_LValueBitCast:
6064       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6065       if (!Visit(E->getSubExpr()))
6066         return false;
6067       Result.Designator.setInvalid();
6068       return true;
6069 
6070     case CK_BaseToDerived:
6071       if (!Visit(E->getSubExpr()))
6072         return false;
6073       return HandleBaseToDerivedCast(Info, E, Result);
6074 
6075     case CK_Dynamic:
6076       if (!Visit(E->getSubExpr()))
6077         return false;
6078       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6079     }
6080   }
6081 };
6082 } // end anonymous namespace
6083 
6084 /// Evaluate an expression as an lvalue. This can be legitimately called on
6085 /// expressions which are not glvalues, in three cases:
6086 ///  * function designators in C, and
6087 ///  * "extern void" objects
6088 ///  * @selector() expressions in Objective-C
6089 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6090                            bool InvalidBaseOK) {
6091   assert(E->isGLValue() || E->getType()->isFunctionType() ||
6092          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6093   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6094 }
6095 
6096 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6097   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6098     return Success(FD);
6099   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6100     return VisitVarDecl(E, VD);
6101   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6102     return Visit(BD->getBinding());
6103   return Error(E);
6104 }
6105 
6106 
6107 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6108 
6109   // If we are within a lambda's call operator, check whether the 'VD' referred
6110   // to within 'E' actually represents a lambda-capture that maps to a
6111   // data-member/field within the closure object, and if so, evaluate to the
6112   // field or what the field refers to.
6113   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6114       isa<DeclRefExpr>(E) &&
6115       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6116     // We don't always have a complete capture-map when checking or inferring if
6117     // the function call operator meets the requirements of a constexpr function
6118     // - but we don't need to evaluate the captures to determine constexprness
6119     // (dcl.constexpr C++17).
6120     if (Info.checkingPotentialConstantExpression())
6121       return false;
6122 
6123     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6124       // Start with 'Result' referring to the complete closure object...
6125       Result = *Info.CurrentCall->This;
6126       // ... then update it to refer to the field of the closure object
6127       // that represents the capture.
6128       if (!HandleLValueMember(Info, E, Result, FD))
6129         return false;
6130       // And if the field is of reference type, update 'Result' to refer to what
6131       // the field refers to.
6132       if (FD->getType()->isReferenceType()) {
6133         APValue RVal;
6134         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6135                                             RVal))
6136           return false;
6137         Result.setFrom(Info.Ctx, RVal);
6138       }
6139       return true;
6140     }
6141   }
6142   CallStackFrame *Frame = nullptr;
6143   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6144     // Only if a local variable was declared in the function currently being
6145     // evaluated, do we expect to be able to find its value in the current
6146     // frame. (Otherwise it was likely declared in an enclosing context and
6147     // could either have a valid evaluatable value (for e.g. a constexpr
6148     // variable) or be ill-formed (and trigger an appropriate evaluation
6149     // diagnostic)).
6150     if (Info.CurrentCall->Callee &&
6151         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6152       Frame = Info.CurrentCall;
6153     }
6154   }
6155 
6156   if (!VD->getType()->isReferenceType()) {
6157     if (Frame) {
6158       Result.set({VD, Frame->Index,
6159                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6160       return true;
6161     }
6162     return Success(VD);
6163   }
6164 
6165   APValue *V;
6166   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6167     return false;
6168   if (!V->hasValue()) {
6169     // FIXME: Is it possible for V to be indeterminate here? If so, we should
6170     // adjust the diagnostic to say that.
6171     if (!Info.checkingPotentialConstantExpression())
6172       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6173     return false;
6174   }
6175   return Success(*V, E);
6176 }
6177 
6178 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6179     const MaterializeTemporaryExpr *E) {
6180   // Walk through the expression to find the materialized temporary itself.
6181   SmallVector<const Expr *, 2> CommaLHSs;
6182   SmallVector<SubobjectAdjustment, 2> Adjustments;
6183   const Expr *Inner = E->GetTemporaryExpr()->
6184       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6185 
6186   // If we passed any comma operators, evaluate their LHSs.
6187   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6188     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6189       return false;
6190 
6191   // A materialized temporary with static storage duration can appear within the
6192   // result of a constant expression evaluation, so we need to preserve its
6193   // value for use outside this evaluation.
6194   APValue *Value;
6195   if (E->getStorageDuration() == SD_Static) {
6196     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6197     *Value = APValue();
6198     Result.set(E);
6199   } else {
6200     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6201                              *Info.CurrentCall);
6202   }
6203 
6204   QualType Type = Inner->getType();
6205 
6206   // Materialize the temporary itself.
6207   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6208       (E->getStorageDuration() == SD_Static &&
6209        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6210     *Value = APValue();
6211     return false;
6212   }
6213 
6214   // Adjust our lvalue to refer to the desired subobject.
6215   for (unsigned I = Adjustments.size(); I != 0; /**/) {
6216     --I;
6217     switch (Adjustments[I].Kind) {
6218     case SubobjectAdjustment::DerivedToBaseAdjustment:
6219       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6220                                 Type, Result))
6221         return false;
6222       Type = Adjustments[I].DerivedToBase.BasePath->getType();
6223       break;
6224 
6225     case SubobjectAdjustment::FieldAdjustment:
6226       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6227         return false;
6228       Type = Adjustments[I].Field->getType();
6229       break;
6230 
6231     case SubobjectAdjustment::MemberPointerAdjustment:
6232       if (!HandleMemberPointerAccess(this->Info, Type, Result,
6233                                      Adjustments[I].Ptr.RHS))
6234         return false;
6235       Type = Adjustments[I].Ptr.MPT->getPointeeType();
6236       break;
6237     }
6238   }
6239 
6240   return true;
6241 }
6242 
6243 bool
6244 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6245   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6246          "lvalue compound literal in c++?");
6247   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6248   // only see this when folding in C, so there's no standard to follow here.
6249   return Success(E);
6250 }
6251 
6252 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6253   TypeInfoLValue TypeInfo;
6254 
6255   if (!E->isPotentiallyEvaluated()) {
6256     if (E->isTypeOperand())
6257       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6258     else
6259       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6260   } else {
6261     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6262       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6263         << E->getExprOperand()->getType()
6264         << E->getExprOperand()->getSourceRange();
6265     }
6266 
6267     if (!Visit(E->getExprOperand()))
6268       return false;
6269 
6270     Optional<DynamicType> DynType =
6271         ComputeDynamicType(Info, E, Result, AK_TypeId);
6272     if (!DynType)
6273       return false;
6274 
6275     TypeInfo =
6276         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6277   }
6278 
6279   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6280 }
6281 
6282 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6283   return Success(E);
6284 }
6285 
6286 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6287   // Handle static data members.
6288   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6289     VisitIgnoredBaseExpression(E->getBase());
6290     return VisitVarDecl(E, VD);
6291   }
6292 
6293   // Handle static member functions.
6294   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6295     if (MD->isStatic()) {
6296       VisitIgnoredBaseExpression(E->getBase());
6297       return Success(MD);
6298     }
6299   }
6300 
6301   // Handle non-static data members.
6302   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6303 }
6304 
6305 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6306   // FIXME: Deal with vectors as array subscript bases.
6307   if (E->getBase()->getType()->isVectorType())
6308     return Error(E);
6309 
6310   bool Success = true;
6311   if (!evaluatePointer(E->getBase(), Result)) {
6312     if (!Info.noteFailure())
6313       return false;
6314     Success = false;
6315   }
6316 
6317   APSInt Index;
6318   if (!EvaluateInteger(E->getIdx(), Index, Info))
6319     return false;
6320 
6321   return Success &&
6322          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6323 }
6324 
6325 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6326   return evaluatePointer(E->getSubExpr(), Result);
6327 }
6328 
6329 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6330   if (!Visit(E->getSubExpr()))
6331     return false;
6332   // __real is a no-op on scalar lvalues.
6333   if (E->getSubExpr()->getType()->isAnyComplexType())
6334     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6335   return true;
6336 }
6337 
6338 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6339   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6340          "lvalue __imag__ on scalar?");
6341   if (!Visit(E->getSubExpr()))
6342     return false;
6343   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6344   return true;
6345 }
6346 
6347 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6348   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6349     return Error(UO);
6350 
6351   if (!this->Visit(UO->getSubExpr()))
6352     return false;
6353 
6354   return handleIncDec(
6355       this->Info, UO, Result, UO->getSubExpr()->getType(),
6356       UO->isIncrementOp(), nullptr);
6357 }
6358 
6359 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6360     const CompoundAssignOperator *CAO) {
6361   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6362     return Error(CAO);
6363 
6364   APValue RHS;
6365 
6366   // The overall lvalue result is the result of evaluating the LHS.
6367   if (!this->Visit(CAO->getLHS())) {
6368     if (Info.noteFailure())
6369       Evaluate(RHS, this->Info, CAO->getRHS());
6370     return false;
6371   }
6372 
6373   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6374     return false;
6375 
6376   return handleCompoundAssignment(
6377       this->Info, CAO,
6378       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6379       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6380 }
6381 
6382 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6383   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6384     return Error(E);
6385 
6386   APValue NewVal;
6387 
6388   if (!this->Visit(E->getLHS())) {
6389     if (Info.noteFailure())
6390       Evaluate(NewVal, this->Info, E->getRHS());
6391     return false;
6392   }
6393 
6394   if (!Evaluate(NewVal, this->Info, E->getRHS()))
6395     return false;
6396 
6397   if (Info.getLangOpts().CPlusPlus2a &&
6398       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6399     return false;
6400 
6401   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6402                           NewVal);
6403 }
6404 
6405 //===----------------------------------------------------------------------===//
6406 // Pointer Evaluation
6407 //===----------------------------------------------------------------------===//
6408 
6409 /// Attempts to compute the number of bytes available at the pointer
6410 /// returned by a function with the alloc_size attribute. Returns true if we
6411 /// were successful. Places an unsigned number into `Result`.
6412 ///
6413 /// This expects the given CallExpr to be a call to a function with an
6414 /// alloc_size attribute.
6415 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6416                                             const CallExpr *Call,
6417                                             llvm::APInt &Result) {
6418   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6419 
6420   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6421   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6422   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6423   if (Call->getNumArgs() <= SizeArgNo)
6424     return false;
6425 
6426   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6427     Expr::EvalResult ExprResult;
6428     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6429       return false;
6430     Into = ExprResult.Val.getInt();
6431     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6432       return false;
6433     Into = Into.zextOrSelf(BitsInSizeT);
6434     return true;
6435   };
6436 
6437   APSInt SizeOfElem;
6438   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6439     return false;
6440 
6441   if (!AllocSize->getNumElemsParam().isValid()) {
6442     Result = std::move(SizeOfElem);
6443     return true;
6444   }
6445 
6446   APSInt NumberOfElems;
6447   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6448   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6449     return false;
6450 
6451   bool Overflow;
6452   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6453   if (Overflow)
6454     return false;
6455 
6456   Result = std::move(BytesAvailable);
6457   return true;
6458 }
6459 
6460 /// Convenience function. LVal's base must be a call to an alloc_size
6461 /// function.
6462 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6463                                             const LValue &LVal,
6464                                             llvm::APInt &Result) {
6465   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6466          "Can't get the size of a non alloc_size function");
6467   const auto *Base = LVal.getLValueBase().get<const Expr *>();
6468   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6469   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6470 }
6471 
6472 /// Attempts to evaluate the given LValueBase as the result of a call to
6473 /// a function with the alloc_size attribute. If it was possible to do so, this
6474 /// function will return true, make Result's Base point to said function call,
6475 /// and mark Result's Base as invalid.
6476 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6477                                       LValue &Result) {
6478   if (Base.isNull())
6479     return false;
6480 
6481   // Because we do no form of static analysis, we only support const variables.
6482   //
6483   // Additionally, we can't support parameters, nor can we support static
6484   // variables (in the latter case, use-before-assign isn't UB; in the former,
6485   // we have no clue what they'll be assigned to).
6486   const auto *VD =
6487       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6488   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6489     return false;
6490 
6491   const Expr *Init = VD->getAnyInitializer();
6492   if (!Init)
6493     return false;
6494 
6495   const Expr *E = Init->IgnoreParens();
6496   if (!tryUnwrapAllocSizeCall(E))
6497     return false;
6498 
6499   // Store E instead of E unwrapped so that the type of the LValue's base is
6500   // what the user wanted.
6501   Result.setInvalid(E);
6502 
6503   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6504   Result.addUnsizedArray(Info, E, Pointee);
6505   return true;
6506 }
6507 
6508 namespace {
6509 class PointerExprEvaluator
6510   : public ExprEvaluatorBase<PointerExprEvaluator> {
6511   LValue &Result;
6512   bool InvalidBaseOK;
6513 
6514   bool Success(const Expr *E) {
6515     Result.set(E);
6516     return true;
6517   }
6518 
6519   bool evaluateLValue(const Expr *E, LValue &Result) {
6520     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6521   }
6522 
6523   bool evaluatePointer(const Expr *E, LValue &Result) {
6524     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6525   }
6526 
6527   bool visitNonBuiltinCallExpr(const CallExpr *E);
6528 public:
6529 
6530   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6531       : ExprEvaluatorBaseTy(info), Result(Result),
6532         InvalidBaseOK(InvalidBaseOK) {}
6533 
6534   bool Success(const APValue &V, const Expr *E) {
6535     Result.setFrom(Info.Ctx, V);
6536     return true;
6537   }
6538   bool ZeroInitialization(const Expr *E) {
6539     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6540     Result.setNull(E->getType(), TargetVal);
6541     return true;
6542   }
6543 
6544   bool VisitBinaryOperator(const BinaryOperator *E);
6545   bool VisitCastExpr(const CastExpr* E);
6546   bool VisitUnaryAddrOf(const UnaryOperator *E);
6547   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
6548       { return Success(E); }
6549   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
6550     if (E->isExpressibleAsConstantInitializer())
6551       return Success(E);
6552     if (Info.noteFailure())
6553       EvaluateIgnoredValue(Info, E->getSubExpr());
6554     return Error(E);
6555   }
6556   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
6557       { return Success(E); }
6558   bool VisitCallExpr(const CallExpr *E);
6559   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6560   bool VisitBlockExpr(const BlockExpr *E) {
6561     if (!E->getBlockDecl()->hasCaptures())
6562       return Success(E);
6563     return Error(E);
6564   }
6565   bool VisitCXXThisExpr(const CXXThisExpr *E) {
6566     // Can't look at 'this' when checking a potential constant expression.
6567     if (Info.checkingPotentialConstantExpression())
6568       return false;
6569     if (!Info.CurrentCall->This) {
6570       if (Info.getLangOpts().CPlusPlus11)
6571         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
6572       else
6573         Info.FFDiag(E);
6574       return false;
6575     }
6576     Result = *Info.CurrentCall->This;
6577     // If we are inside a lambda's call operator, the 'this' expression refers
6578     // to the enclosing '*this' object (either by value or reference) which is
6579     // either copied into the closure object's field that represents the '*this'
6580     // or refers to '*this'.
6581     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6582       // Update 'Result' to refer to the data member/field of the closure object
6583       // that represents the '*this' capture.
6584       if (!HandleLValueMember(Info, E, Result,
6585                              Info.CurrentCall->LambdaThisCaptureField))
6586         return false;
6587       // If we captured '*this' by reference, replace the field with its referent.
6588       if (Info.CurrentCall->LambdaThisCaptureField->getType()
6589               ->isPointerType()) {
6590         APValue RVal;
6591         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6592                                             RVal))
6593           return false;
6594 
6595         Result.setFrom(Info.Ctx, RVal);
6596       }
6597     }
6598     return true;
6599   }
6600 
6601   bool VisitSourceLocExpr(const SourceLocExpr *E) {
6602     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6603     APValue LValResult = E->EvaluateInContext(
6604         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6605     Result.setFrom(Info.Ctx, LValResult);
6606     return true;
6607   }
6608 
6609   // FIXME: Missing: @protocol, @selector
6610 };
6611 } // end anonymous namespace
6612 
6613 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6614                             bool InvalidBaseOK) {
6615   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6616   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6617 }
6618 
6619 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6620   if (E->getOpcode() != BO_Add &&
6621       E->getOpcode() != BO_Sub)
6622     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6623 
6624   const Expr *PExp = E->getLHS();
6625   const Expr *IExp = E->getRHS();
6626   if (IExp->getType()->isPointerType())
6627     std::swap(PExp, IExp);
6628 
6629   bool EvalPtrOK = evaluatePointer(PExp, Result);
6630   if (!EvalPtrOK && !Info.noteFailure())
6631     return false;
6632 
6633   llvm::APSInt Offset;
6634   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
6635     return false;
6636 
6637   if (E->getOpcode() == BO_Sub)
6638     negateAsSigned(Offset);
6639 
6640   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
6641   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
6642 }
6643 
6644 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6645   return evaluateLValue(E->getSubExpr(), Result);
6646 }
6647 
6648 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6649   const Expr *SubExpr = E->getSubExpr();
6650 
6651   switch (E->getCastKind()) {
6652   default:
6653     break;
6654 
6655   case CK_BitCast:
6656   case CK_CPointerToObjCPointerCast:
6657   case CK_BlockPointerToObjCPointerCast:
6658   case CK_AnyPointerToBlockPointerCast:
6659   case CK_AddressSpaceConversion:
6660     if (!Visit(SubExpr))
6661       return false;
6662     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6663     // permitted in constant expressions in C++11. Bitcasts from cv void* are
6664     // also static_casts, but we disallow them as a resolution to DR1312.
6665     if (!E->getType()->isVoidPointerType()) {
6666       Result.Designator.setInvalid();
6667       if (SubExpr->getType()->isVoidPointerType())
6668         CCEDiag(E, diag::note_constexpr_invalid_cast)
6669           << 3 << SubExpr->getType();
6670       else
6671         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6672     }
6673     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6674       ZeroInitialization(E);
6675     return true;
6676 
6677   case CK_DerivedToBase:
6678   case CK_UncheckedDerivedToBase:
6679     if (!evaluatePointer(E->getSubExpr(), Result))
6680       return false;
6681     if (!Result.Base && Result.Offset.isZero())
6682       return true;
6683 
6684     // Now figure out the necessary offset to add to the base LV to get from
6685     // the derived class to the base class.
6686     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6687                                   castAs<PointerType>()->getPointeeType(),
6688                                 Result);
6689 
6690   case CK_BaseToDerived:
6691     if (!Visit(E->getSubExpr()))
6692       return false;
6693     if (!Result.Base && Result.Offset.isZero())
6694       return true;
6695     return HandleBaseToDerivedCast(Info, E, Result);
6696 
6697   case CK_Dynamic:
6698     if (!Visit(E->getSubExpr()))
6699       return false;
6700     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6701 
6702   case CK_NullToPointer:
6703     VisitIgnoredValue(E->getSubExpr());
6704     return ZeroInitialization(E);
6705 
6706   case CK_IntegralToPointer: {
6707     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6708 
6709     APValue Value;
6710     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
6711       break;
6712 
6713     if (Value.isInt()) {
6714       unsigned Size = Info.Ctx.getTypeSize(E->getType());
6715       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
6716       Result.Base = (Expr*)nullptr;
6717       Result.InvalidBase = false;
6718       Result.Offset = CharUnits::fromQuantity(N);
6719       Result.Designator.setInvalid();
6720       Result.IsNullPtr = false;
6721       return true;
6722     } else {
6723       // Cast is of an lvalue, no need to change value.
6724       Result.setFrom(Info.Ctx, Value);
6725       return true;
6726     }
6727   }
6728 
6729   case CK_ArrayToPointerDecay: {
6730     if (SubExpr->isGLValue()) {
6731       if (!evaluateLValue(SubExpr, Result))
6732         return false;
6733     } else {
6734       APValue &Value = createTemporary(SubExpr, false, Result,
6735                                        *Info.CurrentCall);
6736       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
6737         return false;
6738     }
6739     // The result is a pointer to the first element of the array.
6740     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6741     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6742       Result.addArray(Info, E, CAT);
6743     else
6744       Result.addUnsizedArray(Info, E, AT->getElementType());
6745     return true;
6746   }
6747 
6748   case CK_FunctionToPointerDecay:
6749     return evaluateLValue(SubExpr, Result);
6750 
6751   case CK_LValueToRValue: {
6752     LValue LVal;
6753     if (!evaluateLValue(E->getSubExpr(), LVal))
6754       return false;
6755 
6756     APValue RVal;
6757     // Note, we use the subexpression's type in order to retain cv-qualifiers.
6758     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6759                                         LVal, RVal))
6760       return InvalidBaseOK &&
6761              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
6762     return Success(RVal, E);
6763   }
6764   }
6765 
6766   return ExprEvaluatorBaseTy::VisitCastExpr(E);
6767 }
6768 
6769 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6770                                 UnaryExprOrTypeTrait ExprKind) {
6771   // C++ [expr.alignof]p3:
6772   //     When alignof is applied to a reference type, the result is the
6773   //     alignment of the referenced type.
6774   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6775     T = Ref->getPointeeType();
6776 
6777   if (T.getQualifiers().hasUnaligned())
6778     return CharUnits::One();
6779 
6780   const bool AlignOfReturnsPreferred =
6781       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6782 
6783   // __alignof is defined to return the preferred alignment.
6784   // Before 8, clang returned the preferred alignment for alignof and _Alignof
6785   // as well.
6786   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6787     return Info.Ctx.toCharUnitsFromBits(
6788       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6789   // alignof and _Alignof are defined to return the ABI alignment.
6790   else if (ExprKind == UETT_AlignOf)
6791     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6792   else
6793     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6794 }
6795 
6796 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6797                                 UnaryExprOrTypeTrait ExprKind) {
6798   E = E->IgnoreParens();
6799 
6800   // The kinds of expressions that we have special-case logic here for
6801   // should be kept up to date with the special checks for those
6802   // expressions in Sema.
6803 
6804   // alignof decl is always accepted, even if it doesn't make sense: we default
6805   // to 1 in those cases.
6806   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6807     return Info.Ctx.getDeclAlign(DRE->getDecl(),
6808                                  /*RefAsPointee*/true);
6809 
6810   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6811     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6812                                  /*RefAsPointee*/true);
6813 
6814   return GetAlignOfType(Info, E->getType(), ExprKind);
6815 }
6816 
6817 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6818 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6819   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6820     return true;
6821 
6822   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6823     return false;
6824 
6825   Result.setInvalid(E);
6826   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6827   Result.addUnsizedArray(Info, E, PointeeTy);
6828   return true;
6829 }
6830 
6831 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6832   if (IsStringLiteralCall(E))
6833     return Success(E);
6834 
6835   if (unsigned BuiltinOp = E->getBuiltinCallee())
6836     return VisitBuiltinCallExpr(E, BuiltinOp);
6837 
6838   return visitNonBuiltinCallExpr(E);
6839 }
6840 
6841 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6842                                                 unsigned BuiltinOp) {
6843   switch (BuiltinOp) {
6844   case Builtin::BI__builtin_addressof:
6845     return evaluateLValue(E->getArg(0), Result);
6846   case Builtin::BI__builtin_assume_aligned: {
6847     // We need to be very careful here because: if the pointer does not have the
6848     // asserted alignment, then the behavior is undefined, and undefined
6849     // behavior is non-constant.
6850     if (!evaluatePointer(E->getArg(0), Result))
6851       return false;
6852 
6853     LValue OffsetResult(Result);
6854     APSInt Alignment;
6855     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6856       return false;
6857     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6858 
6859     if (E->getNumArgs() > 2) {
6860       APSInt Offset;
6861       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6862         return false;
6863 
6864       int64_t AdditionalOffset = -Offset.getZExtValue();
6865       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6866     }
6867 
6868     // If there is a base object, then it must have the correct alignment.
6869     if (OffsetResult.Base) {
6870       CharUnits BaseAlignment;
6871       if (const ValueDecl *VD =
6872           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6873         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6874       } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6875         BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
6876       } else {
6877         BaseAlignment = GetAlignOfType(
6878             Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
6879       }
6880 
6881       if (BaseAlignment < Align) {
6882         Result.Designator.setInvalid();
6883         // FIXME: Add support to Diagnostic for long / long long.
6884         CCEDiag(E->getArg(0),
6885                 diag::note_constexpr_baa_insufficient_alignment) << 0
6886           << (unsigned)BaseAlignment.getQuantity()
6887           << (unsigned)Align.getQuantity();
6888         return false;
6889       }
6890     }
6891 
6892     // The offset must also have the correct alignment.
6893     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6894       Result.Designator.setInvalid();
6895 
6896       (OffsetResult.Base
6897            ? CCEDiag(E->getArg(0),
6898                      diag::note_constexpr_baa_insufficient_alignment) << 1
6899            : CCEDiag(E->getArg(0),
6900                      diag::note_constexpr_baa_value_insufficient_alignment))
6901         << (int)OffsetResult.Offset.getQuantity()
6902         << (unsigned)Align.getQuantity();
6903       return false;
6904     }
6905 
6906     return true;
6907   }
6908   case Builtin::BI__builtin_launder:
6909     return evaluatePointer(E->getArg(0), Result);
6910   case Builtin::BIstrchr:
6911   case Builtin::BIwcschr:
6912   case Builtin::BImemchr:
6913   case Builtin::BIwmemchr:
6914     if (Info.getLangOpts().CPlusPlus11)
6915       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6916         << /*isConstexpr*/0 << /*isConstructor*/0
6917         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6918     else
6919       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6920     LLVM_FALLTHROUGH;
6921   case Builtin::BI__builtin_strchr:
6922   case Builtin::BI__builtin_wcschr:
6923   case Builtin::BI__builtin_memchr:
6924   case Builtin::BI__builtin_char_memchr:
6925   case Builtin::BI__builtin_wmemchr: {
6926     if (!Visit(E->getArg(0)))
6927       return false;
6928     APSInt Desired;
6929     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6930       return false;
6931     uint64_t MaxLength = uint64_t(-1);
6932     if (BuiltinOp != Builtin::BIstrchr &&
6933         BuiltinOp != Builtin::BIwcschr &&
6934         BuiltinOp != Builtin::BI__builtin_strchr &&
6935         BuiltinOp != Builtin::BI__builtin_wcschr) {
6936       APSInt N;
6937       if (!EvaluateInteger(E->getArg(2), N, Info))
6938         return false;
6939       MaxLength = N.getExtValue();
6940     }
6941     // We cannot find the value if there are no candidates to match against.
6942     if (MaxLength == 0u)
6943       return ZeroInitialization(E);
6944     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6945         Result.Designator.Invalid)
6946       return false;
6947     QualType CharTy = Result.Designator.getType(Info.Ctx);
6948     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6949                      BuiltinOp == Builtin::BI__builtin_memchr;
6950     assert(IsRawByte ||
6951            Info.Ctx.hasSameUnqualifiedType(
6952                CharTy, E->getArg(0)->getType()->getPointeeType()));
6953     // Pointers to const void may point to objects of incomplete type.
6954     if (IsRawByte && CharTy->isIncompleteType()) {
6955       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6956       return false;
6957     }
6958     // Give up on byte-oriented matching against multibyte elements.
6959     // FIXME: We can compare the bytes in the correct order.
6960     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6961       return false;
6962     // Figure out what value we're actually looking for (after converting to
6963     // the corresponding unsigned type if necessary).
6964     uint64_t DesiredVal;
6965     bool StopAtNull = false;
6966     switch (BuiltinOp) {
6967     case Builtin::BIstrchr:
6968     case Builtin::BI__builtin_strchr:
6969       // strchr compares directly to the passed integer, and therefore
6970       // always fails if given an int that is not a char.
6971       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6972                                                   E->getArg(1)->getType(),
6973                                                   Desired),
6974                                Desired))
6975         return ZeroInitialization(E);
6976       StopAtNull = true;
6977       LLVM_FALLTHROUGH;
6978     case Builtin::BImemchr:
6979     case Builtin::BI__builtin_memchr:
6980     case Builtin::BI__builtin_char_memchr:
6981       // memchr compares by converting both sides to unsigned char. That's also
6982       // correct for strchr if we get this far (to cope with plain char being
6983       // unsigned in the strchr case).
6984       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6985       break;
6986 
6987     case Builtin::BIwcschr:
6988     case Builtin::BI__builtin_wcschr:
6989       StopAtNull = true;
6990       LLVM_FALLTHROUGH;
6991     case Builtin::BIwmemchr:
6992     case Builtin::BI__builtin_wmemchr:
6993       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6994       DesiredVal = Desired.getZExtValue();
6995       break;
6996     }
6997 
6998     for (; MaxLength; --MaxLength) {
6999       APValue Char;
7000       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7001           !Char.isInt())
7002         return false;
7003       if (Char.getInt().getZExtValue() == DesiredVal)
7004         return true;
7005       if (StopAtNull && !Char.getInt())
7006         break;
7007       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7008         return false;
7009     }
7010     // Not found: return nullptr.
7011     return ZeroInitialization(E);
7012   }
7013 
7014   case Builtin::BImemcpy:
7015   case Builtin::BImemmove:
7016   case Builtin::BIwmemcpy:
7017   case Builtin::BIwmemmove:
7018     if (Info.getLangOpts().CPlusPlus11)
7019       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7020         << /*isConstexpr*/0 << /*isConstructor*/0
7021         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7022     else
7023       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7024     LLVM_FALLTHROUGH;
7025   case Builtin::BI__builtin_memcpy:
7026   case Builtin::BI__builtin_memmove:
7027   case Builtin::BI__builtin_wmemcpy:
7028   case Builtin::BI__builtin_wmemmove: {
7029     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7030                  BuiltinOp == Builtin::BIwmemmove ||
7031                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7032                  BuiltinOp == Builtin::BI__builtin_wmemmove;
7033     bool Move = BuiltinOp == Builtin::BImemmove ||
7034                 BuiltinOp == Builtin::BIwmemmove ||
7035                 BuiltinOp == Builtin::BI__builtin_memmove ||
7036                 BuiltinOp == Builtin::BI__builtin_wmemmove;
7037 
7038     // The result of mem* is the first argument.
7039     if (!Visit(E->getArg(0)))
7040       return false;
7041     LValue Dest = Result;
7042 
7043     LValue Src;
7044     if (!EvaluatePointer(E->getArg(1), Src, Info))
7045       return false;
7046 
7047     APSInt N;
7048     if (!EvaluateInteger(E->getArg(2), N, Info))
7049       return false;
7050     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7051 
7052     // If the size is zero, we treat this as always being a valid no-op.
7053     // (Even if one of the src and dest pointers is null.)
7054     if (!N)
7055       return true;
7056 
7057     // Otherwise, if either of the operands is null, we can't proceed. Don't
7058     // try to determine the type of the copied objects, because there aren't
7059     // any.
7060     if (!Src.Base || !Dest.Base) {
7061       APValue Val;
7062       (!Src.Base ? Src : Dest).moveInto(Val);
7063       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7064           << Move << WChar << !!Src.Base
7065           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7066       return false;
7067     }
7068     if (Src.Designator.Invalid || Dest.Designator.Invalid)
7069       return false;
7070 
7071     // We require that Src and Dest are both pointers to arrays of
7072     // trivially-copyable type. (For the wide version, the designator will be
7073     // invalid if the designated object is not a wchar_t.)
7074     QualType T = Dest.Designator.getType(Info.Ctx);
7075     QualType SrcT = Src.Designator.getType(Info.Ctx);
7076     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7077       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7078       return false;
7079     }
7080     if (T->isIncompleteType()) {
7081       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7082       return false;
7083     }
7084     if (!T.isTriviallyCopyableType(Info.Ctx)) {
7085       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7086       return false;
7087     }
7088 
7089     // Figure out how many T's we're copying.
7090     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7091     if (!WChar) {
7092       uint64_t Remainder;
7093       llvm::APInt OrigN = N;
7094       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7095       if (Remainder) {
7096         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7097             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7098             << (unsigned)TSize;
7099         return false;
7100       }
7101     }
7102 
7103     // Check that the copying will remain within the arrays, just so that we
7104     // can give a more meaningful diagnostic. This implicitly also checks that
7105     // N fits into 64 bits.
7106     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7107     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7108     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7109       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7110           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7111           << N.toString(10, /*Signed*/false);
7112       return false;
7113     }
7114     uint64_t NElems = N.getZExtValue();
7115     uint64_t NBytes = NElems * TSize;
7116 
7117     // Check for overlap.
7118     int Direction = 1;
7119     if (HasSameBase(Src, Dest)) {
7120       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7121       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7122       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7123         // Dest is inside the source region.
7124         if (!Move) {
7125           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7126           return false;
7127         }
7128         // For memmove and friends, copy backwards.
7129         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7130             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7131           return false;
7132         Direction = -1;
7133       } else if (!Move && SrcOffset >= DestOffset &&
7134                  SrcOffset - DestOffset < NBytes) {
7135         // Src is inside the destination region for memcpy: invalid.
7136         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7137         return false;
7138       }
7139     }
7140 
7141     while (true) {
7142       APValue Val;
7143       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7144           !handleAssignment(Info, E, Dest, T, Val))
7145         return false;
7146       // Do not iterate past the last element; if we're copying backwards, that
7147       // might take us off the start of the array.
7148       if (--NElems == 0)
7149         return true;
7150       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7151           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7152         return false;
7153     }
7154   }
7155 
7156   default:
7157     return visitNonBuiltinCallExpr(E);
7158   }
7159 }
7160 
7161 //===----------------------------------------------------------------------===//
7162 // Member Pointer Evaluation
7163 //===----------------------------------------------------------------------===//
7164 
7165 namespace {
7166 class MemberPointerExprEvaluator
7167   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7168   MemberPtr &Result;
7169 
7170   bool Success(const ValueDecl *D) {
7171     Result = MemberPtr(D);
7172     return true;
7173   }
7174 public:
7175 
7176   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7177     : ExprEvaluatorBaseTy(Info), Result(Result) {}
7178 
7179   bool Success(const APValue &V, const Expr *E) {
7180     Result.setFrom(V);
7181     return true;
7182   }
7183   bool ZeroInitialization(const Expr *E) {
7184     return Success((const ValueDecl*)nullptr);
7185   }
7186 
7187   bool VisitCastExpr(const CastExpr *E);
7188   bool VisitUnaryAddrOf(const UnaryOperator *E);
7189 };
7190 } // end anonymous namespace
7191 
7192 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7193                                   EvalInfo &Info) {
7194   assert(E->isRValue() && E->getType()->isMemberPointerType());
7195   return MemberPointerExprEvaluator(Info, Result).Visit(E);
7196 }
7197 
7198 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7199   switch (E->getCastKind()) {
7200   default:
7201     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7202 
7203   case CK_NullToMemberPointer:
7204     VisitIgnoredValue(E->getSubExpr());
7205     return ZeroInitialization(E);
7206 
7207   case CK_BaseToDerivedMemberPointer: {
7208     if (!Visit(E->getSubExpr()))
7209       return false;
7210     if (E->path_empty())
7211       return true;
7212     // Base-to-derived member pointer casts store the path in derived-to-base
7213     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7214     // the wrong end of the derived->base arc, so stagger the path by one class.
7215     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7216     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7217          PathI != PathE; ++PathI) {
7218       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7219       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7220       if (!Result.castToDerived(Derived))
7221         return Error(E);
7222     }
7223     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7224     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7225       return Error(E);
7226     return true;
7227   }
7228 
7229   case CK_DerivedToBaseMemberPointer:
7230     if (!Visit(E->getSubExpr()))
7231       return false;
7232     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7233          PathE = E->path_end(); PathI != PathE; ++PathI) {
7234       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7235       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7236       if (!Result.castToBase(Base))
7237         return Error(E);
7238     }
7239     return true;
7240   }
7241 }
7242 
7243 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7244   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7245   // member can be formed.
7246   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7247 }
7248 
7249 //===----------------------------------------------------------------------===//
7250 // Record Evaluation
7251 //===----------------------------------------------------------------------===//
7252 
7253 namespace {
7254   class RecordExprEvaluator
7255   : public ExprEvaluatorBase<RecordExprEvaluator> {
7256     const LValue &This;
7257     APValue &Result;
7258   public:
7259 
7260     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7261       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7262 
7263     bool Success(const APValue &V, const Expr *E) {
7264       Result = V;
7265       return true;
7266     }
7267     bool ZeroInitialization(const Expr *E) {
7268       return ZeroInitialization(E, E->getType());
7269     }
7270     bool ZeroInitialization(const Expr *E, QualType T);
7271 
7272     bool VisitCallExpr(const CallExpr *E) {
7273       return handleCallExpr(E, Result, &This);
7274     }
7275     bool VisitCastExpr(const CastExpr *E);
7276     bool VisitInitListExpr(const InitListExpr *E);
7277     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7278       return VisitCXXConstructExpr(E, E->getType());
7279     }
7280     bool VisitLambdaExpr(const LambdaExpr *E);
7281     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7282     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7283     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7284 
7285     bool VisitBinCmp(const BinaryOperator *E);
7286   };
7287 }
7288 
7289 /// Perform zero-initialization on an object of non-union class type.
7290 /// C++11 [dcl.init]p5:
7291 ///  To zero-initialize an object or reference of type T means:
7292 ///    [...]
7293 ///    -- if T is a (possibly cv-qualified) non-union class type,
7294 ///       each non-static data member and each base-class subobject is
7295 ///       zero-initialized
7296 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7297                                           const RecordDecl *RD,
7298                                           const LValue &This, APValue &Result) {
7299   assert(!RD->isUnion() && "Expected non-union class type");
7300   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7301   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7302                    std::distance(RD->field_begin(), RD->field_end()));
7303 
7304   if (RD->isInvalidDecl()) return false;
7305   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7306 
7307   if (CD) {
7308     unsigned Index = 0;
7309     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7310            End = CD->bases_end(); I != End; ++I, ++Index) {
7311       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7312       LValue Subobject = This;
7313       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7314         return false;
7315       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7316                                          Result.getStructBase(Index)))
7317         return false;
7318     }
7319   }
7320 
7321   for (const auto *I : RD->fields()) {
7322     // -- if T is a reference type, no initialization is performed.
7323     if (I->getType()->isReferenceType())
7324       continue;
7325 
7326     LValue Subobject = This;
7327     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7328       return false;
7329 
7330     ImplicitValueInitExpr VIE(I->getType());
7331     if (!EvaluateInPlace(
7332           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7333       return false;
7334   }
7335 
7336   return true;
7337 }
7338 
7339 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7340   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7341   if (RD->isInvalidDecl()) return false;
7342   if (RD->isUnion()) {
7343     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7344     // object's first non-static named data member is zero-initialized
7345     RecordDecl::field_iterator I = RD->field_begin();
7346     if (I == RD->field_end()) {
7347       Result = APValue((const FieldDecl*)nullptr);
7348       return true;
7349     }
7350 
7351     LValue Subobject = This;
7352     if (!HandleLValueMember(Info, E, Subobject, *I))
7353       return false;
7354     Result = APValue(*I);
7355     ImplicitValueInitExpr VIE(I->getType());
7356     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7357   }
7358 
7359   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7360     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7361     return false;
7362   }
7363 
7364   return HandleClassZeroInitialization(Info, E, RD, This, Result);
7365 }
7366 
7367 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7368   switch (E->getCastKind()) {
7369   default:
7370     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7371 
7372   case CK_ConstructorConversion:
7373     return Visit(E->getSubExpr());
7374 
7375   case CK_DerivedToBase:
7376   case CK_UncheckedDerivedToBase: {
7377     APValue DerivedObject;
7378     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7379       return false;
7380     if (!DerivedObject.isStruct())
7381       return Error(E->getSubExpr());
7382 
7383     // Derived-to-base rvalue conversion: just slice off the derived part.
7384     APValue *Value = &DerivedObject;
7385     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7386     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7387          PathE = E->path_end(); PathI != PathE; ++PathI) {
7388       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7389       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7390       Value = &Value->getStructBase(getBaseIndex(RD, Base));
7391       RD = Base;
7392     }
7393     Result = *Value;
7394     return true;
7395   }
7396   }
7397 }
7398 
7399 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7400   if (E->isTransparent())
7401     return Visit(E->getInit(0));
7402 
7403   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7404   if (RD->isInvalidDecl()) return false;
7405   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7406   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7407 
7408   EvalInfo::EvaluatingConstructorRAII EvalObj(
7409       Info,
7410       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7411       CXXRD && CXXRD->getNumBases());
7412 
7413   if (RD->isUnion()) {
7414     const FieldDecl *Field = E->getInitializedFieldInUnion();
7415     Result = APValue(Field);
7416     if (!Field)
7417       return true;
7418 
7419     // If the initializer list for a union does not contain any elements, the
7420     // first element of the union is value-initialized.
7421     // FIXME: The element should be initialized from an initializer list.
7422     //        Is this difference ever observable for initializer lists which
7423     //        we don't build?
7424     ImplicitValueInitExpr VIE(Field->getType());
7425     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7426 
7427     LValue Subobject = This;
7428     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7429       return false;
7430 
7431     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7432     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7433                                   isa<CXXDefaultInitExpr>(InitExpr));
7434 
7435     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7436   }
7437 
7438   if (!Result.hasValue())
7439     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7440                      std::distance(RD->field_begin(), RD->field_end()));
7441   unsigned ElementNo = 0;
7442   bool Success = true;
7443 
7444   // Initialize base classes.
7445   if (CXXRD && CXXRD->getNumBases()) {
7446     for (const auto &Base : CXXRD->bases()) {
7447       assert(ElementNo < E->getNumInits() && "missing init for base class");
7448       const Expr *Init = E->getInit(ElementNo);
7449 
7450       LValue Subobject = This;
7451       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7452         return false;
7453 
7454       APValue &FieldVal = Result.getStructBase(ElementNo);
7455       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7456         if (!Info.noteFailure())
7457           return false;
7458         Success = false;
7459       }
7460       ++ElementNo;
7461     }
7462 
7463     EvalObj.finishedConstructingBases();
7464   }
7465 
7466   // Initialize members.
7467   for (const auto *Field : RD->fields()) {
7468     // Anonymous bit-fields are not considered members of the class for
7469     // purposes of aggregate initialization.
7470     if (Field->isUnnamedBitfield())
7471       continue;
7472 
7473     LValue Subobject = This;
7474 
7475     bool HaveInit = ElementNo < E->getNumInits();
7476 
7477     // FIXME: Diagnostics here should point to the end of the initializer
7478     // list, not the start.
7479     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7480                             Subobject, Field, &Layout))
7481       return false;
7482 
7483     // Perform an implicit value-initialization for members beyond the end of
7484     // the initializer list.
7485     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7486     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7487 
7488     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7489     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7490                                   isa<CXXDefaultInitExpr>(Init));
7491 
7492     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7493     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7494         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7495                                                        FieldVal, Field))) {
7496       if (!Info.noteFailure())
7497         return false;
7498       Success = false;
7499     }
7500   }
7501 
7502   return Success;
7503 }
7504 
7505 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7506                                                 QualType T) {
7507   // Note that E's type is not necessarily the type of our class here; we might
7508   // be initializing an array element instead.
7509   const CXXConstructorDecl *FD = E->getConstructor();
7510   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7511 
7512   bool ZeroInit = E->requiresZeroInitialization();
7513   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7514     // If we've already performed zero-initialization, we're already done.
7515     if (Result.hasValue())
7516       return true;
7517 
7518     // We can get here in two different ways:
7519     //  1) We're performing value-initialization, and should zero-initialize
7520     //     the object, or
7521     //  2) We're performing default-initialization of an object with a trivial
7522     //     constexpr default constructor, in which case we should start the
7523     //     lifetimes of all the base subobjects (there can be no data member
7524     //     subobjects in this case) per [basic.life]p1.
7525     // Either way, ZeroInitialization is appropriate.
7526     return ZeroInitialization(E, T);
7527   }
7528 
7529   const FunctionDecl *Definition = nullptr;
7530   auto Body = FD->getBody(Definition);
7531 
7532   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7533     return false;
7534 
7535   // Avoid materializing a temporary for an elidable copy/move constructor.
7536   if (E->isElidable() && !ZeroInit)
7537     if (const MaterializeTemporaryExpr *ME
7538           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7539       return Visit(ME->GetTemporaryExpr());
7540 
7541   if (ZeroInit && !ZeroInitialization(E, T))
7542     return false;
7543 
7544   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7545   return HandleConstructorCall(E, This, Args,
7546                                cast<CXXConstructorDecl>(Definition), Info,
7547                                Result);
7548 }
7549 
7550 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7551     const CXXInheritedCtorInitExpr *E) {
7552   if (!Info.CurrentCall) {
7553     assert(Info.checkingPotentialConstantExpression());
7554     return false;
7555   }
7556 
7557   const CXXConstructorDecl *FD = E->getConstructor();
7558   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7559     return false;
7560 
7561   const FunctionDecl *Definition = nullptr;
7562   auto Body = FD->getBody(Definition);
7563 
7564   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7565     return false;
7566 
7567   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
7568                                cast<CXXConstructorDecl>(Definition), Info,
7569                                Result);
7570 }
7571 
7572 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7573     const CXXStdInitializerListExpr *E) {
7574   const ConstantArrayType *ArrayType =
7575       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7576 
7577   LValue Array;
7578   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7579     return false;
7580 
7581   // Get a pointer to the first element of the array.
7582   Array.addArray(Info, E, ArrayType);
7583 
7584   // FIXME: Perform the checks on the field types in SemaInit.
7585   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7586   RecordDecl::field_iterator Field = Record->field_begin();
7587   if (Field == Record->field_end())
7588     return Error(E);
7589 
7590   // Start pointer.
7591   if (!Field->getType()->isPointerType() ||
7592       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7593                             ArrayType->getElementType()))
7594     return Error(E);
7595 
7596   // FIXME: What if the initializer_list type has base classes, etc?
7597   Result = APValue(APValue::UninitStruct(), 0, 2);
7598   Array.moveInto(Result.getStructField(0));
7599 
7600   if (++Field == Record->field_end())
7601     return Error(E);
7602 
7603   if (Field->getType()->isPointerType() &&
7604       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7605                            ArrayType->getElementType())) {
7606     // End pointer.
7607     if (!HandleLValueArrayAdjustment(Info, E, Array,
7608                                      ArrayType->getElementType(),
7609                                      ArrayType->getSize().getZExtValue()))
7610       return false;
7611     Array.moveInto(Result.getStructField(1));
7612   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7613     // Length.
7614     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7615   else
7616     return Error(E);
7617 
7618   if (++Field != Record->field_end())
7619     return Error(E);
7620 
7621   return true;
7622 }
7623 
7624 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7625   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7626   if (ClosureClass->isInvalidDecl()) return false;
7627 
7628   if (Info.checkingPotentialConstantExpression()) return true;
7629 
7630   const size_t NumFields =
7631       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
7632 
7633   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7634                                             E->capture_init_end()) &&
7635          "The number of lambda capture initializers should equal the number of "
7636          "fields within the closure type");
7637 
7638   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7639   // Iterate through all the lambda's closure object's fields and initialize
7640   // them.
7641   auto *CaptureInitIt = E->capture_init_begin();
7642   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7643   bool Success = true;
7644   for (const auto *Field : ClosureClass->fields()) {
7645     assert(CaptureInitIt != E->capture_init_end());
7646     // Get the initializer for this field
7647     Expr *const CurFieldInit = *CaptureInitIt++;
7648 
7649     // If there is no initializer, either this is a VLA or an error has
7650     // occurred.
7651     if (!CurFieldInit)
7652       return Error(E);
7653 
7654     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7655     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7656       if (!Info.keepEvaluatingAfterFailure())
7657         return false;
7658       Success = false;
7659     }
7660     ++CaptureIt;
7661   }
7662   return Success;
7663 }
7664 
7665 static bool EvaluateRecord(const Expr *E, const LValue &This,
7666                            APValue &Result, EvalInfo &Info) {
7667   assert(E->isRValue() && E->getType()->isRecordType() &&
7668          "can't evaluate expression as a record rvalue");
7669   return RecordExprEvaluator(Info, This, Result).Visit(E);
7670 }
7671 
7672 //===----------------------------------------------------------------------===//
7673 // Temporary Evaluation
7674 //
7675 // Temporaries are represented in the AST as rvalues, but generally behave like
7676 // lvalues. The full-object of which the temporary is a subobject is implicitly
7677 // materialized so that a reference can bind to it.
7678 //===----------------------------------------------------------------------===//
7679 namespace {
7680 class TemporaryExprEvaluator
7681   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7682 public:
7683   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
7684     LValueExprEvaluatorBaseTy(Info, Result, false) {}
7685 
7686   /// Visit an expression which constructs the value of this temporary.
7687   bool VisitConstructExpr(const Expr *E) {
7688     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7689     return EvaluateInPlace(Value, Info, Result, E);
7690   }
7691 
7692   bool VisitCastExpr(const CastExpr *E) {
7693     switch (E->getCastKind()) {
7694     default:
7695       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7696 
7697     case CK_ConstructorConversion:
7698       return VisitConstructExpr(E->getSubExpr());
7699     }
7700   }
7701   bool VisitInitListExpr(const InitListExpr *E) {
7702     return VisitConstructExpr(E);
7703   }
7704   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7705     return VisitConstructExpr(E);
7706   }
7707   bool VisitCallExpr(const CallExpr *E) {
7708     return VisitConstructExpr(E);
7709   }
7710   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7711     return VisitConstructExpr(E);
7712   }
7713   bool VisitLambdaExpr(const LambdaExpr *E) {
7714     return VisitConstructExpr(E);
7715   }
7716 };
7717 } // end anonymous namespace
7718 
7719 /// Evaluate an expression of record type as a temporary.
7720 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
7721   assert(E->isRValue() && E->getType()->isRecordType());
7722   return TemporaryExprEvaluator(Info, Result).Visit(E);
7723 }
7724 
7725 //===----------------------------------------------------------------------===//
7726 // Vector Evaluation
7727 //===----------------------------------------------------------------------===//
7728 
7729 namespace {
7730   class VectorExprEvaluator
7731   : public ExprEvaluatorBase<VectorExprEvaluator> {
7732     APValue &Result;
7733   public:
7734 
7735     VectorExprEvaluator(EvalInfo &info, APValue &Result)
7736       : ExprEvaluatorBaseTy(info), Result(Result) {}
7737 
7738     bool Success(ArrayRef<APValue> V, const Expr *E) {
7739       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7740       // FIXME: remove this APValue copy.
7741       Result = APValue(V.data(), V.size());
7742       return true;
7743     }
7744     bool Success(const APValue &V, const Expr *E) {
7745       assert(V.isVector());
7746       Result = V;
7747       return true;
7748     }
7749     bool ZeroInitialization(const Expr *E);
7750 
7751     bool VisitUnaryReal(const UnaryOperator *E)
7752       { return Visit(E->getSubExpr()); }
7753     bool VisitCastExpr(const CastExpr* E);
7754     bool VisitInitListExpr(const InitListExpr *E);
7755     bool VisitUnaryImag(const UnaryOperator *E);
7756     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
7757     //                 binary comparisons, binary and/or/xor,
7758     //                 shufflevector, ExtVectorElementExpr
7759   };
7760 } // end anonymous namespace
7761 
7762 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
7763   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
7764   return VectorExprEvaluator(Info, Result).Visit(E);
7765 }
7766 
7767 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
7768   const VectorType *VTy = E->getType()->castAs<VectorType>();
7769   unsigned NElts = VTy->getNumElements();
7770 
7771   const Expr *SE = E->getSubExpr();
7772   QualType SETy = SE->getType();
7773 
7774   switch (E->getCastKind()) {
7775   case CK_VectorSplat: {
7776     APValue Val = APValue();
7777     if (SETy->isIntegerType()) {
7778       APSInt IntResult;
7779       if (!EvaluateInteger(SE, IntResult, Info))
7780         return false;
7781       Val = APValue(std::move(IntResult));
7782     } else if (SETy->isRealFloatingType()) {
7783       APFloat FloatResult(0.0);
7784       if (!EvaluateFloat(SE, FloatResult, Info))
7785         return false;
7786       Val = APValue(std::move(FloatResult));
7787     } else {
7788       return Error(E);
7789     }
7790 
7791     // Splat and create vector APValue.
7792     SmallVector<APValue, 4> Elts(NElts, Val);
7793     return Success(Elts, E);
7794   }
7795   case CK_BitCast: {
7796     // Evaluate the operand into an APInt we can extract from.
7797     llvm::APInt SValInt;
7798     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7799       return false;
7800     // Extract the elements
7801     QualType EltTy = VTy->getElementType();
7802     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7803     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7804     SmallVector<APValue, 4> Elts;
7805     if (EltTy->isRealFloatingType()) {
7806       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7807       unsigned FloatEltSize = EltSize;
7808       if (&Sem == &APFloat::x87DoubleExtended())
7809         FloatEltSize = 80;
7810       for (unsigned i = 0; i < NElts; i++) {
7811         llvm::APInt Elt;
7812         if (BigEndian)
7813           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7814         else
7815           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7816         Elts.push_back(APValue(APFloat(Sem, Elt)));
7817       }
7818     } else if (EltTy->isIntegerType()) {
7819       for (unsigned i = 0; i < NElts; i++) {
7820         llvm::APInt Elt;
7821         if (BigEndian)
7822           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7823         else
7824           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7825         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7826       }
7827     } else {
7828       return Error(E);
7829     }
7830     return Success(Elts, E);
7831   }
7832   default:
7833     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7834   }
7835 }
7836 
7837 bool
7838 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7839   const VectorType *VT = E->getType()->castAs<VectorType>();
7840   unsigned NumInits = E->getNumInits();
7841   unsigned NumElements = VT->getNumElements();
7842 
7843   QualType EltTy = VT->getElementType();
7844   SmallVector<APValue, 4> Elements;
7845 
7846   // The number of initializers can be less than the number of
7847   // vector elements. For OpenCL, this can be due to nested vector
7848   // initialization. For GCC compatibility, missing trailing elements
7849   // should be initialized with zeroes.
7850   unsigned CountInits = 0, CountElts = 0;
7851   while (CountElts < NumElements) {
7852     // Handle nested vector initialization.
7853     if (CountInits < NumInits
7854         && E->getInit(CountInits)->getType()->isVectorType()) {
7855       APValue v;
7856       if (!EvaluateVector(E->getInit(CountInits), v, Info))
7857         return Error(E);
7858       unsigned vlen = v.getVectorLength();
7859       for (unsigned j = 0; j < vlen; j++)
7860         Elements.push_back(v.getVectorElt(j));
7861       CountElts += vlen;
7862     } else if (EltTy->isIntegerType()) {
7863       llvm::APSInt sInt(32);
7864       if (CountInits < NumInits) {
7865         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7866           return false;
7867       } else // trailing integer zero.
7868         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7869       Elements.push_back(APValue(sInt));
7870       CountElts++;
7871     } else {
7872       llvm::APFloat f(0.0);
7873       if (CountInits < NumInits) {
7874         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7875           return false;
7876       } else // trailing float zero.
7877         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7878       Elements.push_back(APValue(f));
7879       CountElts++;
7880     }
7881     CountInits++;
7882   }
7883   return Success(Elements, E);
7884 }
7885 
7886 bool
7887 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7888   const VectorType *VT = E->getType()->getAs<VectorType>();
7889   QualType EltTy = VT->getElementType();
7890   APValue ZeroElement;
7891   if (EltTy->isIntegerType())
7892     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7893   else
7894     ZeroElement =
7895         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7896 
7897   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7898   return Success(Elements, E);
7899 }
7900 
7901 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7902   VisitIgnoredValue(E->getSubExpr());
7903   return ZeroInitialization(E);
7904 }
7905 
7906 //===----------------------------------------------------------------------===//
7907 // Array Evaluation
7908 //===----------------------------------------------------------------------===//
7909 
7910 namespace {
7911   class ArrayExprEvaluator
7912   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7913     const LValue &This;
7914     APValue &Result;
7915   public:
7916 
7917     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7918       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7919 
7920     bool Success(const APValue &V, const Expr *E) {
7921       assert(V.isArray() && "expected array");
7922       Result = V;
7923       return true;
7924     }
7925 
7926     bool ZeroInitialization(const Expr *E) {
7927       const ConstantArrayType *CAT =
7928           Info.Ctx.getAsConstantArrayType(E->getType());
7929       if (!CAT)
7930         return Error(E);
7931 
7932       Result = APValue(APValue::UninitArray(), 0,
7933                        CAT->getSize().getZExtValue());
7934       if (!Result.hasArrayFiller()) return true;
7935 
7936       // Zero-initialize all elements.
7937       LValue Subobject = This;
7938       Subobject.addArray(Info, E, CAT);
7939       ImplicitValueInitExpr VIE(CAT->getElementType());
7940       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7941     }
7942 
7943     bool VisitCallExpr(const CallExpr *E) {
7944       return handleCallExpr(E, Result, &This);
7945     }
7946     bool VisitInitListExpr(const InitListExpr *E);
7947     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7948     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7949     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7950                                const LValue &Subobject,
7951                                APValue *Value, QualType Type);
7952     bool VisitStringLiteral(const StringLiteral *E) {
7953       expandStringLiteral(Info, E, Result);
7954       return true;
7955     }
7956   };
7957 } // end anonymous namespace
7958 
7959 static bool EvaluateArray(const Expr *E, const LValue &This,
7960                           APValue &Result, EvalInfo &Info) {
7961   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7962   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7963 }
7964 
7965 // Return true iff the given array filler may depend on the element index.
7966 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7967   // For now, just whitelist non-class value-initialization and initialization
7968   // lists comprised of them.
7969   if (isa<ImplicitValueInitExpr>(FillerExpr))
7970     return false;
7971   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7972     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7973       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7974         return true;
7975     }
7976     return false;
7977   }
7978   return true;
7979 }
7980 
7981 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7982   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7983   if (!CAT)
7984     return Error(E);
7985 
7986   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7987   // an appropriately-typed string literal enclosed in braces.
7988   if (E->isStringLiteralInit())
7989     return Visit(E->getInit(0));
7990 
7991   bool Success = true;
7992 
7993   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7994          "zero-initialized array shouldn't have any initialized elts");
7995   APValue Filler;
7996   if (Result.isArray() && Result.hasArrayFiller())
7997     Filler = Result.getArrayFiller();
7998 
7999   unsigned NumEltsToInit = E->getNumInits();
8000   unsigned NumElts = CAT->getSize().getZExtValue();
8001   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8002 
8003   // If the initializer might depend on the array index, run it for each
8004   // array element.
8005   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8006     NumEltsToInit = NumElts;
8007 
8008   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8009                           << NumEltsToInit << ".\n");
8010 
8011   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8012 
8013   // If the array was previously zero-initialized, preserve the
8014   // zero-initialized values.
8015   if (Filler.hasValue()) {
8016     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8017       Result.getArrayInitializedElt(I) = Filler;
8018     if (Result.hasArrayFiller())
8019       Result.getArrayFiller() = Filler;
8020   }
8021 
8022   LValue Subobject = This;
8023   Subobject.addArray(Info, E, CAT);
8024   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8025     const Expr *Init =
8026         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8027     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8028                          Info, Subobject, Init) ||
8029         !HandleLValueArrayAdjustment(Info, Init, Subobject,
8030                                      CAT->getElementType(), 1)) {
8031       if (!Info.noteFailure())
8032         return false;
8033       Success = false;
8034     }
8035   }
8036 
8037   if (!Result.hasArrayFiller())
8038     return Success;
8039 
8040   // If we get here, we have a trivial filler, which we can just evaluate
8041   // once and splat over the rest of the array elements.
8042   assert(FillerExpr && "no array filler for incomplete init list");
8043   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8044                          FillerExpr) && Success;
8045 }
8046 
8047 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8048   if (E->getCommonExpr() &&
8049       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8050                 Info, E->getCommonExpr()->getSourceExpr()))
8051     return false;
8052 
8053   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8054 
8055   uint64_t Elements = CAT->getSize().getZExtValue();
8056   Result = APValue(APValue::UninitArray(), Elements, Elements);
8057 
8058   LValue Subobject = This;
8059   Subobject.addArray(Info, E, CAT);
8060 
8061   bool Success = true;
8062   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8063     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8064                          Info, Subobject, E->getSubExpr()) ||
8065         !HandleLValueArrayAdjustment(Info, E, Subobject,
8066                                      CAT->getElementType(), 1)) {
8067       if (!Info.noteFailure())
8068         return false;
8069       Success = false;
8070     }
8071   }
8072 
8073   return Success;
8074 }
8075 
8076 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8077   return VisitCXXConstructExpr(E, This, &Result, E->getType());
8078 }
8079 
8080 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8081                                                const LValue &Subobject,
8082                                                APValue *Value,
8083                                                QualType Type) {
8084   bool HadZeroInit = Value->hasValue();
8085 
8086   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8087     unsigned N = CAT->getSize().getZExtValue();
8088 
8089     // Preserve the array filler if we had prior zero-initialization.
8090     APValue Filler =
8091       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8092                                              : APValue();
8093 
8094     *Value = APValue(APValue::UninitArray(), N, N);
8095 
8096     if (HadZeroInit)
8097       for (unsigned I = 0; I != N; ++I)
8098         Value->getArrayInitializedElt(I) = Filler;
8099 
8100     // Initialize the elements.
8101     LValue ArrayElt = Subobject;
8102     ArrayElt.addArray(Info, E, CAT);
8103     for (unsigned I = 0; I != N; ++I)
8104       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8105                                  CAT->getElementType()) ||
8106           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8107                                        CAT->getElementType(), 1))
8108         return false;
8109 
8110     return true;
8111   }
8112 
8113   if (!Type->isRecordType())
8114     return Error(E);
8115 
8116   return RecordExprEvaluator(Info, Subobject, *Value)
8117              .VisitCXXConstructExpr(E, Type);
8118 }
8119 
8120 //===----------------------------------------------------------------------===//
8121 // Integer Evaluation
8122 //
8123 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8124 // types and back in constant folding. Integer values are thus represented
8125 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8126 //===----------------------------------------------------------------------===//
8127 
8128 namespace {
8129 class IntExprEvaluator
8130         : public ExprEvaluatorBase<IntExprEvaluator> {
8131   APValue &Result;
8132 public:
8133   IntExprEvaluator(EvalInfo &info, APValue &result)
8134       : ExprEvaluatorBaseTy(info), Result(result) {}
8135 
8136   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8137     assert(E->getType()->isIntegralOrEnumerationType() &&
8138            "Invalid evaluation result.");
8139     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8140            "Invalid evaluation result.");
8141     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8142            "Invalid evaluation result.");
8143     Result = APValue(SI);
8144     return true;
8145   }
8146   bool Success(const llvm::APSInt &SI, const Expr *E) {
8147     return Success(SI, E, Result);
8148   }
8149 
8150   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8151     assert(E->getType()->isIntegralOrEnumerationType() &&
8152            "Invalid evaluation result.");
8153     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8154            "Invalid evaluation result.");
8155     Result = APValue(APSInt(I));
8156     Result.getInt().setIsUnsigned(
8157                             E->getType()->isUnsignedIntegerOrEnumerationType());
8158     return true;
8159   }
8160   bool Success(const llvm::APInt &I, const Expr *E) {
8161     return Success(I, E, Result);
8162   }
8163 
8164   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8165     assert(E->getType()->isIntegralOrEnumerationType() &&
8166            "Invalid evaluation result.");
8167     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8168     return true;
8169   }
8170   bool Success(uint64_t Value, const Expr *E) {
8171     return Success(Value, E, Result);
8172   }
8173 
8174   bool Success(CharUnits Size, const Expr *E) {
8175     return Success(Size.getQuantity(), E);
8176   }
8177 
8178   bool Success(const APValue &V, const Expr *E) {
8179     if (V.isLValue() || V.isAddrLabelDiff()) {
8180       Result = V;
8181       return true;
8182     }
8183     return Success(V.getInt(), E);
8184   }
8185 
8186   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8187 
8188   //===--------------------------------------------------------------------===//
8189   //                            Visitor Methods
8190   //===--------------------------------------------------------------------===//
8191 
8192   bool VisitConstantExpr(const ConstantExpr *E);
8193 
8194   bool VisitIntegerLiteral(const IntegerLiteral *E) {
8195     return Success(E->getValue(), E);
8196   }
8197   bool VisitCharacterLiteral(const CharacterLiteral *E) {
8198     return Success(E->getValue(), E);
8199   }
8200 
8201   bool CheckReferencedDecl(const Expr *E, const Decl *D);
8202   bool VisitDeclRefExpr(const DeclRefExpr *E) {
8203     if (CheckReferencedDecl(E, E->getDecl()))
8204       return true;
8205 
8206     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8207   }
8208   bool VisitMemberExpr(const MemberExpr *E) {
8209     if (CheckReferencedDecl(E, E->getMemberDecl())) {
8210       VisitIgnoredBaseExpression(E->getBase());
8211       return true;
8212     }
8213 
8214     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8215   }
8216 
8217   bool VisitCallExpr(const CallExpr *E);
8218   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8219   bool VisitBinaryOperator(const BinaryOperator *E);
8220   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8221   bool VisitUnaryOperator(const UnaryOperator *E);
8222 
8223   bool VisitCastExpr(const CastExpr* E);
8224   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8225 
8226   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8227     return Success(E->getValue(), E);
8228   }
8229 
8230   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8231     return Success(E->getValue(), E);
8232   }
8233 
8234   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8235     if (Info.ArrayInitIndex == uint64_t(-1)) {
8236       // We were asked to evaluate this subexpression independent of the
8237       // enclosing ArrayInitLoopExpr. We can't do that.
8238       Info.FFDiag(E);
8239       return false;
8240     }
8241     return Success(Info.ArrayInitIndex, E);
8242   }
8243 
8244   // Note, GNU defines __null as an integer, not a pointer.
8245   bool VisitGNUNullExpr(const GNUNullExpr *E) {
8246     return ZeroInitialization(E);
8247   }
8248 
8249   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8250     return Success(E->getValue(), E);
8251   }
8252 
8253   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8254     return Success(E->getValue(), E);
8255   }
8256 
8257   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8258     return Success(E->getValue(), E);
8259   }
8260 
8261   bool VisitUnaryReal(const UnaryOperator *E);
8262   bool VisitUnaryImag(const UnaryOperator *E);
8263 
8264   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8265   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8266   bool VisitSourceLocExpr(const SourceLocExpr *E);
8267   // FIXME: Missing: array subscript of vector, member of vector
8268 };
8269 
8270 class FixedPointExprEvaluator
8271     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8272   APValue &Result;
8273 
8274  public:
8275   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8276       : ExprEvaluatorBaseTy(info), Result(result) {}
8277 
8278   bool Success(const llvm::APInt &I, const Expr *E) {
8279     return Success(
8280         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8281   }
8282 
8283   bool Success(uint64_t Value, const Expr *E) {
8284     return Success(
8285         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8286   }
8287 
8288   bool Success(const APValue &V, const Expr *E) {
8289     return Success(V.getFixedPoint(), E);
8290   }
8291 
8292   bool Success(const APFixedPoint &V, const Expr *E) {
8293     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8294     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8295            "Invalid evaluation result.");
8296     Result = APValue(V);
8297     return true;
8298   }
8299 
8300   //===--------------------------------------------------------------------===//
8301   //                            Visitor Methods
8302   //===--------------------------------------------------------------------===//
8303 
8304   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8305     return Success(E->getValue(), E);
8306   }
8307 
8308   bool VisitCastExpr(const CastExpr *E);
8309   bool VisitUnaryOperator(const UnaryOperator *E);
8310   bool VisitBinaryOperator(const BinaryOperator *E);
8311 };
8312 } // end anonymous namespace
8313 
8314 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8315 /// produce either the integer value or a pointer.
8316 ///
8317 /// GCC has a heinous extension which folds casts between pointer types and
8318 /// pointer-sized integral types. We support this by allowing the evaluation of
8319 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8320 /// Some simple arithmetic on such values is supported (they are treated much
8321 /// like char*).
8322 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8323                                     EvalInfo &Info) {
8324   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8325   return IntExprEvaluator(Info, Result).Visit(E);
8326 }
8327 
8328 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8329   APValue Val;
8330   if (!EvaluateIntegerOrLValue(E, Val, Info))
8331     return false;
8332   if (!Val.isInt()) {
8333     // FIXME: It would be better to produce the diagnostic for casting
8334     //        a pointer to an integer.
8335     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8336     return false;
8337   }
8338   Result = Val.getInt();
8339   return true;
8340 }
8341 
8342 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8343   APValue Evaluated = E->EvaluateInContext(
8344       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8345   return Success(Evaluated, E);
8346 }
8347 
8348 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8349                                EvalInfo &Info) {
8350   if (E->getType()->isFixedPointType()) {
8351     APValue Val;
8352     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8353       return false;
8354     if (!Val.isFixedPoint())
8355       return false;
8356 
8357     Result = Val.getFixedPoint();
8358     return true;
8359   }
8360   return false;
8361 }
8362 
8363 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8364                                         EvalInfo &Info) {
8365   if (E->getType()->isIntegerType()) {
8366     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8367     APSInt Val;
8368     if (!EvaluateInteger(E, Val, Info))
8369       return false;
8370     Result = APFixedPoint(Val, FXSema);
8371     return true;
8372   } else if (E->getType()->isFixedPointType()) {
8373     return EvaluateFixedPoint(E, Result, Info);
8374   }
8375   return false;
8376 }
8377 
8378 /// Check whether the given declaration can be directly converted to an integral
8379 /// rvalue. If not, no diagnostic is produced; there are other things we can
8380 /// try.
8381 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8382   // Enums are integer constant exprs.
8383   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8384     // Check for signedness/width mismatches between E type and ECD value.
8385     bool SameSign = (ECD->getInitVal().isSigned()
8386                      == E->getType()->isSignedIntegerOrEnumerationType());
8387     bool SameWidth = (ECD->getInitVal().getBitWidth()
8388                       == Info.Ctx.getIntWidth(E->getType()));
8389     if (SameSign && SameWidth)
8390       return Success(ECD->getInitVal(), E);
8391     else {
8392       // Get rid of mismatch (otherwise Success assertions will fail)
8393       // by computing a new value matching the type of E.
8394       llvm::APSInt Val = ECD->getInitVal();
8395       if (!SameSign)
8396         Val.setIsSigned(!ECD->getInitVal().isSigned());
8397       if (!SameWidth)
8398         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8399       return Success(Val, E);
8400     }
8401   }
8402   return false;
8403 }
8404 
8405 /// Values returned by __builtin_classify_type, chosen to match the values
8406 /// produced by GCC's builtin.
8407 enum class GCCTypeClass {
8408   None = -1,
8409   Void = 0,
8410   Integer = 1,
8411   // GCC reserves 2 for character types, but instead classifies them as
8412   // integers.
8413   Enum = 3,
8414   Bool = 4,
8415   Pointer = 5,
8416   // GCC reserves 6 for references, but appears to never use it (because
8417   // expressions never have reference type, presumably).
8418   PointerToDataMember = 7,
8419   RealFloat = 8,
8420   Complex = 9,
8421   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8422   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8423   // GCC claims to reserve 11 for pointers to member functions, but *actually*
8424   // uses 12 for that purpose, same as for a class or struct. Maybe it
8425   // internally implements a pointer to member as a struct?  Who knows.
8426   PointerToMemberFunction = 12, // Not a bug, see above.
8427   ClassOrStruct = 12,
8428   Union = 13,
8429   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8430   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8431   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8432   // literals.
8433 };
8434 
8435 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8436 /// as GCC.
8437 static GCCTypeClass
8438 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8439   assert(!T->isDependentType() && "unexpected dependent type");
8440 
8441   QualType CanTy = T.getCanonicalType();
8442   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8443 
8444   switch (CanTy->getTypeClass()) {
8445 #define TYPE(ID, BASE)
8446 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8447 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8448 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8449 #include "clang/AST/TypeNodes.def"
8450   case Type::Auto:
8451   case Type::DeducedTemplateSpecialization:
8452       llvm_unreachable("unexpected non-canonical or dependent type");
8453 
8454   case Type::Builtin:
8455     switch (BT->getKind()) {
8456 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8457 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8458     case BuiltinType::ID: return GCCTypeClass::Integer;
8459 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8460     case BuiltinType::ID: return GCCTypeClass::RealFloat;
8461 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8462     case BuiltinType::ID: break;
8463 #include "clang/AST/BuiltinTypes.def"
8464     case BuiltinType::Void:
8465       return GCCTypeClass::Void;
8466 
8467     case BuiltinType::Bool:
8468       return GCCTypeClass::Bool;
8469 
8470     case BuiltinType::Char_U:
8471     case BuiltinType::UChar:
8472     case BuiltinType::WChar_U:
8473     case BuiltinType::Char8:
8474     case BuiltinType::Char16:
8475     case BuiltinType::Char32:
8476     case BuiltinType::UShort:
8477     case BuiltinType::UInt:
8478     case BuiltinType::ULong:
8479     case BuiltinType::ULongLong:
8480     case BuiltinType::UInt128:
8481       return GCCTypeClass::Integer;
8482 
8483     case BuiltinType::UShortAccum:
8484     case BuiltinType::UAccum:
8485     case BuiltinType::ULongAccum:
8486     case BuiltinType::UShortFract:
8487     case BuiltinType::UFract:
8488     case BuiltinType::ULongFract:
8489     case BuiltinType::SatUShortAccum:
8490     case BuiltinType::SatUAccum:
8491     case BuiltinType::SatULongAccum:
8492     case BuiltinType::SatUShortFract:
8493     case BuiltinType::SatUFract:
8494     case BuiltinType::SatULongFract:
8495       return GCCTypeClass::None;
8496 
8497     case BuiltinType::NullPtr:
8498 
8499     case BuiltinType::ObjCId:
8500     case BuiltinType::ObjCClass:
8501     case BuiltinType::ObjCSel:
8502 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8503     case BuiltinType::Id:
8504 #include "clang/Basic/OpenCLImageTypes.def"
8505 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8506     case BuiltinType::Id:
8507 #include "clang/Basic/OpenCLExtensionTypes.def"
8508     case BuiltinType::OCLSampler:
8509     case BuiltinType::OCLEvent:
8510     case BuiltinType::OCLClkEvent:
8511     case BuiltinType::OCLQueue:
8512     case BuiltinType::OCLReserveID:
8513       return GCCTypeClass::None;
8514 
8515     case BuiltinType::Dependent:
8516       llvm_unreachable("unexpected dependent type");
8517     };
8518     llvm_unreachable("unexpected placeholder type");
8519 
8520   case Type::Enum:
8521     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
8522 
8523   case Type::Pointer:
8524   case Type::ConstantArray:
8525   case Type::VariableArray:
8526   case Type::IncompleteArray:
8527   case Type::FunctionNoProto:
8528   case Type::FunctionProto:
8529     return GCCTypeClass::Pointer;
8530 
8531   case Type::MemberPointer:
8532     return CanTy->isMemberDataPointerType()
8533                ? GCCTypeClass::PointerToDataMember
8534                : GCCTypeClass::PointerToMemberFunction;
8535 
8536   case Type::Complex:
8537     return GCCTypeClass::Complex;
8538 
8539   case Type::Record:
8540     return CanTy->isUnionType() ? GCCTypeClass::Union
8541                                 : GCCTypeClass::ClassOrStruct;
8542 
8543   case Type::Atomic:
8544     // GCC classifies _Atomic T the same as T.
8545     return EvaluateBuiltinClassifyType(
8546         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
8547 
8548   case Type::BlockPointer:
8549   case Type::Vector:
8550   case Type::ExtVector:
8551   case Type::ObjCObject:
8552   case Type::ObjCInterface:
8553   case Type::ObjCObjectPointer:
8554   case Type::Pipe:
8555     // GCC classifies vectors as None. We follow its lead and classify all
8556     // other types that don't fit into the regular classification the same way.
8557     return GCCTypeClass::None;
8558 
8559   case Type::LValueReference:
8560   case Type::RValueReference:
8561     llvm_unreachable("invalid type for expression");
8562   }
8563 
8564   llvm_unreachable("unexpected type class");
8565 }
8566 
8567 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8568 /// as GCC.
8569 static GCCTypeClass
8570 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8571   // If no argument was supplied, default to None. This isn't
8572   // ideal, however it is what gcc does.
8573   if (E->getNumArgs() == 0)
8574     return GCCTypeClass::None;
8575 
8576   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8577   // being an ICE, but still folds it to a constant using the type of the first
8578   // argument.
8579   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
8580 }
8581 
8582 /// EvaluateBuiltinConstantPForLValue - Determine the result of
8583 /// __builtin_constant_p when applied to the given pointer.
8584 ///
8585 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
8586 /// or it points to the first character of a string literal.
8587 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8588   APValue::LValueBase Base = LV.getLValueBase();
8589   if (Base.isNull()) {
8590     // A null base is acceptable.
8591     return true;
8592   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8593     if (!isa<StringLiteral>(E))
8594       return false;
8595     return LV.getLValueOffset().isZero();
8596   } else if (Base.is<TypeInfoLValue>()) {
8597     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8598     // evaluate to true.
8599     return true;
8600   } else {
8601     // Any other base is not constant enough for GCC.
8602     return false;
8603   }
8604 }
8605 
8606 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8607 /// GCC as we can manage.
8608 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
8609   // This evaluation is not permitted to have side-effects, so evaluate it in
8610   // a speculative evaluation context.
8611   SpeculativeEvaluationRAII SpeculativeEval(Info);
8612 
8613   // Constant-folding is always enabled for the operand of __builtin_constant_p
8614   // (even when the enclosing evaluation context otherwise requires a strict
8615   // language-specific constant expression).
8616   FoldConstant Fold(Info, true);
8617 
8618   QualType ArgType = Arg->getType();
8619 
8620   // __builtin_constant_p always has one operand. The rules which gcc follows
8621   // are not precisely documented, but are as follows:
8622   //
8623   //  - If the operand is of integral, floating, complex or enumeration type,
8624   //    and can be folded to a known value of that type, it returns 1.
8625   //  - If the operand can be folded to a pointer to the first character
8626   //    of a string literal (or such a pointer cast to an integral type)
8627   //    or to a null pointer or an integer cast to a pointer, it returns 1.
8628   //
8629   // Otherwise, it returns 0.
8630   //
8631   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
8632   // its support for this did not work prior to GCC 9 and is not yet well
8633   // understood.
8634   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8635       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8636       ArgType->isNullPtrType()) {
8637     APValue V;
8638     if (!::EvaluateAsRValue(Info, Arg, V)) {
8639       Fold.keepDiagnostics();
8640       return false;
8641     }
8642 
8643     // For a pointer (possibly cast to integer), there are special rules.
8644     if (V.getKind() == APValue::LValue)
8645       return EvaluateBuiltinConstantPForLValue(V);
8646 
8647     // Otherwise, any constant value is good enough.
8648     return V.hasValue();
8649   }
8650 
8651   // Anything else isn't considered to be sufficiently constant.
8652   return false;
8653 }
8654 
8655 /// Retrieves the "underlying object type" of the given expression,
8656 /// as used by __builtin_object_size.
8657 static QualType getObjectType(APValue::LValueBase B) {
8658   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8659     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8660       return VD->getType();
8661   } else if (const Expr *E = B.get<const Expr*>()) {
8662     if (isa<CompoundLiteralExpr>(E))
8663       return E->getType();
8664   } else if (B.is<TypeInfoLValue>()) {
8665     return B.getTypeInfoType();
8666   }
8667 
8668   return QualType();
8669 }
8670 
8671 /// A more selective version of E->IgnoreParenCasts for
8672 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
8673 /// to change the type of E.
8674 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8675 ///
8676 /// Always returns an RValue with a pointer representation.
8677 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8678   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8679 
8680   auto *NoParens = E->IgnoreParens();
8681   auto *Cast = dyn_cast<CastExpr>(NoParens);
8682   if (Cast == nullptr)
8683     return NoParens;
8684 
8685   // We only conservatively allow a few kinds of casts, because this code is
8686   // inherently a simple solution that seeks to support the common case.
8687   auto CastKind = Cast->getCastKind();
8688   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8689       CastKind != CK_AddressSpaceConversion)
8690     return NoParens;
8691 
8692   auto *SubExpr = Cast->getSubExpr();
8693   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8694     return NoParens;
8695   return ignorePointerCastsAndParens(SubExpr);
8696 }
8697 
8698 /// Checks to see if the given LValue's Designator is at the end of the LValue's
8699 /// record layout. e.g.
8700 ///   struct { struct { int a, b; } fst, snd; } obj;
8701 ///   obj.fst   // no
8702 ///   obj.snd   // yes
8703 ///   obj.fst.a // no
8704 ///   obj.fst.b // no
8705 ///   obj.snd.a // no
8706 ///   obj.snd.b // yes
8707 ///
8708 /// Please note: this function is specialized for how __builtin_object_size
8709 /// views "objects".
8710 ///
8711 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
8712 /// correct result, it will always return true.
8713 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8714   assert(!LVal.Designator.Invalid);
8715 
8716   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8717     const RecordDecl *Parent = FD->getParent();
8718     Invalid = Parent->isInvalidDecl();
8719     if (Invalid || Parent->isUnion())
8720       return true;
8721     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
8722     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8723   };
8724 
8725   auto &Base = LVal.getLValueBase();
8726   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8727     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
8728       bool Invalid;
8729       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8730         return Invalid;
8731     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
8732       for (auto *FD : IFD->chain()) {
8733         bool Invalid;
8734         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8735           return Invalid;
8736       }
8737     }
8738   }
8739 
8740   unsigned I = 0;
8741   QualType BaseType = getType(Base);
8742   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
8743     // If we don't know the array bound, conservatively assume we're looking at
8744     // the final array element.
8745     ++I;
8746     if (BaseType->isIncompleteArrayType())
8747       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8748     else
8749       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
8750   }
8751 
8752   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8753     const auto &Entry = LVal.Designator.Entries[I];
8754     if (BaseType->isArrayType()) {
8755       // Because __builtin_object_size treats arrays as objects, we can ignore
8756       // the index iff this is the last array in the Designator.
8757       if (I + 1 == E)
8758         return true;
8759       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
8760       uint64_t Index = Entry.getAsArrayIndex();
8761       if (Index + 1 != CAT->getSize())
8762         return false;
8763       BaseType = CAT->getElementType();
8764     } else if (BaseType->isAnyComplexType()) {
8765       const auto *CT = BaseType->castAs<ComplexType>();
8766       uint64_t Index = Entry.getAsArrayIndex();
8767       if (Index != 1)
8768         return false;
8769       BaseType = CT->getElementType();
8770     } else if (auto *FD = getAsField(Entry)) {
8771       bool Invalid;
8772       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8773         return Invalid;
8774       BaseType = FD->getType();
8775     } else {
8776       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
8777       return false;
8778     }
8779   }
8780   return true;
8781 }
8782 
8783 /// Tests to see if the LValue has a user-specified designator (that isn't
8784 /// necessarily valid). Note that this always returns 'true' if the LValue has
8785 /// an unsized array as its first designator entry, because there's currently no
8786 /// way to tell if the user typed *foo or foo[0].
8787 static bool refersToCompleteObject(const LValue &LVal) {
8788   if (LVal.Designator.Invalid)
8789     return false;
8790 
8791   if (!LVal.Designator.Entries.empty())
8792     return LVal.Designator.isMostDerivedAnUnsizedArray();
8793 
8794   if (!LVal.InvalidBase)
8795     return true;
8796 
8797   // If `E` is a MemberExpr, then the first part of the designator is hiding in
8798   // the LValueBase.
8799   const auto *E = LVal.Base.dyn_cast<const Expr *>();
8800   return !E || !isa<MemberExpr>(E);
8801 }
8802 
8803 /// Attempts to detect a user writing into a piece of memory that's impossible
8804 /// to figure out the size of by just using types.
8805 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8806   const SubobjectDesignator &Designator = LVal.Designator;
8807   // Notes:
8808   // - Users can only write off of the end when we have an invalid base. Invalid
8809   //   bases imply we don't know where the memory came from.
8810   // - We used to be a bit more aggressive here; we'd only be conservative if
8811   //   the array at the end was flexible, or if it had 0 or 1 elements. This
8812   //   broke some common standard library extensions (PR30346), but was
8813   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
8814   //   with some sort of whitelist. OTOH, it seems that GCC is always
8815   //   conservative with the last element in structs (if it's an array), so our
8816   //   current behavior is more compatible than a whitelisting approach would
8817   //   be.
8818   return LVal.InvalidBase &&
8819          Designator.Entries.size() == Designator.MostDerivedPathLength &&
8820          Designator.MostDerivedIsArrayElement &&
8821          isDesignatorAtObjectEnd(Ctx, LVal);
8822 }
8823 
8824 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8825 /// Fails if the conversion would cause loss of precision.
8826 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8827                                             CharUnits &Result) {
8828   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8829   if (Int.ugt(CharUnitsMax))
8830     return false;
8831   Result = CharUnits::fromQuantity(Int.getZExtValue());
8832   return true;
8833 }
8834 
8835 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8836 /// determine how many bytes exist from the beginning of the object to either
8837 /// the end of the current subobject, or the end of the object itself, depending
8838 /// on what the LValue looks like + the value of Type.
8839 ///
8840 /// If this returns false, the value of Result is undefined.
8841 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8842                                unsigned Type, const LValue &LVal,
8843                                CharUnits &EndOffset) {
8844   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8845 
8846   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8847     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8848       return false;
8849     return HandleSizeof(Info, ExprLoc, Ty, Result);
8850   };
8851 
8852   // We want to evaluate the size of the entire object. This is a valid fallback
8853   // for when Type=1 and the designator is invalid, because we're asked for an
8854   // upper-bound.
8855   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8856     // Type=3 wants a lower bound, so we can't fall back to this.
8857     if (Type == 3 && !DetermineForCompleteObject)
8858       return false;
8859 
8860     llvm::APInt APEndOffset;
8861     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8862         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8863       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8864 
8865     if (LVal.InvalidBase)
8866       return false;
8867 
8868     QualType BaseTy = getObjectType(LVal.getLValueBase());
8869     return CheckedHandleSizeof(BaseTy, EndOffset);
8870   }
8871 
8872   // We want to evaluate the size of a subobject.
8873   const SubobjectDesignator &Designator = LVal.Designator;
8874 
8875   // The following is a moderately common idiom in C:
8876   //
8877   // struct Foo { int a; char c[1]; };
8878   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8879   // strcpy(&F->c[0], Bar);
8880   //
8881   // In order to not break too much legacy code, we need to support it.
8882   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8883     // If we can resolve this to an alloc_size call, we can hand that back,
8884     // because we know for certain how many bytes there are to write to.
8885     llvm::APInt APEndOffset;
8886     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8887         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8888       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8889 
8890     // If we cannot determine the size of the initial allocation, then we can't
8891     // given an accurate upper-bound. However, we are still able to give
8892     // conservative lower-bounds for Type=3.
8893     if (Type == 1)
8894       return false;
8895   }
8896 
8897   CharUnits BytesPerElem;
8898   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8899     return false;
8900 
8901   // According to the GCC documentation, we want the size of the subobject
8902   // denoted by the pointer. But that's not quite right -- what we actually
8903   // want is the size of the immediately-enclosing array, if there is one.
8904   int64_t ElemsRemaining;
8905   if (Designator.MostDerivedIsArrayElement &&
8906       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8907     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8908     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
8909     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8910   } else {
8911     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8912   }
8913 
8914   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8915   return true;
8916 }
8917 
8918 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8919 /// returns true and stores the result in @p Size.
8920 ///
8921 /// If @p WasError is non-null, this will report whether the failure to evaluate
8922 /// is to be treated as an Error in IntExprEvaluator.
8923 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8924                                          EvalInfo &Info, uint64_t &Size) {
8925   // Determine the denoted object.
8926   LValue LVal;
8927   {
8928     // The operand of __builtin_object_size is never evaluated for side-effects.
8929     // If there are any, but we can determine the pointed-to object anyway, then
8930     // ignore the side-effects.
8931     SpeculativeEvaluationRAII SpeculativeEval(Info);
8932     IgnoreSideEffectsRAII Fold(Info);
8933 
8934     if (E->isGLValue()) {
8935       // It's possible for us to be given GLValues if we're called via
8936       // Expr::tryEvaluateObjectSize.
8937       APValue RVal;
8938       if (!EvaluateAsRValue(Info, E, RVal))
8939         return false;
8940       LVal.setFrom(Info.Ctx, RVal);
8941     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8942                                 /*InvalidBaseOK=*/true))
8943       return false;
8944   }
8945 
8946   // If we point to before the start of the object, there are no accessible
8947   // bytes.
8948   if (LVal.getLValueOffset().isNegative()) {
8949     Size = 0;
8950     return true;
8951   }
8952 
8953   CharUnits EndOffset;
8954   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8955     return false;
8956 
8957   // If we've fallen outside of the end offset, just pretend there's nothing to
8958   // write to/read from.
8959   if (EndOffset <= LVal.getLValueOffset())
8960     Size = 0;
8961   else
8962     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8963   return true;
8964 }
8965 
8966 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8967   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8968   if (E->getResultAPValueKind() != APValue::None)
8969     return Success(E->getAPValueResult(), E);
8970   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8971 }
8972 
8973 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8974   if (unsigned BuiltinOp = E->getBuiltinCallee())
8975     return VisitBuiltinCallExpr(E, BuiltinOp);
8976 
8977   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8978 }
8979 
8980 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8981                                             unsigned BuiltinOp) {
8982   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8983   default:
8984     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8985 
8986   case Builtin::BI__builtin_dynamic_object_size:
8987   case Builtin::BI__builtin_object_size: {
8988     // The type was checked when we built the expression.
8989     unsigned Type =
8990         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8991     assert(Type <= 3 && "unexpected type");
8992 
8993     uint64_t Size;
8994     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8995       return Success(Size, E);
8996 
8997     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8998       return Success((Type & 2) ? 0 : -1, E);
8999 
9000     // Expression had no side effects, but we couldn't statically determine the
9001     // size of the referenced object.
9002     switch (Info.EvalMode) {
9003     case EvalInfo::EM_ConstantExpression:
9004     case EvalInfo::EM_PotentialConstantExpression:
9005     case EvalInfo::EM_ConstantFold:
9006     case EvalInfo::EM_EvaluateForOverflow:
9007     case EvalInfo::EM_IgnoreSideEffects:
9008       // Leave it to IR generation.
9009       return Error(E);
9010     case EvalInfo::EM_ConstantExpressionUnevaluated:
9011     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
9012       // Reduce it to a constant now.
9013       return Success((Type & 2) ? 0 : -1, E);
9014     }
9015 
9016     llvm_unreachable("unexpected EvalMode");
9017   }
9018 
9019   case Builtin::BI__builtin_os_log_format_buffer_size: {
9020     analyze_os_log::OSLogBufferLayout Layout;
9021     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9022     return Success(Layout.size().getQuantity(), E);
9023   }
9024 
9025   case Builtin::BI__builtin_bswap16:
9026   case Builtin::BI__builtin_bswap32:
9027   case Builtin::BI__builtin_bswap64: {
9028     APSInt Val;
9029     if (!EvaluateInteger(E->getArg(0), Val, Info))
9030       return false;
9031 
9032     return Success(Val.byteSwap(), E);
9033   }
9034 
9035   case Builtin::BI__builtin_classify_type:
9036     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9037 
9038   case Builtin::BI__builtin_clrsb:
9039   case Builtin::BI__builtin_clrsbl:
9040   case Builtin::BI__builtin_clrsbll: {
9041     APSInt Val;
9042     if (!EvaluateInteger(E->getArg(0), Val, Info))
9043       return false;
9044 
9045     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9046   }
9047 
9048   case Builtin::BI__builtin_clz:
9049   case Builtin::BI__builtin_clzl:
9050   case Builtin::BI__builtin_clzll:
9051   case Builtin::BI__builtin_clzs: {
9052     APSInt Val;
9053     if (!EvaluateInteger(E->getArg(0), Val, Info))
9054       return false;
9055     if (!Val)
9056       return Error(E);
9057 
9058     return Success(Val.countLeadingZeros(), E);
9059   }
9060 
9061   case Builtin::BI__builtin_constant_p: {
9062     const Expr *Arg = E->getArg(0);
9063     if (EvaluateBuiltinConstantP(Info, Arg))
9064       return Success(true, E);
9065     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9066       // Outside a constant context, eagerly evaluate to false in the presence
9067       // of side-effects in order to avoid -Wunsequenced false-positives in
9068       // a branch on __builtin_constant_p(expr).
9069       return Success(false, E);
9070     }
9071     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9072     return false;
9073   }
9074 
9075   case Builtin::BI__builtin_is_constant_evaluated:
9076     return Success(Info.InConstantContext, E);
9077 
9078   case Builtin::BI__builtin_ctz:
9079   case Builtin::BI__builtin_ctzl:
9080   case Builtin::BI__builtin_ctzll:
9081   case Builtin::BI__builtin_ctzs: {
9082     APSInt Val;
9083     if (!EvaluateInteger(E->getArg(0), Val, Info))
9084       return false;
9085     if (!Val)
9086       return Error(E);
9087 
9088     return Success(Val.countTrailingZeros(), E);
9089   }
9090 
9091   case Builtin::BI__builtin_eh_return_data_regno: {
9092     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9093     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9094     return Success(Operand, E);
9095   }
9096 
9097   case Builtin::BI__builtin_expect:
9098     return Visit(E->getArg(0));
9099 
9100   case Builtin::BI__builtin_ffs:
9101   case Builtin::BI__builtin_ffsl:
9102   case Builtin::BI__builtin_ffsll: {
9103     APSInt Val;
9104     if (!EvaluateInteger(E->getArg(0), Val, Info))
9105       return false;
9106 
9107     unsigned N = Val.countTrailingZeros();
9108     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9109   }
9110 
9111   case Builtin::BI__builtin_fpclassify: {
9112     APFloat Val(0.0);
9113     if (!EvaluateFloat(E->getArg(5), Val, Info))
9114       return false;
9115     unsigned Arg;
9116     switch (Val.getCategory()) {
9117     case APFloat::fcNaN: Arg = 0; break;
9118     case APFloat::fcInfinity: Arg = 1; break;
9119     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9120     case APFloat::fcZero: Arg = 4; break;
9121     }
9122     return Visit(E->getArg(Arg));
9123   }
9124 
9125   case Builtin::BI__builtin_isinf_sign: {
9126     APFloat Val(0.0);
9127     return EvaluateFloat(E->getArg(0), Val, Info) &&
9128            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9129   }
9130 
9131   case Builtin::BI__builtin_isinf: {
9132     APFloat Val(0.0);
9133     return EvaluateFloat(E->getArg(0), Val, Info) &&
9134            Success(Val.isInfinity() ? 1 : 0, E);
9135   }
9136 
9137   case Builtin::BI__builtin_isfinite: {
9138     APFloat Val(0.0);
9139     return EvaluateFloat(E->getArg(0), Val, Info) &&
9140            Success(Val.isFinite() ? 1 : 0, E);
9141   }
9142 
9143   case Builtin::BI__builtin_isnan: {
9144     APFloat Val(0.0);
9145     return EvaluateFloat(E->getArg(0), Val, Info) &&
9146            Success(Val.isNaN() ? 1 : 0, E);
9147   }
9148 
9149   case Builtin::BI__builtin_isnormal: {
9150     APFloat Val(0.0);
9151     return EvaluateFloat(E->getArg(0), Val, Info) &&
9152            Success(Val.isNormal() ? 1 : 0, E);
9153   }
9154 
9155   case Builtin::BI__builtin_parity:
9156   case Builtin::BI__builtin_parityl:
9157   case Builtin::BI__builtin_parityll: {
9158     APSInt Val;
9159     if (!EvaluateInteger(E->getArg(0), Val, Info))
9160       return false;
9161 
9162     return Success(Val.countPopulation() % 2, E);
9163   }
9164 
9165   case Builtin::BI__builtin_popcount:
9166   case Builtin::BI__builtin_popcountl:
9167   case Builtin::BI__builtin_popcountll: {
9168     APSInt Val;
9169     if (!EvaluateInteger(E->getArg(0), Val, Info))
9170       return false;
9171 
9172     return Success(Val.countPopulation(), E);
9173   }
9174 
9175   case Builtin::BIstrlen:
9176   case Builtin::BIwcslen:
9177     // A call to strlen is not a constant expression.
9178     if (Info.getLangOpts().CPlusPlus11)
9179       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9180         << /*isConstexpr*/0 << /*isConstructor*/0
9181         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9182     else
9183       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9184     LLVM_FALLTHROUGH;
9185   case Builtin::BI__builtin_strlen:
9186   case Builtin::BI__builtin_wcslen: {
9187     // As an extension, we support __builtin_strlen() as a constant expression,
9188     // and support folding strlen() to a constant.
9189     LValue String;
9190     if (!EvaluatePointer(E->getArg(0), String, Info))
9191       return false;
9192 
9193     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9194 
9195     // Fast path: if it's a string literal, search the string value.
9196     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9197             String.getLValueBase().dyn_cast<const Expr *>())) {
9198       // The string literal may have embedded null characters. Find the first
9199       // one and truncate there.
9200       StringRef Str = S->getBytes();
9201       int64_t Off = String.Offset.getQuantity();
9202       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9203           S->getCharByteWidth() == 1 &&
9204           // FIXME: Add fast-path for wchar_t too.
9205           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9206         Str = Str.substr(Off);
9207 
9208         StringRef::size_type Pos = Str.find(0);
9209         if (Pos != StringRef::npos)
9210           Str = Str.substr(0, Pos);
9211 
9212         return Success(Str.size(), E);
9213       }
9214 
9215       // Fall through to slow path to issue appropriate diagnostic.
9216     }
9217 
9218     // Slow path: scan the bytes of the string looking for the terminating 0.
9219     for (uint64_t Strlen = 0; /**/; ++Strlen) {
9220       APValue Char;
9221       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9222           !Char.isInt())
9223         return false;
9224       if (!Char.getInt())
9225         return Success(Strlen, E);
9226       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9227         return false;
9228     }
9229   }
9230 
9231   case Builtin::BIstrcmp:
9232   case Builtin::BIwcscmp:
9233   case Builtin::BIstrncmp:
9234   case Builtin::BIwcsncmp:
9235   case Builtin::BImemcmp:
9236   case Builtin::BIbcmp:
9237   case Builtin::BIwmemcmp:
9238     // A call to strlen is not a constant expression.
9239     if (Info.getLangOpts().CPlusPlus11)
9240       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9241         << /*isConstexpr*/0 << /*isConstructor*/0
9242         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9243     else
9244       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9245     LLVM_FALLTHROUGH;
9246   case Builtin::BI__builtin_strcmp:
9247   case Builtin::BI__builtin_wcscmp:
9248   case Builtin::BI__builtin_strncmp:
9249   case Builtin::BI__builtin_wcsncmp:
9250   case Builtin::BI__builtin_memcmp:
9251   case Builtin::BI__builtin_bcmp:
9252   case Builtin::BI__builtin_wmemcmp: {
9253     LValue String1, String2;
9254     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9255         !EvaluatePointer(E->getArg(1), String2, Info))
9256       return false;
9257 
9258     uint64_t MaxLength = uint64_t(-1);
9259     if (BuiltinOp != Builtin::BIstrcmp &&
9260         BuiltinOp != Builtin::BIwcscmp &&
9261         BuiltinOp != Builtin::BI__builtin_strcmp &&
9262         BuiltinOp != Builtin::BI__builtin_wcscmp) {
9263       APSInt N;
9264       if (!EvaluateInteger(E->getArg(2), N, Info))
9265         return false;
9266       MaxLength = N.getExtValue();
9267     }
9268 
9269     // Empty substrings compare equal by definition.
9270     if (MaxLength == 0u)
9271       return Success(0, E);
9272 
9273     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9274         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9275         String1.Designator.Invalid || String2.Designator.Invalid)
9276       return false;
9277 
9278     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9279     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9280 
9281     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9282                      BuiltinOp == Builtin::BIbcmp ||
9283                      BuiltinOp == Builtin::BI__builtin_memcmp ||
9284                      BuiltinOp == Builtin::BI__builtin_bcmp;
9285 
9286     assert(IsRawByte ||
9287            (Info.Ctx.hasSameUnqualifiedType(
9288                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9289             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9290 
9291     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9292       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9293              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9294              Char1.isInt() && Char2.isInt();
9295     };
9296     const auto &AdvanceElems = [&] {
9297       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9298              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9299     };
9300 
9301     if (IsRawByte) {
9302       uint64_t BytesRemaining = MaxLength;
9303       // Pointers to const void may point to objects of incomplete type.
9304       if (CharTy1->isIncompleteType()) {
9305         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9306         return false;
9307       }
9308       if (CharTy2->isIncompleteType()) {
9309         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9310         return false;
9311       }
9312       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9313       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9314       // Give up on comparing between elements with disparate widths.
9315       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9316         return false;
9317       uint64_t BytesPerElement = CharTy1Size.getQuantity();
9318       assert(BytesRemaining && "BytesRemaining should not be zero: the "
9319                                "following loop considers at least one element");
9320       while (true) {
9321         APValue Char1, Char2;
9322         if (!ReadCurElems(Char1, Char2))
9323           return false;
9324         // We have compatible in-memory widths, but a possible type and
9325         // (for `bool`) internal representation mismatch.
9326         // Assuming two's complement representation, including 0 for `false` and
9327         // 1 for `true`, we can check an appropriate number of elements for
9328         // equality even if they are not byte-sized.
9329         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9330         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9331         if (Char1InMem.ne(Char2InMem)) {
9332           // If the elements are byte-sized, then we can produce a three-way
9333           // comparison result in a straightforward manner.
9334           if (BytesPerElement == 1u) {
9335             // memcmp always compares unsigned chars.
9336             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9337           }
9338           // The result is byte-order sensitive, and we have multibyte elements.
9339           // FIXME: We can compare the remaining bytes in the correct order.
9340           return false;
9341         }
9342         if (!AdvanceElems())
9343           return false;
9344         if (BytesRemaining <= BytesPerElement)
9345           break;
9346         BytesRemaining -= BytesPerElement;
9347       }
9348       // Enough elements are equal to account for the memcmp limit.
9349       return Success(0, E);
9350     }
9351 
9352     bool StopAtNull =
9353         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9354          BuiltinOp != Builtin::BIwmemcmp &&
9355          BuiltinOp != Builtin::BI__builtin_memcmp &&
9356          BuiltinOp != Builtin::BI__builtin_bcmp &&
9357          BuiltinOp != Builtin::BI__builtin_wmemcmp);
9358     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9359                   BuiltinOp == Builtin::BIwcsncmp ||
9360                   BuiltinOp == Builtin::BIwmemcmp ||
9361                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
9362                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9363                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
9364 
9365     for (; MaxLength; --MaxLength) {
9366       APValue Char1, Char2;
9367       if (!ReadCurElems(Char1, Char2))
9368         return false;
9369       if (Char1.getInt() != Char2.getInt()) {
9370         if (IsWide) // wmemcmp compares with wchar_t signedness.
9371           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9372         // memcmp always compares unsigned chars.
9373         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9374       }
9375       if (StopAtNull && !Char1.getInt())
9376         return Success(0, E);
9377       assert(!(StopAtNull && !Char2.getInt()));
9378       if (!AdvanceElems())
9379         return false;
9380     }
9381     // We hit the strncmp / memcmp limit.
9382     return Success(0, E);
9383   }
9384 
9385   case Builtin::BI__atomic_always_lock_free:
9386   case Builtin::BI__atomic_is_lock_free:
9387   case Builtin::BI__c11_atomic_is_lock_free: {
9388     APSInt SizeVal;
9389     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9390       return false;
9391 
9392     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9393     // of two less than the maximum inline atomic width, we know it is
9394     // lock-free.  If the size isn't a power of two, or greater than the
9395     // maximum alignment where we promote atomics, we know it is not lock-free
9396     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
9397     // the answer can only be determined at runtime; for example, 16-byte
9398     // atomics have lock-free implementations on some, but not all,
9399     // x86-64 processors.
9400 
9401     // Check power-of-two.
9402     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9403     if (Size.isPowerOfTwo()) {
9404       // Check against inlining width.
9405       unsigned InlineWidthBits =
9406           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9407       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9408         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9409             Size == CharUnits::One() ||
9410             E->getArg(1)->isNullPointerConstant(Info.Ctx,
9411                                                 Expr::NPC_NeverValueDependent))
9412           // OK, we will inline appropriately-aligned operations of this size,
9413           // and _Atomic(T) is appropriately-aligned.
9414           return Success(1, E);
9415 
9416         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9417           castAs<PointerType>()->getPointeeType();
9418         if (!PointeeType->isIncompleteType() &&
9419             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9420           // OK, we will inline operations on this object.
9421           return Success(1, E);
9422         }
9423       }
9424     }
9425 
9426     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9427         Success(0, E) : Error(E);
9428   }
9429   case Builtin::BIomp_is_initial_device:
9430     // We can decide statically which value the runtime would return if called.
9431     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9432   case Builtin::BI__builtin_add_overflow:
9433   case Builtin::BI__builtin_sub_overflow:
9434   case Builtin::BI__builtin_mul_overflow:
9435   case Builtin::BI__builtin_sadd_overflow:
9436   case Builtin::BI__builtin_uadd_overflow:
9437   case Builtin::BI__builtin_uaddl_overflow:
9438   case Builtin::BI__builtin_uaddll_overflow:
9439   case Builtin::BI__builtin_usub_overflow:
9440   case Builtin::BI__builtin_usubl_overflow:
9441   case Builtin::BI__builtin_usubll_overflow:
9442   case Builtin::BI__builtin_umul_overflow:
9443   case Builtin::BI__builtin_umull_overflow:
9444   case Builtin::BI__builtin_umulll_overflow:
9445   case Builtin::BI__builtin_saddl_overflow:
9446   case Builtin::BI__builtin_saddll_overflow:
9447   case Builtin::BI__builtin_ssub_overflow:
9448   case Builtin::BI__builtin_ssubl_overflow:
9449   case Builtin::BI__builtin_ssubll_overflow:
9450   case Builtin::BI__builtin_smul_overflow:
9451   case Builtin::BI__builtin_smull_overflow:
9452   case Builtin::BI__builtin_smulll_overflow: {
9453     LValue ResultLValue;
9454     APSInt LHS, RHS;
9455 
9456     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9457     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9458         !EvaluateInteger(E->getArg(1), RHS, Info) ||
9459         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9460       return false;
9461 
9462     APSInt Result;
9463     bool DidOverflow = false;
9464 
9465     // If the types don't have to match, enlarge all 3 to the largest of them.
9466     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9467         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9468         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9469       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9470                       ResultType->isSignedIntegerOrEnumerationType();
9471       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9472                       ResultType->isSignedIntegerOrEnumerationType();
9473       uint64_t LHSSize = LHS.getBitWidth();
9474       uint64_t RHSSize = RHS.getBitWidth();
9475       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9476       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9477 
9478       // Add an additional bit if the signedness isn't uniformly agreed to. We
9479       // could do this ONLY if there is a signed and an unsigned that both have
9480       // MaxBits, but the code to check that is pretty nasty.  The issue will be
9481       // caught in the shrink-to-result later anyway.
9482       if (IsSigned && !AllSigned)
9483         ++MaxBits;
9484 
9485       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9486       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9487       Result = APSInt(MaxBits, !IsSigned);
9488     }
9489 
9490     // Find largest int.
9491     switch (BuiltinOp) {
9492     default:
9493       llvm_unreachable("Invalid value for BuiltinOp");
9494     case Builtin::BI__builtin_add_overflow:
9495     case Builtin::BI__builtin_sadd_overflow:
9496     case Builtin::BI__builtin_saddl_overflow:
9497     case Builtin::BI__builtin_saddll_overflow:
9498     case Builtin::BI__builtin_uadd_overflow:
9499     case Builtin::BI__builtin_uaddl_overflow:
9500     case Builtin::BI__builtin_uaddll_overflow:
9501       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9502                               : LHS.uadd_ov(RHS, DidOverflow);
9503       break;
9504     case Builtin::BI__builtin_sub_overflow:
9505     case Builtin::BI__builtin_ssub_overflow:
9506     case Builtin::BI__builtin_ssubl_overflow:
9507     case Builtin::BI__builtin_ssubll_overflow:
9508     case Builtin::BI__builtin_usub_overflow:
9509     case Builtin::BI__builtin_usubl_overflow:
9510     case Builtin::BI__builtin_usubll_overflow:
9511       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9512                               : LHS.usub_ov(RHS, DidOverflow);
9513       break;
9514     case Builtin::BI__builtin_mul_overflow:
9515     case Builtin::BI__builtin_smul_overflow:
9516     case Builtin::BI__builtin_smull_overflow:
9517     case Builtin::BI__builtin_smulll_overflow:
9518     case Builtin::BI__builtin_umul_overflow:
9519     case Builtin::BI__builtin_umull_overflow:
9520     case Builtin::BI__builtin_umulll_overflow:
9521       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9522                               : LHS.umul_ov(RHS, DidOverflow);
9523       break;
9524     }
9525 
9526     // In the case where multiple sizes are allowed, truncate and see if
9527     // the values are the same.
9528     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9529         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9530         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9531       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9532       // since it will give us the behavior of a TruncOrSelf in the case where
9533       // its parameter <= its size.  We previously set Result to be at least the
9534       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9535       // will work exactly like TruncOrSelf.
9536       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9537       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9538 
9539       if (!APSInt::isSameValue(Temp, Result))
9540         DidOverflow = true;
9541       Result = Temp;
9542     }
9543 
9544     APValue APV{Result};
9545     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9546       return false;
9547     return Success(DidOverflow, E);
9548   }
9549   }
9550 }
9551 
9552 /// Determine whether this is a pointer past the end of the complete
9553 /// object referred to by the lvalue.
9554 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9555                                             const LValue &LV) {
9556   // A null pointer can be viewed as being "past the end" but we don't
9557   // choose to look at it that way here.
9558   if (!LV.getLValueBase())
9559     return false;
9560 
9561   // If the designator is valid and refers to a subobject, we're not pointing
9562   // past the end.
9563   if (!LV.getLValueDesignator().Invalid &&
9564       !LV.getLValueDesignator().isOnePastTheEnd())
9565     return false;
9566 
9567   // A pointer to an incomplete type might be past-the-end if the type's size is
9568   // zero.  We cannot tell because the type is incomplete.
9569   QualType Ty = getType(LV.getLValueBase());
9570   if (Ty->isIncompleteType())
9571     return true;
9572 
9573   // We're a past-the-end pointer if we point to the byte after the object,
9574   // no matter what our type or path is.
9575   auto Size = Ctx.getTypeSizeInChars(Ty);
9576   return LV.getLValueOffset() == Size;
9577 }
9578 
9579 namespace {
9580 
9581 /// Data recursive integer evaluator of certain binary operators.
9582 ///
9583 /// We use a data recursive algorithm for binary operators so that we are able
9584 /// to handle extreme cases of chained binary operators without causing stack
9585 /// overflow.
9586 class DataRecursiveIntBinOpEvaluator {
9587   struct EvalResult {
9588     APValue Val;
9589     bool Failed;
9590 
9591     EvalResult() : Failed(false) { }
9592 
9593     void swap(EvalResult &RHS) {
9594       Val.swap(RHS.Val);
9595       Failed = RHS.Failed;
9596       RHS.Failed = false;
9597     }
9598   };
9599 
9600   struct Job {
9601     const Expr *E;
9602     EvalResult LHSResult; // meaningful only for binary operator expression.
9603     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
9604 
9605     Job() = default;
9606     Job(Job &&) = default;
9607 
9608     void startSpeculativeEval(EvalInfo &Info) {
9609       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
9610     }
9611 
9612   private:
9613     SpeculativeEvaluationRAII SpecEvalRAII;
9614   };
9615 
9616   SmallVector<Job, 16> Queue;
9617 
9618   IntExprEvaluator &IntEval;
9619   EvalInfo &Info;
9620   APValue &FinalResult;
9621 
9622 public:
9623   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9624     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9625 
9626   /// True if \param E is a binary operator that we are going to handle
9627   /// data recursively.
9628   /// We handle binary operators that are comma, logical, or that have operands
9629   /// with integral or enumeration type.
9630   static bool shouldEnqueue(const BinaryOperator *E) {
9631     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9632            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
9633             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9634             E->getRHS()->getType()->isIntegralOrEnumerationType());
9635   }
9636 
9637   bool Traverse(const BinaryOperator *E) {
9638     enqueue(E);
9639     EvalResult PrevResult;
9640     while (!Queue.empty())
9641       process(PrevResult);
9642 
9643     if (PrevResult.Failed) return false;
9644 
9645     FinalResult.swap(PrevResult.Val);
9646     return true;
9647   }
9648 
9649 private:
9650   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9651     return IntEval.Success(Value, E, Result);
9652   }
9653   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9654     return IntEval.Success(Value, E, Result);
9655   }
9656   bool Error(const Expr *E) {
9657     return IntEval.Error(E);
9658   }
9659   bool Error(const Expr *E, diag::kind D) {
9660     return IntEval.Error(E, D);
9661   }
9662 
9663   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9664     return Info.CCEDiag(E, D);
9665   }
9666 
9667   // Returns true if visiting the RHS is necessary, false otherwise.
9668   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9669                          bool &SuppressRHSDiags);
9670 
9671   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9672                   const BinaryOperator *E, APValue &Result);
9673 
9674   void EvaluateExpr(const Expr *E, EvalResult &Result) {
9675     Result.Failed = !Evaluate(Result.Val, Info, E);
9676     if (Result.Failed)
9677       Result.Val = APValue();
9678   }
9679 
9680   void process(EvalResult &Result);
9681 
9682   void enqueue(const Expr *E) {
9683     E = E->IgnoreParens();
9684     Queue.resize(Queue.size()+1);
9685     Queue.back().E = E;
9686     Queue.back().Kind = Job::AnyExprKind;
9687   }
9688 };
9689 
9690 }
9691 
9692 bool DataRecursiveIntBinOpEvaluator::
9693        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9694                          bool &SuppressRHSDiags) {
9695   if (E->getOpcode() == BO_Comma) {
9696     // Ignore LHS but note if we could not evaluate it.
9697     if (LHSResult.Failed)
9698       return Info.noteSideEffect();
9699     return true;
9700   }
9701 
9702   if (E->isLogicalOp()) {
9703     bool LHSAsBool;
9704     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
9705       // We were able to evaluate the LHS, see if we can get away with not
9706       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
9707       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9708         Success(LHSAsBool, E, LHSResult.Val);
9709         return false; // Ignore RHS
9710       }
9711     } else {
9712       LHSResult.Failed = true;
9713 
9714       // Since we weren't able to evaluate the left hand side, it
9715       // might have had side effects.
9716       if (!Info.noteSideEffect())
9717         return false;
9718 
9719       // We can't evaluate the LHS; however, sometimes the result
9720       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9721       // Don't ignore RHS and suppress diagnostics from this arm.
9722       SuppressRHSDiags = true;
9723     }
9724 
9725     return true;
9726   }
9727 
9728   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9729          E->getRHS()->getType()->isIntegralOrEnumerationType());
9730 
9731   if (LHSResult.Failed && !Info.noteFailure())
9732     return false; // Ignore RHS;
9733 
9734   return true;
9735 }
9736 
9737 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9738                                     bool IsSub) {
9739   // Compute the new offset in the appropriate width, wrapping at 64 bits.
9740   // FIXME: When compiling for a 32-bit target, we should use 32-bit
9741   // offsets.
9742   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9743   CharUnits &Offset = LVal.getLValueOffset();
9744   uint64_t Offset64 = Offset.getQuantity();
9745   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9746   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9747                                          : Offset64 + Index64);
9748 }
9749 
9750 bool DataRecursiveIntBinOpEvaluator::
9751        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9752                   const BinaryOperator *E, APValue &Result) {
9753   if (E->getOpcode() == BO_Comma) {
9754     if (RHSResult.Failed)
9755       return false;
9756     Result = RHSResult.Val;
9757     return true;
9758   }
9759 
9760   if (E->isLogicalOp()) {
9761     bool lhsResult, rhsResult;
9762     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9763     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
9764 
9765     if (LHSIsOK) {
9766       if (RHSIsOK) {
9767         if (E->getOpcode() == BO_LOr)
9768           return Success(lhsResult || rhsResult, E, Result);
9769         else
9770           return Success(lhsResult && rhsResult, E, Result);
9771       }
9772     } else {
9773       if (RHSIsOK) {
9774         // We can't evaluate the LHS; however, sometimes the result
9775         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9776         if (rhsResult == (E->getOpcode() == BO_LOr))
9777           return Success(rhsResult, E, Result);
9778       }
9779     }
9780 
9781     return false;
9782   }
9783 
9784   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9785          E->getRHS()->getType()->isIntegralOrEnumerationType());
9786 
9787   if (LHSResult.Failed || RHSResult.Failed)
9788     return false;
9789 
9790   const APValue &LHSVal = LHSResult.Val;
9791   const APValue &RHSVal = RHSResult.Val;
9792 
9793   // Handle cases like (unsigned long)&a + 4.
9794   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9795     Result = LHSVal;
9796     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
9797     return true;
9798   }
9799 
9800   // Handle cases like 4 + (unsigned long)&a
9801   if (E->getOpcode() == BO_Add &&
9802       RHSVal.isLValue() && LHSVal.isInt()) {
9803     Result = RHSVal;
9804     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
9805     return true;
9806   }
9807 
9808   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9809     // Handle (intptr_t)&&A - (intptr_t)&&B.
9810     if (!LHSVal.getLValueOffset().isZero() ||
9811         !RHSVal.getLValueOffset().isZero())
9812       return false;
9813     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9814     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9815     if (!LHSExpr || !RHSExpr)
9816       return false;
9817     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9818     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9819     if (!LHSAddrExpr || !RHSAddrExpr)
9820       return false;
9821     // Make sure both labels come from the same function.
9822     if (LHSAddrExpr->getLabel()->getDeclContext() !=
9823         RHSAddrExpr->getLabel()->getDeclContext())
9824       return false;
9825     Result = APValue(LHSAddrExpr, RHSAddrExpr);
9826     return true;
9827   }
9828 
9829   // All the remaining cases expect both operands to be an integer
9830   if (!LHSVal.isInt() || !RHSVal.isInt())
9831     return Error(E);
9832 
9833   // Set up the width and signedness manually, in case it can't be deduced
9834   // from the operation we're performing.
9835   // FIXME: Don't do this in the cases where we can deduce it.
9836   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9837                E->getType()->isUnsignedIntegerOrEnumerationType());
9838   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9839                          RHSVal.getInt(), Value))
9840     return false;
9841   return Success(Value, E, Result);
9842 }
9843 
9844 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9845   Job &job = Queue.back();
9846 
9847   switch (job.Kind) {
9848     case Job::AnyExprKind: {
9849       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9850         if (shouldEnqueue(Bop)) {
9851           job.Kind = Job::BinOpKind;
9852           enqueue(Bop->getLHS());
9853           return;
9854         }
9855       }
9856 
9857       EvaluateExpr(job.E, Result);
9858       Queue.pop_back();
9859       return;
9860     }
9861 
9862     case Job::BinOpKind: {
9863       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9864       bool SuppressRHSDiags = false;
9865       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9866         Queue.pop_back();
9867         return;
9868       }
9869       if (SuppressRHSDiags)
9870         job.startSpeculativeEval(Info);
9871       job.LHSResult.swap(Result);
9872       job.Kind = Job::BinOpVisitedLHSKind;
9873       enqueue(Bop->getRHS());
9874       return;
9875     }
9876 
9877     case Job::BinOpVisitedLHSKind: {
9878       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9879       EvalResult RHS;
9880       RHS.swap(Result);
9881       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9882       Queue.pop_back();
9883       return;
9884     }
9885   }
9886 
9887   llvm_unreachable("Invalid Job::Kind!");
9888 }
9889 
9890 namespace {
9891 /// Used when we determine that we should fail, but can keep evaluating prior to
9892 /// noting that we had a failure.
9893 class DelayedNoteFailureRAII {
9894   EvalInfo &Info;
9895   bool NoteFailure;
9896 
9897 public:
9898   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9899       : Info(Info), NoteFailure(NoteFailure) {}
9900   ~DelayedNoteFailureRAII() {
9901     if (NoteFailure) {
9902       bool ContinueAfterFailure = Info.noteFailure();
9903       (void)ContinueAfterFailure;
9904       assert(ContinueAfterFailure &&
9905              "Shouldn't have kept evaluating on failure.");
9906     }
9907   }
9908 };
9909 }
9910 
9911 template <class SuccessCB, class AfterCB>
9912 static bool
9913 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9914                                  SuccessCB &&Success, AfterCB &&DoAfter) {
9915   assert(E->isComparisonOp() && "expected comparison operator");
9916   assert((E->getOpcode() == BO_Cmp ||
9917           E->getType()->isIntegralOrEnumerationType()) &&
9918          "unsupported binary expression evaluation");
9919   auto Error = [&](const Expr *E) {
9920     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9921     return false;
9922   };
9923 
9924   using CCR = ComparisonCategoryResult;
9925   bool IsRelational = E->isRelationalOp();
9926   bool IsEquality = E->isEqualityOp();
9927   if (E->getOpcode() == BO_Cmp) {
9928     const ComparisonCategoryInfo &CmpInfo =
9929         Info.Ctx.CompCategories.getInfoForType(E->getType());
9930     IsRelational = CmpInfo.isOrdered();
9931     IsEquality = CmpInfo.isEquality();
9932   }
9933 
9934   QualType LHSTy = E->getLHS()->getType();
9935   QualType RHSTy = E->getRHS()->getType();
9936 
9937   if (LHSTy->isIntegralOrEnumerationType() &&
9938       RHSTy->isIntegralOrEnumerationType()) {
9939     APSInt LHS, RHS;
9940     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9941     if (!LHSOK && !Info.noteFailure())
9942       return false;
9943     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9944       return false;
9945     if (LHS < RHS)
9946       return Success(CCR::Less, E);
9947     if (LHS > RHS)
9948       return Success(CCR::Greater, E);
9949     return Success(CCR::Equal, E);
9950   }
9951 
9952   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9953     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9954     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9955 
9956     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9957     if (!LHSOK && !Info.noteFailure())
9958       return false;
9959     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9960       return false;
9961     if (LHSFX < RHSFX)
9962       return Success(CCR::Less, E);
9963     if (LHSFX > RHSFX)
9964       return Success(CCR::Greater, E);
9965     return Success(CCR::Equal, E);
9966   }
9967 
9968   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
9969     ComplexValue LHS, RHS;
9970     bool LHSOK;
9971     if (E->isAssignmentOp()) {
9972       LValue LV;
9973       EvaluateLValue(E->getLHS(), LV, Info);
9974       LHSOK = false;
9975     } else if (LHSTy->isRealFloatingType()) {
9976       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9977       if (LHSOK) {
9978         LHS.makeComplexFloat();
9979         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9980       }
9981     } else {
9982       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9983     }
9984     if (!LHSOK && !Info.noteFailure())
9985       return false;
9986 
9987     if (E->getRHS()->getType()->isRealFloatingType()) {
9988       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9989         return false;
9990       RHS.makeComplexFloat();
9991       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9992     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9993       return false;
9994 
9995     if (LHS.isComplexFloat()) {
9996       APFloat::cmpResult CR_r =
9997         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9998       APFloat::cmpResult CR_i =
9999         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10000       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10001       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10002     } else {
10003       assert(IsEquality && "invalid complex comparison");
10004       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10005                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
10006       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10007     }
10008   }
10009 
10010   if (LHSTy->isRealFloatingType() &&
10011       RHSTy->isRealFloatingType()) {
10012     APFloat RHS(0.0), LHS(0.0);
10013 
10014     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10015     if (!LHSOK && !Info.noteFailure())
10016       return false;
10017 
10018     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10019       return false;
10020 
10021     assert(E->isComparisonOp() && "Invalid binary operator!");
10022     auto GetCmpRes = [&]() {
10023       switch (LHS.compare(RHS)) {
10024       case APFloat::cmpEqual:
10025         return CCR::Equal;
10026       case APFloat::cmpLessThan:
10027         return CCR::Less;
10028       case APFloat::cmpGreaterThan:
10029         return CCR::Greater;
10030       case APFloat::cmpUnordered:
10031         return CCR::Unordered;
10032       }
10033       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10034     };
10035     return Success(GetCmpRes(), E);
10036   }
10037 
10038   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10039     LValue LHSValue, RHSValue;
10040 
10041     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10042     if (!LHSOK && !Info.noteFailure())
10043       return false;
10044 
10045     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10046       return false;
10047 
10048     // Reject differing bases from the normal codepath; we special-case
10049     // comparisons to null.
10050     if (!HasSameBase(LHSValue, RHSValue)) {
10051       // Inequalities and subtractions between unrelated pointers have
10052       // unspecified or undefined behavior.
10053       if (!IsEquality)
10054         return Error(E);
10055       // A constant address may compare equal to the address of a symbol.
10056       // The one exception is that address of an object cannot compare equal
10057       // to a null pointer constant.
10058       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10059           (!RHSValue.Base && !RHSValue.Offset.isZero()))
10060         return Error(E);
10061       // It's implementation-defined whether distinct literals will have
10062       // distinct addresses. In clang, the result of such a comparison is
10063       // unspecified, so it is not a constant expression. However, we do know
10064       // that the address of a literal will be non-null.
10065       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10066           LHSValue.Base && RHSValue.Base)
10067         return Error(E);
10068       // We can't tell whether weak symbols will end up pointing to the same
10069       // object.
10070       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10071         return Error(E);
10072       // We can't compare the address of the start of one object with the
10073       // past-the-end address of another object, per C++ DR1652.
10074       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10075            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10076           (RHSValue.Base && RHSValue.Offset.isZero() &&
10077            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10078         return Error(E);
10079       // We can't tell whether an object is at the same address as another
10080       // zero sized object.
10081       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10082           (LHSValue.Base && isZeroSized(RHSValue)))
10083         return Error(E);
10084       return Success(CCR::Nonequal, E);
10085     }
10086 
10087     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10088     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10089 
10090     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10091     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10092 
10093     // C++11 [expr.rel]p3:
10094     //   Pointers to void (after pointer conversions) can be compared, with a
10095     //   result defined as follows: If both pointers represent the same
10096     //   address or are both the null pointer value, the result is true if the
10097     //   operator is <= or >= and false otherwise; otherwise the result is
10098     //   unspecified.
10099     // We interpret this as applying to pointers to *cv* void.
10100     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10101       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10102 
10103     // C++11 [expr.rel]p2:
10104     // - If two pointers point to non-static data members of the same object,
10105     //   or to subobjects or array elements fo such members, recursively, the
10106     //   pointer to the later declared member compares greater provided the
10107     //   two members have the same access control and provided their class is
10108     //   not a union.
10109     //   [...]
10110     // - Otherwise pointer comparisons are unspecified.
10111     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10112       bool WasArrayIndex;
10113       unsigned Mismatch = FindDesignatorMismatch(
10114           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10115       // At the point where the designators diverge, the comparison has a
10116       // specified value if:
10117       //  - we are comparing array indices
10118       //  - we are comparing fields of a union, or fields with the same access
10119       // Otherwise, the result is unspecified and thus the comparison is not a
10120       // constant expression.
10121       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10122           Mismatch < RHSDesignator.Entries.size()) {
10123         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10124         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10125         if (!LF && !RF)
10126           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10127         else if (!LF)
10128           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10129               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10130               << RF->getParent() << RF;
10131         else if (!RF)
10132           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10133               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10134               << LF->getParent() << LF;
10135         else if (!LF->getParent()->isUnion() &&
10136                  LF->getAccess() != RF->getAccess())
10137           Info.CCEDiag(E,
10138                        diag::note_constexpr_pointer_comparison_differing_access)
10139               << LF << LF->getAccess() << RF << RF->getAccess()
10140               << LF->getParent();
10141       }
10142     }
10143 
10144     // The comparison here must be unsigned, and performed with the same
10145     // width as the pointer.
10146     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10147     uint64_t CompareLHS = LHSOffset.getQuantity();
10148     uint64_t CompareRHS = RHSOffset.getQuantity();
10149     assert(PtrSize <= 64 && "Unexpected pointer width");
10150     uint64_t Mask = ~0ULL >> (64 - PtrSize);
10151     CompareLHS &= Mask;
10152     CompareRHS &= Mask;
10153 
10154     // If there is a base and this is a relational operator, we can only
10155     // compare pointers within the object in question; otherwise, the result
10156     // depends on where the object is located in memory.
10157     if (!LHSValue.Base.isNull() && IsRelational) {
10158       QualType BaseTy = getType(LHSValue.Base);
10159       if (BaseTy->isIncompleteType())
10160         return Error(E);
10161       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10162       uint64_t OffsetLimit = Size.getQuantity();
10163       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10164         return Error(E);
10165     }
10166 
10167     if (CompareLHS < CompareRHS)
10168       return Success(CCR::Less, E);
10169     if (CompareLHS > CompareRHS)
10170       return Success(CCR::Greater, E);
10171     return Success(CCR::Equal, E);
10172   }
10173 
10174   if (LHSTy->isMemberPointerType()) {
10175     assert(IsEquality && "unexpected member pointer operation");
10176     assert(RHSTy->isMemberPointerType() && "invalid comparison");
10177 
10178     MemberPtr LHSValue, RHSValue;
10179 
10180     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10181     if (!LHSOK && !Info.noteFailure())
10182       return false;
10183 
10184     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10185       return false;
10186 
10187     // C++11 [expr.eq]p2:
10188     //   If both operands are null, they compare equal. Otherwise if only one is
10189     //   null, they compare unequal.
10190     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10191       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10192       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10193     }
10194 
10195     //   Otherwise if either is a pointer to a virtual member function, the
10196     //   result is unspecified.
10197     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10198       if (MD->isVirtual())
10199         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10200     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10201       if (MD->isVirtual())
10202         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10203 
10204     //   Otherwise they compare equal if and only if they would refer to the
10205     //   same member of the same most derived object or the same subobject if
10206     //   they were dereferenced with a hypothetical object of the associated
10207     //   class type.
10208     bool Equal = LHSValue == RHSValue;
10209     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10210   }
10211 
10212   if (LHSTy->isNullPtrType()) {
10213     assert(E->isComparisonOp() && "unexpected nullptr operation");
10214     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10215     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10216     // are compared, the result is true of the operator is <=, >= or ==, and
10217     // false otherwise.
10218     return Success(CCR::Equal, E);
10219   }
10220 
10221   return DoAfter();
10222 }
10223 
10224 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10225   if (!CheckLiteralType(Info, E))
10226     return false;
10227 
10228   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10229                        const BinaryOperator *E) {
10230     // Evaluation succeeded. Lookup the information for the comparison category
10231     // type and fetch the VarDecl for the result.
10232     const ComparisonCategoryInfo &CmpInfo =
10233         Info.Ctx.CompCategories.getInfoForType(E->getType());
10234     const VarDecl *VD =
10235         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10236     // Check and evaluate the result as a constant expression.
10237     LValue LV;
10238     LV.set(VD);
10239     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10240       return false;
10241     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10242   };
10243   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10244     return ExprEvaluatorBaseTy::VisitBinCmp(E);
10245   });
10246 }
10247 
10248 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10249   // We don't call noteFailure immediately because the assignment happens after
10250   // we evaluate LHS and RHS.
10251   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10252     return Error(E);
10253 
10254   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10255   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10256     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10257 
10258   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10259           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10260          "DataRecursiveIntBinOpEvaluator should have handled integral types");
10261 
10262   if (E->isComparisonOp()) {
10263     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10264     // comparisons and then translating the result.
10265     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10266                          const BinaryOperator *E) {
10267       using CCR = ComparisonCategoryResult;
10268       bool IsEqual   = ResKind == CCR::Equal,
10269            IsLess    = ResKind == CCR::Less,
10270            IsGreater = ResKind == CCR::Greater;
10271       auto Op = E->getOpcode();
10272       switch (Op) {
10273       default:
10274         llvm_unreachable("unsupported binary operator");
10275       case BO_EQ:
10276       case BO_NE:
10277         return Success(IsEqual == (Op == BO_EQ), E);
10278       case BO_LT: return Success(IsLess, E);
10279       case BO_GT: return Success(IsGreater, E);
10280       case BO_LE: return Success(IsEqual || IsLess, E);
10281       case BO_GE: return Success(IsEqual || IsGreater, E);
10282       }
10283     };
10284     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10285       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10286     });
10287   }
10288 
10289   QualType LHSTy = E->getLHS()->getType();
10290   QualType RHSTy = E->getRHS()->getType();
10291 
10292   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10293       E->getOpcode() == BO_Sub) {
10294     LValue LHSValue, RHSValue;
10295 
10296     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10297     if (!LHSOK && !Info.noteFailure())
10298       return false;
10299 
10300     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10301       return false;
10302 
10303     // Reject differing bases from the normal codepath; we special-case
10304     // comparisons to null.
10305     if (!HasSameBase(LHSValue, RHSValue)) {
10306       // Handle &&A - &&B.
10307       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10308         return Error(E);
10309       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10310       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10311       if (!LHSExpr || !RHSExpr)
10312         return Error(E);
10313       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10314       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10315       if (!LHSAddrExpr || !RHSAddrExpr)
10316         return Error(E);
10317       // Make sure both labels come from the same function.
10318       if (LHSAddrExpr->getLabel()->getDeclContext() !=
10319           RHSAddrExpr->getLabel()->getDeclContext())
10320         return Error(E);
10321       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10322     }
10323     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10324     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10325 
10326     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10327     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10328 
10329     // C++11 [expr.add]p6:
10330     //   Unless both pointers point to elements of the same array object, or
10331     //   one past the last element of the array object, the behavior is
10332     //   undefined.
10333     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10334         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10335                                 RHSDesignator))
10336       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10337 
10338     QualType Type = E->getLHS()->getType();
10339     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10340 
10341     CharUnits ElementSize;
10342     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10343       return false;
10344 
10345     // As an extension, a type may have zero size (empty struct or union in
10346     // C, array of zero length). Pointer subtraction in such cases has
10347     // undefined behavior, so is not constant.
10348     if (ElementSize.isZero()) {
10349       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10350           << ElementType;
10351       return false;
10352     }
10353 
10354     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10355     // and produce incorrect results when it overflows. Such behavior
10356     // appears to be non-conforming, but is common, so perhaps we should
10357     // assume the standard intended for such cases to be undefined behavior
10358     // and check for them.
10359 
10360     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10361     // overflow in the final conversion to ptrdiff_t.
10362     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10363     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10364     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10365                     false);
10366     APSInt TrueResult = (LHS - RHS) / ElemSize;
10367     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10368 
10369     if (Result.extend(65) != TrueResult &&
10370         !HandleOverflow(Info, E, TrueResult, E->getType()))
10371       return false;
10372     return Success(Result, E);
10373   }
10374 
10375   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10376 }
10377 
10378 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10379 /// a result as the expression's type.
10380 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10381                                     const UnaryExprOrTypeTraitExpr *E) {
10382   switch(E->getKind()) {
10383   case UETT_PreferredAlignOf:
10384   case UETT_AlignOf: {
10385     if (E->isArgumentType())
10386       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10387                      E);
10388     else
10389       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10390                      E);
10391   }
10392 
10393   case UETT_VecStep: {
10394     QualType Ty = E->getTypeOfArgument();
10395 
10396     if (Ty->isVectorType()) {
10397       unsigned n = Ty->castAs<VectorType>()->getNumElements();
10398 
10399       // The vec_step built-in functions that take a 3-component
10400       // vector return 4. (OpenCL 1.1 spec 6.11.12)
10401       if (n == 3)
10402         n = 4;
10403 
10404       return Success(n, E);
10405     } else
10406       return Success(1, E);
10407   }
10408 
10409   case UETT_SizeOf: {
10410     QualType SrcTy = E->getTypeOfArgument();
10411     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10412     //   the result is the size of the referenced type."
10413     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10414       SrcTy = Ref->getPointeeType();
10415 
10416     CharUnits Sizeof;
10417     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10418       return false;
10419     return Success(Sizeof, E);
10420   }
10421   case UETT_OpenMPRequiredSimdAlign:
10422     assert(E->isArgumentType());
10423     return Success(
10424         Info.Ctx.toCharUnitsFromBits(
10425                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10426             .getQuantity(),
10427         E);
10428   }
10429 
10430   llvm_unreachable("unknown expr/type trait");
10431 }
10432 
10433 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10434   CharUnits Result;
10435   unsigned n = OOE->getNumComponents();
10436   if (n == 0)
10437     return Error(OOE);
10438   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10439   for (unsigned i = 0; i != n; ++i) {
10440     OffsetOfNode ON = OOE->getComponent(i);
10441     switch (ON.getKind()) {
10442     case OffsetOfNode::Array: {
10443       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10444       APSInt IdxResult;
10445       if (!EvaluateInteger(Idx, IdxResult, Info))
10446         return false;
10447       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10448       if (!AT)
10449         return Error(OOE);
10450       CurrentType = AT->getElementType();
10451       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10452       Result += IdxResult.getSExtValue() * ElementSize;
10453       break;
10454     }
10455 
10456     case OffsetOfNode::Field: {
10457       FieldDecl *MemberDecl = ON.getField();
10458       const RecordType *RT = CurrentType->getAs<RecordType>();
10459       if (!RT)
10460         return Error(OOE);
10461       RecordDecl *RD = RT->getDecl();
10462       if (RD->isInvalidDecl()) return false;
10463       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10464       unsigned i = MemberDecl->getFieldIndex();
10465       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10466       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10467       CurrentType = MemberDecl->getType().getNonReferenceType();
10468       break;
10469     }
10470 
10471     case OffsetOfNode::Identifier:
10472       llvm_unreachable("dependent __builtin_offsetof");
10473 
10474     case OffsetOfNode::Base: {
10475       CXXBaseSpecifier *BaseSpec = ON.getBase();
10476       if (BaseSpec->isVirtual())
10477         return Error(OOE);
10478 
10479       // Find the layout of the class whose base we are looking into.
10480       const RecordType *RT = CurrentType->getAs<RecordType>();
10481       if (!RT)
10482         return Error(OOE);
10483       RecordDecl *RD = RT->getDecl();
10484       if (RD->isInvalidDecl()) return false;
10485       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10486 
10487       // Find the base class itself.
10488       CurrentType = BaseSpec->getType();
10489       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10490       if (!BaseRT)
10491         return Error(OOE);
10492 
10493       // Add the offset to the base.
10494       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10495       break;
10496     }
10497     }
10498   }
10499   return Success(Result, OOE);
10500 }
10501 
10502 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10503   switch (E->getOpcode()) {
10504   default:
10505     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10506     // See C99 6.6p3.
10507     return Error(E);
10508   case UO_Extension:
10509     // FIXME: Should extension allow i-c-e extension expressions in its scope?
10510     // If so, we could clear the diagnostic ID.
10511     return Visit(E->getSubExpr());
10512   case UO_Plus:
10513     // The result is just the value.
10514     return Visit(E->getSubExpr());
10515   case UO_Minus: {
10516     if (!Visit(E->getSubExpr()))
10517       return false;
10518     if (!Result.isInt()) return Error(E);
10519     const APSInt &Value = Result.getInt();
10520     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10521         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10522                         E->getType()))
10523       return false;
10524     return Success(-Value, E);
10525   }
10526   case UO_Not: {
10527     if (!Visit(E->getSubExpr()))
10528       return false;
10529     if (!Result.isInt()) return Error(E);
10530     return Success(~Result.getInt(), E);
10531   }
10532   case UO_LNot: {
10533     bool bres;
10534     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10535       return false;
10536     return Success(!bres, E);
10537   }
10538   }
10539 }
10540 
10541 /// HandleCast - This is used to evaluate implicit or explicit casts where the
10542 /// result type is integer.
10543 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10544   const Expr *SubExpr = E->getSubExpr();
10545   QualType DestType = E->getType();
10546   QualType SrcType = SubExpr->getType();
10547 
10548   switch (E->getCastKind()) {
10549   case CK_BaseToDerived:
10550   case CK_DerivedToBase:
10551   case CK_UncheckedDerivedToBase:
10552   case CK_Dynamic:
10553   case CK_ToUnion:
10554   case CK_ArrayToPointerDecay:
10555   case CK_FunctionToPointerDecay:
10556   case CK_NullToPointer:
10557   case CK_NullToMemberPointer:
10558   case CK_BaseToDerivedMemberPointer:
10559   case CK_DerivedToBaseMemberPointer:
10560   case CK_ReinterpretMemberPointer:
10561   case CK_ConstructorConversion:
10562   case CK_IntegralToPointer:
10563   case CK_ToVoid:
10564   case CK_VectorSplat:
10565   case CK_IntegralToFloating:
10566   case CK_FloatingCast:
10567   case CK_CPointerToObjCPointerCast:
10568   case CK_BlockPointerToObjCPointerCast:
10569   case CK_AnyPointerToBlockPointerCast:
10570   case CK_ObjCObjectLValueCast:
10571   case CK_FloatingRealToComplex:
10572   case CK_FloatingComplexToReal:
10573   case CK_FloatingComplexCast:
10574   case CK_FloatingComplexToIntegralComplex:
10575   case CK_IntegralRealToComplex:
10576   case CK_IntegralComplexCast:
10577   case CK_IntegralComplexToFloatingComplex:
10578   case CK_BuiltinFnToFnPtr:
10579   case CK_ZeroToOCLOpaqueType:
10580   case CK_NonAtomicToAtomic:
10581   case CK_AddressSpaceConversion:
10582   case CK_IntToOCLSampler:
10583   case CK_FixedPointCast:
10584   case CK_IntegralToFixedPoint:
10585     llvm_unreachable("invalid cast kind for integral value");
10586 
10587   case CK_BitCast:
10588   case CK_Dependent:
10589   case CK_LValueBitCast:
10590   case CK_ARCProduceObject:
10591   case CK_ARCConsumeObject:
10592   case CK_ARCReclaimReturnedObject:
10593   case CK_ARCExtendBlockObject:
10594   case CK_CopyAndAutoreleaseBlockObject:
10595     return Error(E);
10596 
10597   case CK_UserDefinedConversion:
10598   case CK_LValueToRValue:
10599   case CK_AtomicToNonAtomic:
10600   case CK_NoOp:
10601     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10602 
10603   case CK_MemberPointerToBoolean:
10604   case CK_PointerToBoolean:
10605   case CK_IntegralToBoolean:
10606   case CK_FloatingToBoolean:
10607   case CK_BooleanToSignedIntegral:
10608   case CK_FloatingComplexToBoolean:
10609   case CK_IntegralComplexToBoolean: {
10610     bool BoolResult;
10611     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
10612       return false;
10613     uint64_t IntResult = BoolResult;
10614     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10615       IntResult = (uint64_t)-1;
10616     return Success(IntResult, E);
10617   }
10618 
10619   case CK_FixedPointToIntegral: {
10620     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10621     if (!EvaluateFixedPoint(SubExpr, Src, Info))
10622       return false;
10623     bool Overflowed;
10624     llvm::APSInt Result = Src.convertToInt(
10625         Info.Ctx.getIntWidth(DestType),
10626         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10627     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10628       return false;
10629     return Success(Result, E);
10630   }
10631 
10632   case CK_FixedPointToBoolean: {
10633     // Unsigned padding does not affect this.
10634     APValue Val;
10635     if (!Evaluate(Val, Info, SubExpr))
10636       return false;
10637     return Success(Val.getFixedPoint().getBoolValue(), E);
10638   }
10639 
10640   case CK_IntegralCast: {
10641     if (!Visit(SubExpr))
10642       return false;
10643 
10644     if (!Result.isInt()) {
10645       // Allow casts of address-of-label differences if they are no-ops
10646       // or narrowing.  (The narrowing case isn't actually guaranteed to
10647       // be constant-evaluatable except in some narrow cases which are hard
10648       // to detect here.  We let it through on the assumption the user knows
10649       // what they are doing.)
10650       if (Result.isAddrLabelDiff())
10651         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
10652       // Only allow casts of lvalues if they are lossless.
10653       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10654     }
10655 
10656     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10657                                       Result.getInt()), E);
10658   }
10659 
10660   case CK_PointerToIntegral: {
10661     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10662 
10663     LValue LV;
10664     if (!EvaluatePointer(SubExpr, LV, Info))
10665       return false;
10666 
10667     if (LV.getLValueBase()) {
10668       // Only allow based lvalue casts if they are lossless.
10669       // FIXME: Allow a larger integer size than the pointer size, and allow
10670       // narrowing back down to pointer width in subsequent integral casts.
10671       // FIXME: Check integer type's active bits, not its type size.
10672       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
10673         return Error(E);
10674 
10675       LV.Designator.setInvalid();
10676       LV.moveInto(Result);
10677       return true;
10678     }
10679 
10680     APSInt AsInt;
10681     APValue V;
10682     LV.moveInto(V);
10683     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10684       llvm_unreachable("Can't cast this!");
10685 
10686     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
10687   }
10688 
10689   case CK_IntegralComplexToReal: {
10690     ComplexValue C;
10691     if (!EvaluateComplex(SubExpr, C, Info))
10692       return false;
10693     return Success(C.getComplexIntReal(), E);
10694   }
10695 
10696   case CK_FloatingToIntegral: {
10697     APFloat F(0.0);
10698     if (!EvaluateFloat(SubExpr, F, Info))
10699       return false;
10700 
10701     APSInt Value;
10702     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10703       return false;
10704     return Success(Value, E);
10705   }
10706   }
10707 
10708   llvm_unreachable("unknown cast resulting in integral value");
10709 }
10710 
10711 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10712   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10713     ComplexValue LV;
10714     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10715       return false;
10716     if (!LV.isComplexInt())
10717       return Error(E);
10718     return Success(LV.getComplexIntReal(), E);
10719   }
10720 
10721   return Visit(E->getSubExpr());
10722 }
10723 
10724 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10725   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
10726     ComplexValue LV;
10727     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10728       return false;
10729     if (!LV.isComplexInt())
10730       return Error(E);
10731     return Success(LV.getComplexIntImag(), E);
10732   }
10733 
10734   VisitIgnoredValue(E->getSubExpr());
10735   return Success(0, E);
10736 }
10737 
10738 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10739   return Success(E->getPackLength(), E);
10740 }
10741 
10742 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10743   return Success(E->getValue(), E);
10744 }
10745 
10746 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10747   switch (E->getOpcode()) {
10748     default:
10749       // Invalid unary operators
10750       return Error(E);
10751     case UO_Plus:
10752       // The result is just the value.
10753       return Visit(E->getSubExpr());
10754     case UO_Minus: {
10755       if (!Visit(E->getSubExpr())) return false;
10756       if (!Result.isFixedPoint())
10757         return Error(E);
10758       bool Overflowed;
10759       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10760       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10761         return false;
10762       return Success(Negated, E);
10763     }
10764     case UO_LNot: {
10765       bool bres;
10766       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10767         return false;
10768       return Success(!bres, E);
10769     }
10770   }
10771 }
10772 
10773 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10774   const Expr *SubExpr = E->getSubExpr();
10775   QualType DestType = E->getType();
10776   assert(DestType->isFixedPointType() &&
10777          "Expected destination type to be a fixed point type");
10778   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10779 
10780   switch (E->getCastKind()) {
10781   case CK_FixedPointCast: {
10782     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10783     if (!EvaluateFixedPoint(SubExpr, Src, Info))
10784       return false;
10785     bool Overflowed;
10786     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10787     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10788       return false;
10789     return Success(Result, E);
10790   }
10791   case CK_IntegralToFixedPoint: {
10792     APSInt Src;
10793     if (!EvaluateInteger(SubExpr, Src, Info))
10794       return false;
10795 
10796     bool Overflowed;
10797     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10798         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10799 
10800     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10801       return false;
10802 
10803     return Success(IntResult, E);
10804   }
10805   case CK_NoOp:
10806   case CK_LValueToRValue:
10807     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10808   default:
10809     return Error(E);
10810   }
10811 }
10812 
10813 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10814   const Expr *LHS = E->getLHS();
10815   const Expr *RHS = E->getRHS();
10816   FixedPointSemantics ResultFXSema =
10817       Info.Ctx.getFixedPointSemantics(E->getType());
10818 
10819   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10820   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10821     return false;
10822   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10823   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10824     return false;
10825 
10826   switch (E->getOpcode()) {
10827   case BO_Add: {
10828     bool AddOverflow, ConversionOverflow;
10829     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10830                               .convert(ResultFXSema, &ConversionOverflow);
10831     if ((AddOverflow || ConversionOverflow) &&
10832         !HandleOverflow(Info, E, Result, E->getType()))
10833       return false;
10834     return Success(Result, E);
10835   }
10836   default:
10837     return false;
10838   }
10839   llvm_unreachable("Should've exited before this");
10840 }
10841 
10842 //===----------------------------------------------------------------------===//
10843 // Float Evaluation
10844 //===----------------------------------------------------------------------===//
10845 
10846 namespace {
10847 class FloatExprEvaluator
10848   : public ExprEvaluatorBase<FloatExprEvaluator> {
10849   APFloat &Result;
10850 public:
10851   FloatExprEvaluator(EvalInfo &info, APFloat &result)
10852     : ExprEvaluatorBaseTy(info), Result(result) {}
10853 
10854   bool Success(const APValue &V, const Expr *e) {
10855     Result = V.getFloat();
10856     return true;
10857   }
10858 
10859   bool ZeroInitialization(const Expr *E) {
10860     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10861     return true;
10862   }
10863 
10864   bool VisitCallExpr(const CallExpr *E);
10865 
10866   bool VisitUnaryOperator(const UnaryOperator *E);
10867   bool VisitBinaryOperator(const BinaryOperator *E);
10868   bool VisitFloatingLiteral(const FloatingLiteral *E);
10869   bool VisitCastExpr(const CastExpr *E);
10870 
10871   bool VisitUnaryReal(const UnaryOperator *E);
10872   bool VisitUnaryImag(const UnaryOperator *E);
10873 
10874   // FIXME: Missing: array subscript of vector, member of vector
10875 };
10876 } // end anonymous namespace
10877 
10878 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
10879   assert(E->isRValue() && E->getType()->isRealFloatingType());
10880   return FloatExprEvaluator(Info, Result).Visit(E);
10881 }
10882 
10883 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
10884                                   QualType ResultTy,
10885                                   const Expr *Arg,
10886                                   bool SNaN,
10887                                   llvm::APFloat &Result) {
10888   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10889   if (!S) return false;
10890 
10891   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10892 
10893   llvm::APInt fill;
10894 
10895   // Treat empty strings as if they were zero.
10896   if (S->getString().empty())
10897     fill = llvm::APInt(32, 0);
10898   else if (S->getString().getAsInteger(0, fill))
10899     return false;
10900 
10901   if (Context.getTargetInfo().isNan2008()) {
10902     if (SNaN)
10903       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10904     else
10905       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10906   } else {
10907     // Prior to IEEE 754-2008, architectures were allowed to choose whether
10908     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10909     // a different encoding to what became a standard in 2008, and for pre-
10910     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10911     // sNaN. This is now known as "legacy NaN" encoding.
10912     if (SNaN)
10913       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10914     else
10915       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10916   }
10917 
10918   return true;
10919 }
10920 
10921 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
10922   switch (E->getBuiltinCallee()) {
10923   default:
10924     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10925 
10926   case Builtin::BI__builtin_huge_val:
10927   case Builtin::BI__builtin_huge_valf:
10928   case Builtin::BI__builtin_huge_vall:
10929   case Builtin::BI__builtin_huge_valf128:
10930   case Builtin::BI__builtin_inf:
10931   case Builtin::BI__builtin_inff:
10932   case Builtin::BI__builtin_infl:
10933   case Builtin::BI__builtin_inff128: {
10934     const llvm::fltSemantics &Sem =
10935       Info.Ctx.getFloatTypeSemantics(E->getType());
10936     Result = llvm::APFloat::getInf(Sem);
10937     return true;
10938   }
10939 
10940   case Builtin::BI__builtin_nans:
10941   case Builtin::BI__builtin_nansf:
10942   case Builtin::BI__builtin_nansl:
10943   case Builtin::BI__builtin_nansf128:
10944     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10945                                true, Result))
10946       return Error(E);
10947     return true;
10948 
10949   case Builtin::BI__builtin_nan:
10950   case Builtin::BI__builtin_nanf:
10951   case Builtin::BI__builtin_nanl:
10952   case Builtin::BI__builtin_nanf128:
10953     // If this is __builtin_nan() turn this into a nan, otherwise we
10954     // can't constant fold it.
10955     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10956                                false, Result))
10957       return Error(E);
10958     return true;
10959 
10960   case Builtin::BI__builtin_fabs:
10961   case Builtin::BI__builtin_fabsf:
10962   case Builtin::BI__builtin_fabsl:
10963   case Builtin::BI__builtin_fabsf128:
10964     if (!EvaluateFloat(E->getArg(0), Result, Info))
10965       return false;
10966 
10967     if (Result.isNegative())
10968       Result.changeSign();
10969     return true;
10970 
10971   // FIXME: Builtin::BI__builtin_powi
10972   // FIXME: Builtin::BI__builtin_powif
10973   // FIXME: Builtin::BI__builtin_powil
10974 
10975   case Builtin::BI__builtin_copysign:
10976   case Builtin::BI__builtin_copysignf:
10977   case Builtin::BI__builtin_copysignl:
10978   case Builtin::BI__builtin_copysignf128: {
10979     APFloat RHS(0.);
10980     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10981         !EvaluateFloat(E->getArg(1), RHS, Info))
10982       return false;
10983     Result.copySign(RHS);
10984     return true;
10985   }
10986   }
10987 }
10988 
10989 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10990   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10991     ComplexValue CV;
10992     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10993       return false;
10994     Result = CV.FloatReal;
10995     return true;
10996   }
10997 
10998   return Visit(E->getSubExpr());
10999 }
11000 
11001 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11002   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11003     ComplexValue CV;
11004     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11005       return false;
11006     Result = CV.FloatImag;
11007     return true;
11008   }
11009 
11010   VisitIgnoredValue(E->getSubExpr());
11011   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11012   Result = llvm::APFloat::getZero(Sem);
11013   return true;
11014 }
11015 
11016 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11017   switch (E->getOpcode()) {
11018   default: return Error(E);
11019   case UO_Plus:
11020     return EvaluateFloat(E->getSubExpr(), Result, Info);
11021   case UO_Minus:
11022     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11023       return false;
11024     Result.changeSign();
11025     return true;
11026   }
11027 }
11028 
11029 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11030   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11031     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11032 
11033   APFloat RHS(0.0);
11034   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11035   if (!LHSOK && !Info.noteFailure())
11036     return false;
11037   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11038          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11039 }
11040 
11041 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11042   Result = E->getValue();
11043   return true;
11044 }
11045 
11046 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11047   const Expr* SubExpr = E->getSubExpr();
11048 
11049   switch (E->getCastKind()) {
11050   default:
11051     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11052 
11053   case CK_IntegralToFloating: {
11054     APSInt IntResult;
11055     return EvaluateInteger(SubExpr, IntResult, Info) &&
11056            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11057                                 E->getType(), Result);
11058   }
11059 
11060   case CK_FloatingCast: {
11061     if (!Visit(SubExpr))
11062       return false;
11063     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11064                                   Result);
11065   }
11066 
11067   case CK_FloatingComplexToReal: {
11068     ComplexValue V;
11069     if (!EvaluateComplex(SubExpr, V, Info))
11070       return false;
11071     Result = V.getComplexFloatReal();
11072     return true;
11073   }
11074   }
11075 }
11076 
11077 //===----------------------------------------------------------------------===//
11078 // Complex Evaluation (for float and integer)
11079 //===----------------------------------------------------------------------===//
11080 
11081 namespace {
11082 class ComplexExprEvaluator
11083   : public ExprEvaluatorBase<ComplexExprEvaluator> {
11084   ComplexValue &Result;
11085 
11086 public:
11087   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11088     : ExprEvaluatorBaseTy(info), Result(Result) {}
11089 
11090   bool Success(const APValue &V, const Expr *e) {
11091     Result.setFrom(V);
11092     return true;
11093   }
11094 
11095   bool ZeroInitialization(const Expr *E);
11096 
11097   //===--------------------------------------------------------------------===//
11098   //                            Visitor Methods
11099   //===--------------------------------------------------------------------===//
11100 
11101   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11102   bool VisitCastExpr(const CastExpr *E);
11103   bool VisitBinaryOperator(const BinaryOperator *E);
11104   bool VisitUnaryOperator(const UnaryOperator *E);
11105   bool VisitInitListExpr(const InitListExpr *E);
11106 };
11107 } // end anonymous namespace
11108 
11109 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11110                             EvalInfo &Info) {
11111   assert(E->isRValue() && E->getType()->isAnyComplexType());
11112   return ComplexExprEvaluator(Info, Result).Visit(E);
11113 }
11114 
11115 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11116   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11117   if (ElemTy->isRealFloatingType()) {
11118     Result.makeComplexFloat();
11119     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11120     Result.FloatReal = Zero;
11121     Result.FloatImag = Zero;
11122   } else {
11123     Result.makeComplexInt();
11124     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11125     Result.IntReal = Zero;
11126     Result.IntImag = Zero;
11127   }
11128   return true;
11129 }
11130 
11131 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11132   const Expr* SubExpr = E->getSubExpr();
11133 
11134   if (SubExpr->getType()->isRealFloatingType()) {
11135     Result.makeComplexFloat();
11136     APFloat &Imag = Result.FloatImag;
11137     if (!EvaluateFloat(SubExpr, Imag, Info))
11138       return false;
11139 
11140     Result.FloatReal = APFloat(Imag.getSemantics());
11141     return true;
11142   } else {
11143     assert(SubExpr->getType()->isIntegerType() &&
11144            "Unexpected imaginary literal.");
11145 
11146     Result.makeComplexInt();
11147     APSInt &Imag = Result.IntImag;
11148     if (!EvaluateInteger(SubExpr, Imag, Info))
11149       return false;
11150 
11151     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11152     return true;
11153   }
11154 }
11155 
11156 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11157 
11158   switch (E->getCastKind()) {
11159   case CK_BitCast:
11160   case CK_BaseToDerived:
11161   case CK_DerivedToBase:
11162   case CK_UncheckedDerivedToBase:
11163   case CK_Dynamic:
11164   case CK_ToUnion:
11165   case CK_ArrayToPointerDecay:
11166   case CK_FunctionToPointerDecay:
11167   case CK_NullToPointer:
11168   case CK_NullToMemberPointer:
11169   case CK_BaseToDerivedMemberPointer:
11170   case CK_DerivedToBaseMemberPointer:
11171   case CK_MemberPointerToBoolean:
11172   case CK_ReinterpretMemberPointer:
11173   case CK_ConstructorConversion:
11174   case CK_IntegralToPointer:
11175   case CK_PointerToIntegral:
11176   case CK_PointerToBoolean:
11177   case CK_ToVoid:
11178   case CK_VectorSplat:
11179   case CK_IntegralCast:
11180   case CK_BooleanToSignedIntegral:
11181   case CK_IntegralToBoolean:
11182   case CK_IntegralToFloating:
11183   case CK_FloatingToIntegral:
11184   case CK_FloatingToBoolean:
11185   case CK_FloatingCast:
11186   case CK_CPointerToObjCPointerCast:
11187   case CK_BlockPointerToObjCPointerCast:
11188   case CK_AnyPointerToBlockPointerCast:
11189   case CK_ObjCObjectLValueCast:
11190   case CK_FloatingComplexToReal:
11191   case CK_FloatingComplexToBoolean:
11192   case CK_IntegralComplexToReal:
11193   case CK_IntegralComplexToBoolean:
11194   case CK_ARCProduceObject:
11195   case CK_ARCConsumeObject:
11196   case CK_ARCReclaimReturnedObject:
11197   case CK_ARCExtendBlockObject:
11198   case CK_CopyAndAutoreleaseBlockObject:
11199   case CK_BuiltinFnToFnPtr:
11200   case CK_ZeroToOCLOpaqueType:
11201   case CK_NonAtomicToAtomic:
11202   case CK_AddressSpaceConversion:
11203   case CK_IntToOCLSampler:
11204   case CK_FixedPointCast:
11205   case CK_FixedPointToBoolean:
11206   case CK_FixedPointToIntegral:
11207   case CK_IntegralToFixedPoint:
11208     llvm_unreachable("invalid cast kind for complex value");
11209 
11210   case CK_LValueToRValue:
11211   case CK_AtomicToNonAtomic:
11212   case CK_NoOp:
11213     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11214 
11215   case CK_Dependent:
11216   case CK_LValueBitCast:
11217   case CK_UserDefinedConversion:
11218     return Error(E);
11219 
11220   case CK_FloatingRealToComplex: {
11221     APFloat &Real = Result.FloatReal;
11222     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11223       return false;
11224 
11225     Result.makeComplexFloat();
11226     Result.FloatImag = APFloat(Real.getSemantics());
11227     return true;
11228   }
11229 
11230   case CK_FloatingComplexCast: {
11231     if (!Visit(E->getSubExpr()))
11232       return false;
11233 
11234     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11235     QualType From
11236       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11237 
11238     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11239            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11240   }
11241 
11242   case CK_FloatingComplexToIntegralComplex: {
11243     if (!Visit(E->getSubExpr()))
11244       return false;
11245 
11246     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11247     QualType From
11248       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11249     Result.makeComplexInt();
11250     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11251                                 To, Result.IntReal) &&
11252            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11253                                 To, Result.IntImag);
11254   }
11255 
11256   case CK_IntegralRealToComplex: {
11257     APSInt &Real = Result.IntReal;
11258     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11259       return false;
11260 
11261     Result.makeComplexInt();
11262     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11263     return true;
11264   }
11265 
11266   case CK_IntegralComplexCast: {
11267     if (!Visit(E->getSubExpr()))
11268       return false;
11269 
11270     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11271     QualType From
11272       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11273 
11274     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11275     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11276     return true;
11277   }
11278 
11279   case CK_IntegralComplexToFloatingComplex: {
11280     if (!Visit(E->getSubExpr()))
11281       return false;
11282 
11283     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11284     QualType From
11285       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11286     Result.makeComplexFloat();
11287     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11288                                 To, Result.FloatReal) &&
11289            HandleIntToFloatCast(Info, E, From, Result.IntImag,
11290                                 To, Result.FloatImag);
11291   }
11292   }
11293 
11294   llvm_unreachable("unknown cast resulting in complex value");
11295 }
11296 
11297 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11298   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11299     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11300 
11301   // Track whether the LHS or RHS is real at the type system level. When this is
11302   // the case we can simplify our evaluation strategy.
11303   bool LHSReal = false, RHSReal = false;
11304 
11305   bool LHSOK;
11306   if (E->getLHS()->getType()->isRealFloatingType()) {
11307     LHSReal = true;
11308     APFloat &Real = Result.FloatReal;
11309     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11310     if (LHSOK) {
11311       Result.makeComplexFloat();
11312       Result.FloatImag = APFloat(Real.getSemantics());
11313     }
11314   } else {
11315     LHSOK = Visit(E->getLHS());
11316   }
11317   if (!LHSOK && !Info.noteFailure())
11318     return false;
11319 
11320   ComplexValue RHS;
11321   if (E->getRHS()->getType()->isRealFloatingType()) {
11322     RHSReal = true;
11323     APFloat &Real = RHS.FloatReal;
11324     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11325       return false;
11326     RHS.makeComplexFloat();
11327     RHS.FloatImag = APFloat(Real.getSemantics());
11328   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11329     return false;
11330 
11331   assert(!(LHSReal && RHSReal) &&
11332          "Cannot have both operands of a complex operation be real.");
11333   switch (E->getOpcode()) {
11334   default: return Error(E);
11335   case BO_Add:
11336     if (Result.isComplexFloat()) {
11337       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11338                                        APFloat::rmNearestTiesToEven);
11339       if (LHSReal)
11340         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11341       else if (!RHSReal)
11342         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11343                                          APFloat::rmNearestTiesToEven);
11344     } else {
11345       Result.getComplexIntReal() += RHS.getComplexIntReal();
11346       Result.getComplexIntImag() += RHS.getComplexIntImag();
11347     }
11348     break;
11349   case BO_Sub:
11350     if (Result.isComplexFloat()) {
11351       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11352                                             APFloat::rmNearestTiesToEven);
11353       if (LHSReal) {
11354         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11355         Result.getComplexFloatImag().changeSign();
11356       } else if (!RHSReal) {
11357         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11358                                               APFloat::rmNearestTiesToEven);
11359       }
11360     } else {
11361       Result.getComplexIntReal() -= RHS.getComplexIntReal();
11362       Result.getComplexIntImag() -= RHS.getComplexIntImag();
11363     }
11364     break;
11365   case BO_Mul:
11366     if (Result.isComplexFloat()) {
11367       // This is an implementation of complex multiplication according to the
11368       // constraints laid out in C11 Annex G. The implementation uses the
11369       // following naming scheme:
11370       //   (a + ib) * (c + id)
11371       ComplexValue LHS = Result;
11372       APFloat &A = LHS.getComplexFloatReal();
11373       APFloat &B = LHS.getComplexFloatImag();
11374       APFloat &C = RHS.getComplexFloatReal();
11375       APFloat &D = RHS.getComplexFloatImag();
11376       APFloat &ResR = Result.getComplexFloatReal();
11377       APFloat &ResI = Result.getComplexFloatImag();
11378       if (LHSReal) {
11379         assert(!RHSReal && "Cannot have two real operands for a complex op!");
11380         ResR = A * C;
11381         ResI = A * D;
11382       } else if (RHSReal) {
11383         ResR = C * A;
11384         ResI = C * B;
11385       } else {
11386         // In the fully general case, we need to handle NaNs and infinities
11387         // robustly.
11388         APFloat AC = A * C;
11389         APFloat BD = B * D;
11390         APFloat AD = A * D;
11391         APFloat BC = B * C;
11392         ResR = AC - BD;
11393         ResI = AD + BC;
11394         if (ResR.isNaN() && ResI.isNaN()) {
11395           bool Recalc = false;
11396           if (A.isInfinity() || B.isInfinity()) {
11397             A = APFloat::copySign(
11398                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11399             B = APFloat::copySign(
11400                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11401             if (C.isNaN())
11402               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11403             if (D.isNaN())
11404               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11405             Recalc = true;
11406           }
11407           if (C.isInfinity() || D.isInfinity()) {
11408             C = APFloat::copySign(
11409                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11410             D = APFloat::copySign(
11411                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11412             if (A.isNaN())
11413               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11414             if (B.isNaN())
11415               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11416             Recalc = true;
11417           }
11418           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11419                           AD.isInfinity() || BC.isInfinity())) {
11420             if (A.isNaN())
11421               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11422             if (B.isNaN())
11423               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11424             if (C.isNaN())
11425               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11426             if (D.isNaN())
11427               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11428             Recalc = true;
11429           }
11430           if (Recalc) {
11431             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11432             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11433           }
11434         }
11435       }
11436     } else {
11437       ComplexValue LHS = Result;
11438       Result.getComplexIntReal() =
11439         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11440          LHS.getComplexIntImag() * RHS.getComplexIntImag());
11441       Result.getComplexIntImag() =
11442         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11443          LHS.getComplexIntImag() * RHS.getComplexIntReal());
11444     }
11445     break;
11446   case BO_Div:
11447     if (Result.isComplexFloat()) {
11448       // This is an implementation of complex division according to the
11449       // constraints laid out in C11 Annex G. The implementation uses the
11450       // following naming scheme:
11451       //   (a + ib) / (c + id)
11452       ComplexValue LHS = Result;
11453       APFloat &A = LHS.getComplexFloatReal();
11454       APFloat &B = LHS.getComplexFloatImag();
11455       APFloat &C = RHS.getComplexFloatReal();
11456       APFloat &D = RHS.getComplexFloatImag();
11457       APFloat &ResR = Result.getComplexFloatReal();
11458       APFloat &ResI = Result.getComplexFloatImag();
11459       if (RHSReal) {
11460         ResR = A / C;
11461         ResI = B / C;
11462       } else {
11463         if (LHSReal) {
11464           // No real optimizations we can do here, stub out with zero.
11465           B = APFloat::getZero(A.getSemantics());
11466         }
11467         int DenomLogB = 0;
11468         APFloat MaxCD = maxnum(abs(C), abs(D));
11469         if (MaxCD.isFinite()) {
11470           DenomLogB = ilogb(MaxCD);
11471           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11472           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11473         }
11474         APFloat Denom = C * C + D * D;
11475         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11476                       APFloat::rmNearestTiesToEven);
11477         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11478                       APFloat::rmNearestTiesToEven);
11479         if (ResR.isNaN() && ResI.isNaN()) {
11480           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11481             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11482             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11483           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11484                      D.isFinite()) {
11485             A = APFloat::copySign(
11486                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11487             B = APFloat::copySign(
11488                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11489             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11490             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11491           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11492             C = APFloat::copySign(
11493                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11494             D = APFloat::copySign(
11495                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11496             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11497             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11498           }
11499         }
11500       }
11501     } else {
11502       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11503         return Error(E, diag::note_expr_divide_by_zero);
11504 
11505       ComplexValue LHS = Result;
11506       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11507         RHS.getComplexIntImag() * RHS.getComplexIntImag();
11508       Result.getComplexIntReal() =
11509         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11510          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11511       Result.getComplexIntImag() =
11512         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11513          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11514     }
11515     break;
11516   }
11517 
11518   return true;
11519 }
11520 
11521 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11522   // Get the operand value into 'Result'.
11523   if (!Visit(E->getSubExpr()))
11524     return false;
11525 
11526   switch (E->getOpcode()) {
11527   default:
11528     return Error(E);
11529   case UO_Extension:
11530     return true;
11531   case UO_Plus:
11532     // The result is always just the subexpr.
11533     return true;
11534   case UO_Minus:
11535     if (Result.isComplexFloat()) {
11536       Result.getComplexFloatReal().changeSign();
11537       Result.getComplexFloatImag().changeSign();
11538     }
11539     else {
11540       Result.getComplexIntReal() = -Result.getComplexIntReal();
11541       Result.getComplexIntImag() = -Result.getComplexIntImag();
11542     }
11543     return true;
11544   case UO_Not:
11545     if (Result.isComplexFloat())
11546       Result.getComplexFloatImag().changeSign();
11547     else
11548       Result.getComplexIntImag() = -Result.getComplexIntImag();
11549     return true;
11550   }
11551 }
11552 
11553 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11554   if (E->getNumInits() == 2) {
11555     if (E->getType()->isComplexType()) {
11556       Result.makeComplexFloat();
11557       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11558         return false;
11559       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11560         return false;
11561     } else {
11562       Result.makeComplexInt();
11563       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11564         return false;
11565       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11566         return false;
11567     }
11568     return true;
11569   }
11570   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11571 }
11572 
11573 //===----------------------------------------------------------------------===//
11574 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11575 // implicit conversion.
11576 //===----------------------------------------------------------------------===//
11577 
11578 namespace {
11579 class AtomicExprEvaluator :
11580     public ExprEvaluatorBase<AtomicExprEvaluator> {
11581   const LValue *This;
11582   APValue &Result;
11583 public:
11584   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11585       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11586 
11587   bool Success(const APValue &V, const Expr *E) {
11588     Result = V;
11589     return true;
11590   }
11591 
11592   bool ZeroInitialization(const Expr *E) {
11593     ImplicitValueInitExpr VIE(
11594         E->getType()->castAs<AtomicType>()->getValueType());
11595     // For atomic-qualified class (and array) types in C++, initialize the
11596     // _Atomic-wrapped subobject directly, in-place.
11597     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11598                 : Evaluate(Result, Info, &VIE);
11599   }
11600 
11601   bool VisitCastExpr(const CastExpr *E) {
11602     switch (E->getCastKind()) {
11603     default:
11604       return ExprEvaluatorBaseTy::VisitCastExpr(E);
11605     case CK_NonAtomicToAtomic:
11606       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11607                   : Evaluate(Result, Info, E->getSubExpr());
11608     }
11609   }
11610 };
11611 } // end anonymous namespace
11612 
11613 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11614                            EvalInfo &Info) {
11615   assert(E->isRValue() && E->getType()->isAtomicType());
11616   return AtomicExprEvaluator(Info, This, Result).Visit(E);
11617 }
11618 
11619 //===----------------------------------------------------------------------===//
11620 // Void expression evaluation, primarily for a cast to void on the LHS of a
11621 // comma operator
11622 //===----------------------------------------------------------------------===//
11623 
11624 namespace {
11625 class VoidExprEvaluator
11626   : public ExprEvaluatorBase<VoidExprEvaluator> {
11627 public:
11628   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11629 
11630   bool Success(const APValue &V, const Expr *e) { return true; }
11631 
11632   bool ZeroInitialization(const Expr *E) { return true; }
11633 
11634   bool VisitCastExpr(const CastExpr *E) {
11635     switch (E->getCastKind()) {
11636     default:
11637       return ExprEvaluatorBaseTy::VisitCastExpr(E);
11638     case CK_ToVoid:
11639       VisitIgnoredValue(E->getSubExpr());
11640       return true;
11641     }
11642   }
11643 
11644   bool VisitCallExpr(const CallExpr *E) {
11645     switch (E->getBuiltinCallee()) {
11646     default:
11647       return ExprEvaluatorBaseTy::VisitCallExpr(E);
11648     case Builtin::BI__assume:
11649     case Builtin::BI__builtin_assume:
11650       // The argument is not evaluated!
11651       return true;
11652     }
11653   }
11654 };
11655 } // end anonymous namespace
11656 
11657 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11658   assert(E->isRValue() && E->getType()->isVoidType());
11659   return VoidExprEvaluator(Info).Visit(E);
11660 }
11661 
11662 //===----------------------------------------------------------------------===//
11663 // Top level Expr::EvaluateAsRValue method.
11664 //===----------------------------------------------------------------------===//
11665 
11666 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
11667   // In C, function designators are not lvalues, but we evaluate them as if they
11668   // are.
11669   QualType T = E->getType();
11670   if (E->isGLValue() || T->isFunctionType()) {
11671     LValue LV;
11672     if (!EvaluateLValue(E, LV, Info))
11673       return false;
11674     LV.moveInto(Result);
11675   } else if (T->isVectorType()) {
11676     if (!EvaluateVector(E, Result, Info))
11677       return false;
11678   } else if (T->isIntegralOrEnumerationType()) {
11679     if (!IntExprEvaluator(Info, Result).Visit(E))
11680       return false;
11681   } else if (T->hasPointerRepresentation()) {
11682     LValue LV;
11683     if (!EvaluatePointer(E, LV, Info))
11684       return false;
11685     LV.moveInto(Result);
11686   } else if (T->isRealFloatingType()) {
11687     llvm::APFloat F(0.0);
11688     if (!EvaluateFloat(E, F, Info))
11689       return false;
11690     Result = APValue(F);
11691   } else if (T->isAnyComplexType()) {
11692     ComplexValue C;
11693     if (!EvaluateComplex(E, C, Info))
11694       return false;
11695     C.moveInto(Result);
11696   } else if (T->isFixedPointType()) {
11697     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
11698   } else if (T->isMemberPointerType()) {
11699     MemberPtr P;
11700     if (!EvaluateMemberPointer(E, P, Info))
11701       return false;
11702     P.moveInto(Result);
11703     return true;
11704   } else if (T->isArrayType()) {
11705     LValue LV;
11706     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11707     if (!EvaluateArray(E, LV, Value, Info))
11708       return false;
11709     Result = Value;
11710   } else if (T->isRecordType()) {
11711     LValue LV;
11712     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11713     if (!EvaluateRecord(E, LV, Value, Info))
11714       return false;
11715     Result = Value;
11716   } else if (T->isVoidType()) {
11717     if (!Info.getLangOpts().CPlusPlus11)
11718       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
11719         << E->getType();
11720     if (!EvaluateVoid(E, Info))
11721       return false;
11722   } else if (T->isAtomicType()) {
11723     QualType Unqual = T.getAtomicUnqualifiedType();
11724     if (Unqual->isArrayType() || Unqual->isRecordType()) {
11725       LValue LV;
11726       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11727       if (!EvaluateAtomic(E, &LV, Value, Info))
11728         return false;
11729     } else {
11730       if (!EvaluateAtomic(E, nullptr, Result, Info))
11731         return false;
11732     }
11733   } else if (Info.getLangOpts().CPlusPlus11) {
11734     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
11735     return false;
11736   } else {
11737     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11738     return false;
11739   }
11740 
11741   return true;
11742 }
11743 
11744 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11745 /// cases, the in-place evaluation is essential, since later initializers for
11746 /// an object can indirectly refer to subobjects which were initialized earlier.
11747 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
11748                             const Expr *E, bool AllowNonLiteralTypes) {
11749   assert(!E->isValueDependent());
11750 
11751   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
11752     return false;
11753 
11754   if (E->isRValue()) {
11755     // Evaluate arrays and record types in-place, so that later initializers can
11756     // refer to earlier-initialized members of the object.
11757     QualType T = E->getType();
11758     if (T->isArrayType())
11759       return EvaluateArray(E, This, Result, Info);
11760     else if (T->isRecordType())
11761       return EvaluateRecord(E, This, Result, Info);
11762     else if (T->isAtomicType()) {
11763       QualType Unqual = T.getAtomicUnqualifiedType();
11764       if (Unqual->isArrayType() || Unqual->isRecordType())
11765         return EvaluateAtomic(E, &This, Result, Info);
11766     }
11767   }
11768 
11769   // For any other type, in-place evaluation is unimportant.
11770   return Evaluate(Result, Info, E);
11771 }
11772 
11773 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11774 /// lvalue-to-rvalue cast if it is an lvalue.
11775 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
11776   if (E->getType().isNull())
11777     return false;
11778 
11779   if (!CheckLiteralType(Info, E))
11780     return false;
11781 
11782   if (!::Evaluate(Result, Info, E))
11783     return false;
11784 
11785   if (E->isGLValue()) {
11786     LValue LV;
11787     LV.setFrom(Info.Ctx, Result);
11788     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11789       return false;
11790   }
11791 
11792   // Check this core constant expression is a constant expression.
11793   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11794 }
11795 
11796 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
11797                                  const ASTContext &Ctx, bool &IsConst) {
11798   // Fast-path evaluations of integer literals, since we sometimes see files
11799   // containing vast quantities of these.
11800   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11801     Result.Val = APValue(APSInt(L->getValue(),
11802                                 L->getType()->isUnsignedIntegerType()));
11803     IsConst = true;
11804     return true;
11805   }
11806 
11807   // This case should be rare, but we need to check it before we check on
11808   // the type below.
11809   if (Exp->getType().isNull()) {
11810     IsConst = false;
11811     return true;
11812   }
11813 
11814   // FIXME: Evaluating values of large array and record types can cause
11815   // performance problems. Only do so in C++11 for now.
11816   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11817                           Exp->getType()->isRecordType()) &&
11818       !Ctx.getLangOpts().CPlusPlus11) {
11819     IsConst = false;
11820     return true;
11821   }
11822   return false;
11823 }
11824 
11825 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11826                                       Expr::SideEffectsKind SEK) {
11827   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11828          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11829 }
11830 
11831 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11832                              const ASTContext &Ctx, EvalInfo &Info) {
11833   bool IsConst;
11834   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11835     return IsConst;
11836 
11837   return EvaluateAsRValue(Info, E, Result.Val);
11838 }
11839 
11840 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11841                           const ASTContext &Ctx,
11842                           Expr::SideEffectsKind AllowSideEffects,
11843                           EvalInfo &Info) {
11844   if (!E->getType()->isIntegralOrEnumerationType())
11845     return false;
11846 
11847   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11848       !ExprResult.Val.isInt() ||
11849       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11850     return false;
11851 
11852   return true;
11853 }
11854 
11855 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11856                                  const ASTContext &Ctx,
11857                                  Expr::SideEffectsKind AllowSideEffects,
11858                                  EvalInfo &Info) {
11859   if (!E->getType()->isFixedPointType())
11860     return false;
11861 
11862   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11863     return false;
11864 
11865   if (!ExprResult.Val.isFixedPoint() ||
11866       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11867     return false;
11868 
11869   return true;
11870 }
11871 
11872 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
11873 /// any crazy technique (that has nothing to do with language standards) that
11874 /// we want to.  If this function returns true, it returns the folded constant
11875 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11876 /// will be applied to the result.
11877 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11878                             bool InConstantContext) const {
11879   assert(!isValueDependent() &&
11880          "Expression evaluator can't be called on a dependent expression.");
11881   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11882   Info.InConstantContext = InConstantContext;
11883   return ::EvaluateAsRValue(this, Result, Ctx, Info);
11884 }
11885 
11886 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
11887                                       bool InConstantContext) const {
11888   assert(!isValueDependent() &&
11889          "Expression evaluator can't be called on a dependent expression.");
11890   EvalResult Scratch;
11891   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
11892          HandleConversionToBool(Scratch.Val, Result);
11893 }
11894 
11895 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
11896                          SideEffectsKind AllowSideEffects,
11897                          bool InConstantContext) const {
11898   assert(!isValueDependent() &&
11899          "Expression evaluator can't be called on a dependent expression.");
11900   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11901   Info.InConstantContext = InConstantContext;
11902   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
11903 }
11904 
11905 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11906                                 SideEffectsKind AllowSideEffects,
11907                                 bool InConstantContext) const {
11908   assert(!isValueDependent() &&
11909          "Expression evaluator can't be called on a dependent expression.");
11910   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11911   Info.InConstantContext = InConstantContext;
11912   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11913 }
11914 
11915 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11916                            SideEffectsKind AllowSideEffects,
11917                            bool InConstantContext) const {
11918   assert(!isValueDependent() &&
11919          "Expression evaluator can't be called on a dependent expression.");
11920 
11921   if (!getType()->isRealFloatingType())
11922     return false;
11923 
11924   EvalResult ExprResult;
11925   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
11926       !ExprResult.Val.isFloat() ||
11927       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11928     return false;
11929 
11930   Result = ExprResult.Val.getFloat();
11931   return true;
11932 }
11933 
11934 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
11935                             bool InConstantContext) const {
11936   assert(!isValueDependent() &&
11937          "Expression evaluator can't be called on a dependent expression.");
11938 
11939   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
11940   Info.InConstantContext = InConstantContext;
11941   LValue LV;
11942   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11943       !CheckLValueConstantExpression(Info, getExprLoc(),
11944                                      Ctx.getLValueReferenceType(getType()), LV,
11945                                      Expr::EvaluateForCodeGen))
11946     return false;
11947 
11948   LV.moveInto(Result.Val);
11949   return true;
11950 }
11951 
11952 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11953                                   const ASTContext &Ctx) const {
11954   assert(!isValueDependent() &&
11955          "Expression evaluator can't be called on a dependent expression.");
11956 
11957   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11958   EvalInfo Info(Ctx, Result, EM);
11959   Info.InConstantContext = true;
11960 
11961   if (!::Evaluate(Result.Val, Info, this))
11962     return false;
11963 
11964   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11965                                  Usage);
11966 }
11967 
11968 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11969                                  const VarDecl *VD,
11970                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
11971   assert(!isValueDependent() &&
11972          "Expression evaluator can't be called on a dependent expression.");
11973 
11974   // FIXME: Evaluating initializers for large array and record types can cause
11975   // performance problems. Only do so in C++11 for now.
11976   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
11977       !Ctx.getLangOpts().CPlusPlus11)
11978     return false;
11979 
11980   Expr::EvalStatus EStatus;
11981   EStatus.Diag = &Notes;
11982 
11983   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11984                                       ? EvalInfo::EM_ConstantExpression
11985                                       : EvalInfo::EM_ConstantFold);
11986   InitInfo.setEvaluatingDecl(VD, Value);
11987   InitInfo.InConstantContext = true;
11988 
11989   LValue LVal;
11990   LVal.set(VD);
11991 
11992   // C++11 [basic.start.init]p2:
11993   //  Variables with static storage duration or thread storage duration shall be
11994   //  zero-initialized before any other initialization takes place.
11995   // This behavior is not present in C.
11996   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
11997       !VD->getType()->isReferenceType()) {
11998     ImplicitValueInitExpr VIE(VD->getType());
11999     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12000                          /*AllowNonLiteralTypes=*/true))
12001       return false;
12002   }
12003 
12004   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12005                        /*AllowNonLiteralTypes=*/true) ||
12006       EStatus.HasSideEffects)
12007     return false;
12008 
12009   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12010                                  Value);
12011 }
12012 
12013 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12014 /// constant folded, but discard the result.
12015 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12016   assert(!isValueDependent() &&
12017          "Expression evaluator can't be called on a dependent expression.");
12018 
12019   EvalResult Result;
12020   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12021          !hasUnacceptableSideEffect(Result, SEK);
12022 }
12023 
12024 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12025                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12026   assert(!isValueDependent() &&
12027          "Expression evaluator can't be called on a dependent expression.");
12028 
12029   EvalResult EVResult;
12030   EVResult.Diag = Diag;
12031   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12032   Info.InConstantContext = true;
12033 
12034   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12035   (void)Result;
12036   assert(Result && "Could not evaluate expression");
12037   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12038 
12039   return EVResult.Val.getInt();
12040 }
12041 
12042 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12043     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12044   assert(!isValueDependent() &&
12045          "Expression evaluator can't be called on a dependent expression.");
12046 
12047   EvalResult EVResult;
12048   EVResult.Diag = Diag;
12049   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12050   Info.InConstantContext = true;
12051 
12052   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12053   (void)Result;
12054   assert(Result && "Could not evaluate expression");
12055   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12056 
12057   return EVResult.Val.getInt();
12058 }
12059 
12060 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12061   assert(!isValueDependent() &&
12062          "Expression evaluator can't be called on a dependent expression.");
12063 
12064   bool IsConst;
12065   EvalResult EVResult;
12066   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12067     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12068     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12069   }
12070 }
12071 
12072 bool Expr::EvalResult::isGlobalLValue() const {
12073   assert(Val.isLValue());
12074   return IsGlobalLValue(Val.getLValueBase());
12075 }
12076 
12077 
12078 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12079 /// an integer constant expression.
12080 
12081 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12082 /// comma, etc
12083 
12084 // CheckICE - This function does the fundamental ICE checking: the returned
12085 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12086 // and a (possibly null) SourceLocation indicating the location of the problem.
12087 //
12088 // Note that to reduce code duplication, this helper does no evaluation
12089 // itself; the caller checks whether the expression is evaluatable, and
12090 // in the rare cases where CheckICE actually cares about the evaluated
12091 // value, it calls into Evaluate.
12092 
12093 namespace {
12094 
12095 enum ICEKind {
12096   /// This expression is an ICE.
12097   IK_ICE,
12098   /// This expression is not an ICE, but if it isn't evaluated, it's
12099   /// a legal subexpression for an ICE. This return value is used to handle
12100   /// the comma operator in C99 mode, and non-constant subexpressions.
12101   IK_ICEIfUnevaluated,
12102   /// This expression is not an ICE, and is not a legal subexpression for one.
12103   IK_NotICE
12104 };
12105 
12106 struct ICEDiag {
12107   ICEKind Kind;
12108   SourceLocation Loc;
12109 
12110   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12111 };
12112 
12113 }
12114 
12115 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12116 
12117 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12118 
12119 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12120   Expr::EvalResult EVResult;
12121   Expr::EvalStatus Status;
12122   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12123 
12124   Info.InConstantContext = true;
12125   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12126       !EVResult.Val.isInt())
12127     return ICEDiag(IK_NotICE, E->getBeginLoc());
12128 
12129   return NoDiag();
12130 }
12131 
12132 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12133   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12134   if (!E->getType()->isIntegralOrEnumerationType())
12135     return ICEDiag(IK_NotICE, E->getBeginLoc());
12136 
12137   switch (E->getStmtClass()) {
12138 #define ABSTRACT_STMT(Node)
12139 #define STMT(Node, Base) case Expr::Node##Class:
12140 #define EXPR(Node, Base)
12141 #include "clang/AST/StmtNodes.inc"
12142   case Expr::PredefinedExprClass:
12143   case Expr::FloatingLiteralClass:
12144   case Expr::ImaginaryLiteralClass:
12145   case Expr::StringLiteralClass:
12146   case Expr::ArraySubscriptExprClass:
12147   case Expr::OMPArraySectionExprClass:
12148   case Expr::MemberExprClass:
12149   case Expr::CompoundAssignOperatorClass:
12150   case Expr::CompoundLiteralExprClass:
12151   case Expr::ExtVectorElementExprClass:
12152   case Expr::DesignatedInitExprClass:
12153   case Expr::ArrayInitLoopExprClass:
12154   case Expr::ArrayInitIndexExprClass:
12155   case Expr::NoInitExprClass:
12156   case Expr::DesignatedInitUpdateExprClass:
12157   case Expr::ImplicitValueInitExprClass:
12158   case Expr::ParenListExprClass:
12159   case Expr::VAArgExprClass:
12160   case Expr::AddrLabelExprClass:
12161   case Expr::StmtExprClass:
12162   case Expr::CXXMemberCallExprClass:
12163   case Expr::CUDAKernelCallExprClass:
12164   case Expr::CXXDynamicCastExprClass:
12165   case Expr::CXXTypeidExprClass:
12166   case Expr::CXXUuidofExprClass:
12167   case Expr::MSPropertyRefExprClass:
12168   case Expr::MSPropertySubscriptExprClass:
12169   case Expr::CXXNullPtrLiteralExprClass:
12170   case Expr::UserDefinedLiteralClass:
12171   case Expr::CXXThisExprClass:
12172   case Expr::CXXThrowExprClass:
12173   case Expr::CXXNewExprClass:
12174   case Expr::CXXDeleteExprClass:
12175   case Expr::CXXPseudoDestructorExprClass:
12176   case Expr::UnresolvedLookupExprClass:
12177   case Expr::TypoExprClass:
12178   case Expr::DependentScopeDeclRefExprClass:
12179   case Expr::CXXConstructExprClass:
12180   case Expr::CXXInheritedCtorInitExprClass:
12181   case Expr::CXXStdInitializerListExprClass:
12182   case Expr::CXXBindTemporaryExprClass:
12183   case Expr::ExprWithCleanupsClass:
12184   case Expr::CXXTemporaryObjectExprClass:
12185   case Expr::CXXUnresolvedConstructExprClass:
12186   case Expr::CXXDependentScopeMemberExprClass:
12187   case Expr::UnresolvedMemberExprClass:
12188   case Expr::ObjCStringLiteralClass:
12189   case Expr::ObjCBoxedExprClass:
12190   case Expr::ObjCArrayLiteralClass:
12191   case Expr::ObjCDictionaryLiteralClass:
12192   case Expr::ObjCEncodeExprClass:
12193   case Expr::ObjCMessageExprClass:
12194   case Expr::ObjCSelectorExprClass:
12195   case Expr::ObjCProtocolExprClass:
12196   case Expr::ObjCIvarRefExprClass:
12197   case Expr::ObjCPropertyRefExprClass:
12198   case Expr::ObjCSubscriptRefExprClass:
12199   case Expr::ObjCIsaExprClass:
12200   case Expr::ObjCAvailabilityCheckExprClass:
12201   case Expr::ShuffleVectorExprClass:
12202   case Expr::ConvertVectorExprClass:
12203   case Expr::BlockExprClass:
12204   case Expr::NoStmtClass:
12205   case Expr::OpaqueValueExprClass:
12206   case Expr::PackExpansionExprClass:
12207   case Expr::SubstNonTypeTemplateParmPackExprClass:
12208   case Expr::FunctionParmPackExprClass:
12209   case Expr::AsTypeExprClass:
12210   case Expr::ObjCIndirectCopyRestoreExprClass:
12211   case Expr::MaterializeTemporaryExprClass:
12212   case Expr::PseudoObjectExprClass:
12213   case Expr::AtomicExprClass:
12214   case Expr::LambdaExprClass:
12215   case Expr::CXXFoldExprClass:
12216   case Expr::CoawaitExprClass:
12217   case Expr::DependentCoawaitExprClass:
12218   case Expr::CoyieldExprClass:
12219     return ICEDiag(IK_NotICE, E->getBeginLoc());
12220 
12221   case Expr::InitListExprClass: {
12222     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12223     // form "T x = { a };" is equivalent to "T x = a;".
12224     // Unless we're initializing a reference, T is a scalar as it is known to be
12225     // of integral or enumeration type.
12226     if (E->isRValue())
12227       if (cast<InitListExpr>(E)->getNumInits() == 1)
12228         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12229     return ICEDiag(IK_NotICE, E->getBeginLoc());
12230   }
12231 
12232   case Expr::SizeOfPackExprClass:
12233   case Expr::GNUNullExprClass:
12234   case Expr::SourceLocExprClass:
12235     return NoDiag();
12236 
12237   case Expr::SubstNonTypeTemplateParmExprClass:
12238     return
12239       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12240 
12241   case Expr::ConstantExprClass:
12242     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12243 
12244   case Expr::ParenExprClass:
12245     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12246   case Expr::GenericSelectionExprClass:
12247     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12248   case Expr::IntegerLiteralClass:
12249   case Expr::FixedPointLiteralClass:
12250   case Expr::CharacterLiteralClass:
12251   case Expr::ObjCBoolLiteralExprClass:
12252   case Expr::CXXBoolLiteralExprClass:
12253   case Expr::CXXScalarValueInitExprClass:
12254   case Expr::TypeTraitExprClass:
12255   case Expr::ArrayTypeTraitExprClass:
12256   case Expr::ExpressionTraitExprClass:
12257   case Expr::CXXNoexceptExprClass:
12258     return NoDiag();
12259   case Expr::CallExprClass:
12260   case Expr::CXXOperatorCallExprClass: {
12261     // C99 6.6/3 allows function calls within unevaluated subexpressions of
12262     // constant expressions, but they can never be ICEs because an ICE cannot
12263     // contain an operand of (pointer to) function type.
12264     const CallExpr *CE = cast<CallExpr>(E);
12265     if (CE->getBuiltinCallee())
12266       return CheckEvalInICE(E, Ctx);
12267     return ICEDiag(IK_NotICE, E->getBeginLoc());
12268   }
12269   case Expr::DeclRefExprClass: {
12270     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12271       return NoDiag();
12272     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12273     if (Ctx.getLangOpts().CPlusPlus &&
12274         D && IsConstNonVolatile(D->getType())) {
12275       // Parameter variables are never constants.  Without this check,
12276       // getAnyInitializer() can find a default argument, which leads
12277       // to chaos.
12278       if (isa<ParmVarDecl>(D))
12279         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12280 
12281       // C++ 7.1.5.1p2
12282       //   A variable of non-volatile const-qualified integral or enumeration
12283       //   type initialized by an ICE can be used in ICEs.
12284       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12285         if (!Dcl->getType()->isIntegralOrEnumerationType())
12286           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12287 
12288         const VarDecl *VD;
12289         // Look for a declaration of this variable that has an initializer, and
12290         // check whether it is an ICE.
12291         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12292           return NoDiag();
12293         else
12294           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12295       }
12296     }
12297     return ICEDiag(IK_NotICE, E->getBeginLoc());
12298   }
12299   case Expr::UnaryOperatorClass: {
12300     const UnaryOperator *Exp = cast<UnaryOperator>(E);
12301     switch (Exp->getOpcode()) {
12302     case UO_PostInc:
12303     case UO_PostDec:
12304     case UO_PreInc:
12305     case UO_PreDec:
12306     case UO_AddrOf:
12307     case UO_Deref:
12308     case UO_Coawait:
12309       // C99 6.6/3 allows increment and decrement within unevaluated
12310       // subexpressions of constant expressions, but they can never be ICEs
12311       // because an ICE cannot contain an lvalue operand.
12312       return ICEDiag(IK_NotICE, E->getBeginLoc());
12313     case UO_Extension:
12314     case UO_LNot:
12315     case UO_Plus:
12316     case UO_Minus:
12317     case UO_Not:
12318     case UO_Real:
12319     case UO_Imag:
12320       return CheckICE(Exp->getSubExpr(), Ctx);
12321     }
12322     llvm_unreachable("invalid unary operator class");
12323   }
12324   case Expr::OffsetOfExprClass: {
12325     // Note that per C99, offsetof must be an ICE. And AFAIK, using
12326     // EvaluateAsRValue matches the proposed gcc behavior for cases like
12327     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
12328     // compliance: we should warn earlier for offsetof expressions with
12329     // array subscripts that aren't ICEs, and if the array subscripts
12330     // are ICEs, the value of the offsetof must be an integer constant.
12331     return CheckEvalInICE(E, Ctx);
12332   }
12333   case Expr::UnaryExprOrTypeTraitExprClass: {
12334     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12335     if ((Exp->getKind() ==  UETT_SizeOf) &&
12336         Exp->getTypeOfArgument()->isVariableArrayType())
12337       return ICEDiag(IK_NotICE, E->getBeginLoc());
12338     return NoDiag();
12339   }
12340   case Expr::BinaryOperatorClass: {
12341     const BinaryOperator *Exp = cast<BinaryOperator>(E);
12342     switch (Exp->getOpcode()) {
12343     case BO_PtrMemD:
12344     case BO_PtrMemI:
12345     case BO_Assign:
12346     case BO_MulAssign:
12347     case BO_DivAssign:
12348     case BO_RemAssign:
12349     case BO_AddAssign:
12350     case BO_SubAssign:
12351     case BO_ShlAssign:
12352     case BO_ShrAssign:
12353     case BO_AndAssign:
12354     case BO_XorAssign:
12355     case BO_OrAssign:
12356       // C99 6.6/3 allows assignments within unevaluated subexpressions of
12357       // constant expressions, but they can never be ICEs because an ICE cannot
12358       // contain an lvalue operand.
12359       return ICEDiag(IK_NotICE, E->getBeginLoc());
12360 
12361     case BO_Mul:
12362     case BO_Div:
12363     case BO_Rem:
12364     case BO_Add:
12365     case BO_Sub:
12366     case BO_Shl:
12367     case BO_Shr:
12368     case BO_LT:
12369     case BO_GT:
12370     case BO_LE:
12371     case BO_GE:
12372     case BO_EQ:
12373     case BO_NE:
12374     case BO_And:
12375     case BO_Xor:
12376     case BO_Or:
12377     case BO_Comma:
12378     case BO_Cmp: {
12379       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12380       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12381       if (Exp->getOpcode() == BO_Div ||
12382           Exp->getOpcode() == BO_Rem) {
12383         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12384         // we don't evaluate one.
12385         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12386           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12387           if (REval == 0)
12388             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12389           if (REval.isSigned() && REval.isAllOnesValue()) {
12390             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12391             if (LEval.isMinSignedValue())
12392               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12393           }
12394         }
12395       }
12396       if (Exp->getOpcode() == BO_Comma) {
12397         if (Ctx.getLangOpts().C99) {
12398           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12399           // if it isn't evaluated.
12400           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12401             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12402         } else {
12403           // In both C89 and C++, commas in ICEs are illegal.
12404           return ICEDiag(IK_NotICE, E->getBeginLoc());
12405         }
12406       }
12407       return Worst(LHSResult, RHSResult);
12408     }
12409     case BO_LAnd:
12410     case BO_LOr: {
12411       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12412       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12413       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12414         // Rare case where the RHS has a comma "side-effect"; we need
12415         // to actually check the condition to see whether the side
12416         // with the comma is evaluated.
12417         if ((Exp->getOpcode() == BO_LAnd) !=
12418             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12419           return RHSResult;
12420         return NoDiag();
12421       }
12422 
12423       return Worst(LHSResult, RHSResult);
12424     }
12425     }
12426     llvm_unreachable("invalid binary operator kind");
12427   }
12428   case Expr::ImplicitCastExprClass:
12429   case Expr::CStyleCastExprClass:
12430   case Expr::CXXFunctionalCastExprClass:
12431   case Expr::CXXStaticCastExprClass:
12432   case Expr::CXXReinterpretCastExprClass:
12433   case Expr::CXXConstCastExprClass:
12434   case Expr::ObjCBridgedCastExprClass: {
12435     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12436     if (isa<ExplicitCastExpr>(E)) {
12437       if (const FloatingLiteral *FL
12438             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12439         unsigned DestWidth = Ctx.getIntWidth(E->getType());
12440         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12441         APSInt IgnoredVal(DestWidth, !DestSigned);
12442         bool Ignored;
12443         // If the value does not fit in the destination type, the behavior is
12444         // undefined, so we are not required to treat it as a constant
12445         // expression.
12446         if (FL->getValue().convertToInteger(IgnoredVal,
12447                                             llvm::APFloat::rmTowardZero,
12448                                             &Ignored) & APFloat::opInvalidOp)
12449           return ICEDiag(IK_NotICE, E->getBeginLoc());
12450         return NoDiag();
12451       }
12452     }
12453     switch (cast<CastExpr>(E)->getCastKind()) {
12454     case CK_LValueToRValue:
12455     case CK_AtomicToNonAtomic:
12456     case CK_NonAtomicToAtomic:
12457     case CK_NoOp:
12458     case CK_IntegralToBoolean:
12459     case CK_IntegralCast:
12460       return CheckICE(SubExpr, Ctx);
12461     default:
12462       return ICEDiag(IK_NotICE, E->getBeginLoc());
12463     }
12464   }
12465   case Expr::BinaryConditionalOperatorClass: {
12466     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12467     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12468     if (CommonResult.Kind == IK_NotICE) return CommonResult;
12469     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12470     if (FalseResult.Kind == IK_NotICE) return FalseResult;
12471     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12472     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12473         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12474     return FalseResult;
12475   }
12476   case Expr::ConditionalOperatorClass: {
12477     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12478     // If the condition (ignoring parens) is a __builtin_constant_p call,
12479     // then only the true side is actually considered in an integer constant
12480     // expression, and it is fully evaluated.  This is an important GNU
12481     // extension.  See GCC PR38377 for discussion.
12482     if (const CallExpr *CallCE
12483         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12484       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12485         return CheckEvalInICE(E, Ctx);
12486     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12487     if (CondResult.Kind == IK_NotICE)
12488       return CondResult;
12489 
12490     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12491     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12492 
12493     if (TrueResult.Kind == IK_NotICE)
12494       return TrueResult;
12495     if (FalseResult.Kind == IK_NotICE)
12496       return FalseResult;
12497     if (CondResult.Kind == IK_ICEIfUnevaluated)
12498       return CondResult;
12499     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12500       return NoDiag();
12501     // Rare case where the diagnostics depend on which side is evaluated
12502     // Note that if we get here, CondResult is 0, and at least one of
12503     // TrueResult and FalseResult is non-zero.
12504     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12505       return FalseResult;
12506     return TrueResult;
12507   }
12508   case Expr::CXXDefaultArgExprClass:
12509     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12510   case Expr::CXXDefaultInitExprClass:
12511     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12512   case Expr::ChooseExprClass: {
12513     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12514   }
12515   }
12516 
12517   llvm_unreachable("Invalid StmtClass!");
12518 }
12519 
12520 /// Evaluate an expression as a C++11 integral constant expression.
12521 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
12522                                                     const Expr *E,
12523                                                     llvm::APSInt *Value,
12524                                                     SourceLocation *Loc) {
12525   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12526     if (Loc) *Loc = E->getExprLoc();
12527     return false;
12528   }
12529 
12530   APValue Result;
12531   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
12532     return false;
12533 
12534   if (!Result.isInt()) {
12535     if (Loc) *Loc = E->getExprLoc();
12536     return false;
12537   }
12538 
12539   if (Value) *Value = Result.getInt();
12540   return true;
12541 }
12542 
12543 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12544                                  SourceLocation *Loc) const {
12545   assert(!isValueDependent() &&
12546          "Expression evaluator can't be called on a dependent expression.");
12547 
12548   if (Ctx.getLangOpts().CPlusPlus11)
12549     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
12550 
12551   ICEDiag D = CheckICE(this, Ctx);
12552   if (D.Kind != IK_ICE) {
12553     if (Loc) *Loc = D.Loc;
12554     return false;
12555   }
12556   return true;
12557 }
12558 
12559 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
12560                                  SourceLocation *Loc, bool isEvaluated) const {
12561   assert(!isValueDependent() &&
12562          "Expression evaluator can't be called on a dependent expression.");
12563 
12564   if (Ctx.getLangOpts().CPlusPlus11)
12565     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12566 
12567   if (!isIntegerConstantExpr(Ctx, Loc))
12568     return false;
12569 
12570   // The only possible side-effects here are due to UB discovered in the
12571   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12572   // required to treat the expression as an ICE, so we produce the folded
12573   // value.
12574   EvalResult ExprResult;
12575   Expr::EvalStatus Status;
12576   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12577   Info.InConstantContext = true;
12578 
12579   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
12580     llvm_unreachable("ICE cannot be evaluated!");
12581 
12582   Value = ExprResult.Val.getInt();
12583   return true;
12584 }
12585 
12586 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
12587   assert(!isValueDependent() &&
12588          "Expression evaluator can't be called on a dependent expression.");
12589 
12590   return CheckICE(this, Ctx).Kind == IK_ICE;
12591 }
12592 
12593 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
12594                                SourceLocation *Loc) const {
12595   assert(!isValueDependent() &&
12596          "Expression evaluator can't be called on a dependent expression.");
12597 
12598   // We support this checking in C++98 mode in order to diagnose compatibility
12599   // issues.
12600   assert(Ctx.getLangOpts().CPlusPlus);
12601 
12602   // Build evaluation settings.
12603   Expr::EvalStatus Status;
12604   SmallVector<PartialDiagnosticAt, 8> Diags;
12605   Status.Diag = &Diags;
12606   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12607 
12608   APValue Scratch;
12609   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12610 
12611   if (!Diags.empty()) {
12612     IsConstExpr = false;
12613     if (Loc) *Loc = Diags[0].first;
12614   } else if (!IsConstExpr) {
12615     // FIXME: This shouldn't happen.
12616     if (Loc) *Loc = getExprLoc();
12617   }
12618 
12619   return IsConstExpr;
12620 }
12621 
12622 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12623                                     const FunctionDecl *Callee,
12624                                     ArrayRef<const Expr*> Args,
12625                                     const Expr *This) const {
12626   assert(!isValueDependent() &&
12627          "Expression evaluator can't be called on a dependent expression.");
12628 
12629   Expr::EvalStatus Status;
12630   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
12631   Info.InConstantContext = true;
12632 
12633   LValue ThisVal;
12634   const LValue *ThisPtr = nullptr;
12635   if (This) {
12636 #ifndef NDEBUG
12637     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12638     assert(MD && "Don't provide `this` for non-methods.");
12639     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12640 #endif
12641     if (EvaluateObjectArgument(Info, This, ThisVal))
12642       ThisPtr = &ThisVal;
12643     if (Info.EvalStatus.HasSideEffects)
12644       return false;
12645   }
12646 
12647   ArgVector ArgValues(Args.size());
12648   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12649        I != E; ++I) {
12650     if ((*I)->isValueDependent() ||
12651         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
12652       // If evaluation fails, throw away the argument entirely.
12653       ArgValues[I - Args.begin()] = APValue();
12654     if (Info.EvalStatus.HasSideEffects)
12655       return false;
12656   }
12657 
12658   // Build fake call to Callee.
12659   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
12660                        ArgValues.data());
12661   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12662 }
12663 
12664 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
12665                                    SmallVectorImpl<
12666                                      PartialDiagnosticAt> &Diags) {
12667   // FIXME: It would be useful to check constexpr function templates, but at the
12668   // moment the constant expression evaluator cannot cope with the non-rigorous
12669   // ASTs which we build for dependent expressions.
12670   if (FD->isDependentContext())
12671     return true;
12672 
12673   Expr::EvalStatus Status;
12674   Status.Diag = &Diags;
12675 
12676   EvalInfo Info(FD->getASTContext(), Status,
12677                 EvalInfo::EM_PotentialConstantExpression);
12678   Info.InConstantContext = true;
12679 
12680   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
12681   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
12682 
12683   // Fabricate an arbitrary expression on the stack and pretend that it
12684   // is a temporary being used as the 'this' pointer.
12685   LValue This;
12686   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
12687   This.set({&VIE, Info.CurrentCall->Index});
12688 
12689   ArrayRef<const Expr*> Args;
12690 
12691   APValue Scratch;
12692   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12693     // Evaluate the call as a constant initializer, to allow the construction
12694     // of objects of non-literal types.
12695     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
12696     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12697   } else {
12698     SourceLocation Loc = FD->getLocation();
12699     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
12700                        Args, FD->getBody(), Info, Scratch, nullptr);
12701   }
12702 
12703   return Diags.empty();
12704 }
12705 
12706 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12707                                               const FunctionDecl *FD,
12708                                               SmallVectorImpl<
12709                                                 PartialDiagnosticAt> &Diags) {
12710   assert(!E->isValueDependent() &&
12711          "Expression evaluator can't be called on a dependent expression.");
12712 
12713   Expr::EvalStatus Status;
12714   Status.Diag = &Diags;
12715 
12716   EvalInfo Info(FD->getASTContext(), Status,
12717                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
12718   Info.InConstantContext = true;
12719 
12720   // Fabricate a call stack frame to give the arguments a plausible cover story.
12721   ArrayRef<const Expr*> Args;
12722   ArgVector ArgValues(0);
12723   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
12724   (void)Success;
12725   assert(Success &&
12726          "Failed to set up arguments for potential constant evaluation");
12727   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
12728 
12729   APValue ResultScratch;
12730   Evaluate(ResultScratch, Info, E);
12731   return Diags.empty();
12732 }
12733 
12734 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12735                                  unsigned Type) const {
12736   if (!getType()->isPointerType())
12737     return false;
12738 
12739   Expr::EvalStatus Status;
12740   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
12741   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
12742 }
12743