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 "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     ASTContext &getCtx() const override { return Ctx; }
987 
988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1982   }
1983 
1984   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1985     return true;
1986 
1987   const Expr *E = B.get<const Expr*>();
1988   switch (E->getStmtClass()) {
1989   default:
1990     return false;
1991   case Expr::CompoundLiteralExprClass: {
1992     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1993     return CLE->isFileScope() && CLE->isLValue();
1994   }
1995   case Expr::MaterializeTemporaryExprClass:
1996     // A materialized temporary might have been lifetime-extended to static
1997     // storage duration.
1998     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1999   // A string literal has static storage duration.
2000   case Expr::StringLiteralClass:
2001   case Expr::PredefinedExprClass:
2002   case Expr::ObjCStringLiteralClass:
2003   case Expr::ObjCEncodeExprClass:
2004     return true;
2005   case Expr::ObjCBoxedExprClass:
2006     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2007   case Expr::CallExprClass:
2008     return IsConstantCall(cast<CallExpr>(E));
2009   // For GCC compatibility, &&label has static storage duration.
2010   case Expr::AddrLabelExprClass:
2011     return true;
2012   // A Block literal expression may be used as the initialization value for
2013   // Block variables at global or local static scope.
2014   case Expr::BlockExprClass:
2015     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2016   case Expr::ImplicitValueInitExprClass:
2017     // FIXME:
2018     // We can never form an lvalue with an implicit value initialization as its
2019     // base through expression evaluation, so these only appear in one case: the
2020     // implicit variable declaration we invent when checking whether a constexpr
2021     // constructor can produce a constant expression. We must assume that such
2022     // an expression might be a global lvalue.
2023     return true;
2024   }
2025 }
2026 
2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028   return LVal.Base.dyn_cast<const ValueDecl*>();
2029 }
2030 
2031 static bool IsLiteralLValue(const LValue &Value) {
2032   if (Value.getLValueCallIndex())
2033     return false;
2034   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2035   return E && !isa<MaterializeTemporaryExpr>(E);
2036 }
2037 
2038 static bool IsWeakLValue(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   return Decl && Decl->isWeak();
2041 }
2042 
2043 static bool isZeroSized(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   if (Decl && isa<VarDecl>(Decl)) {
2046     QualType Ty = Decl->getType();
2047     if (Ty->isArrayType())
2048       return Ty->isIncompleteType() ||
2049              Decl->getASTContext().getTypeSize(Ty) == 0;
2050   }
2051   return false;
2052 }
2053 
2054 static bool HasSameBase(const LValue &A, const LValue &B) {
2055   if (!A.getLValueBase())
2056     return !B.getLValueBase();
2057   if (!B.getLValueBase())
2058     return false;
2059 
2060   if (A.getLValueBase().getOpaqueValue() !=
2061       B.getLValueBase().getOpaqueValue())
2062     return false;
2063 
2064   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2065          A.getLValueVersion() == B.getLValueVersion();
2066 }
2067 
2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2069   assert(Base && "no location for a null lvalue");
2070   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2071 
2072   // For a parameter, find the corresponding call stack frame (if it still
2073   // exists), and point at the parameter of the function definition we actually
2074   // invoked.
2075   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2076     unsigned Idx = PVD->getFunctionScopeIndex();
2077     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2078       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2079           F->Arguments.Version == Base.getVersion() && F->Callee &&
2080           Idx < F->Callee->getNumParams()) {
2081         VD = F->Callee->getParamDecl(Idx);
2082         break;
2083       }
2084     }
2085   }
2086 
2087   if (VD)
2088     Info.Note(VD->getLocation(), diag::note_declared_at);
2089   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2090     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2091   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2092     // FIXME: Produce a note for dangling pointers too.
2093     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2094       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2095                 diag::note_constexpr_dynamic_alloc_here);
2096   }
2097   // We have no information to show for a typeid(T) object.
2098 }
2099 
2100 enum class CheckEvaluationResultKind {
2101   ConstantExpression,
2102   FullyInitialized,
2103 };
2104 
2105 /// Materialized temporaries that we've already checked to determine if they're
2106 /// initializsed by a constant expression.
2107 using CheckedTemporaries =
2108     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2109 
2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2111                                   EvalInfo &Info, SourceLocation DiagLoc,
2112                                   QualType Type, const APValue &Value,
2113                                   ConstantExprKind Kind,
2114                                   SourceLocation SubobjectLoc,
2115                                   CheckedTemporaries &CheckedTemps);
2116 
2117 /// Check that this reference or pointer core constant expression is a valid
2118 /// value for an address or reference constant expression. Return true if we
2119 /// can fold this expression, whether or not it's a constant expression.
2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2121                                           QualType Type, const LValue &LVal,
2122                                           ConstantExprKind Kind,
2123                                           CheckedTemporaries &CheckedTemps) {
2124   bool IsReferenceType = Type->isReferenceType();
2125 
2126   APValue::LValueBase Base = LVal.getLValueBase();
2127   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2128 
2129   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2130   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2131 
2132   // Additional restrictions apply in a template argument. We only enforce the
2133   // C++20 restrictions here; additional syntactic and semantic restrictions
2134   // are applied elsewhere.
2135   if (isTemplateArgument(Kind)) {
2136     int InvalidBaseKind = -1;
2137     StringRef Ident;
2138     if (Base.is<TypeInfoLValue>())
2139       InvalidBaseKind = 0;
2140     else if (isa_and_nonnull<StringLiteral>(BaseE))
2141       InvalidBaseKind = 1;
2142     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2143              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2144       InvalidBaseKind = 2;
2145     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2146       InvalidBaseKind = 3;
2147       Ident = PE->getIdentKindName();
2148     }
2149 
2150     if (InvalidBaseKind != -1) {
2151       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2152           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2153           << Ident;
2154       return false;
2155     }
2156   }
2157 
2158   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2159     if (FD->isConsteval()) {
2160       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2161           << !Type->isAnyPointerType();
2162       Info.Note(FD->getLocation(), diag::note_declared_at);
2163       return false;
2164     }
2165   }
2166 
2167   // Check that the object is a global. Note that the fake 'this' object we
2168   // manufacture when checking potential constant expressions is conservatively
2169   // assumed to be global here.
2170   if (!IsGlobalLValue(Base)) {
2171     if (Info.getLangOpts().CPlusPlus11) {
2172       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2173       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2174         << IsReferenceType << !Designator.Entries.empty()
2175         << !!VD << VD;
2176 
2177       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2178       if (VarD && VarD->isConstexpr()) {
2179         // Non-static local constexpr variables have unintuitive semantics:
2180         //   constexpr int a = 1;
2181         //   constexpr const int *p = &a;
2182         // ... is invalid because the address of 'a' is not constant. Suggest
2183         // adding a 'static' in this case.
2184         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2185             << VarD
2186             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2187       } else {
2188         NoteLValueLocation(Info, Base);
2189       }
2190     } else {
2191       Info.FFDiag(Loc);
2192     }
2193     // Don't allow references to temporaries to escape.
2194     return false;
2195   }
2196   assert((Info.checkingPotentialConstantExpression() ||
2197           LVal.getLValueCallIndex() == 0) &&
2198          "have call index for global lvalue");
2199 
2200   if (Base.is<DynamicAllocLValue>()) {
2201     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2202         << IsReferenceType << !Designator.Entries.empty();
2203     NoteLValueLocation(Info, Base);
2204     return false;
2205   }
2206 
2207   if (BaseVD) {
2208     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2209       // Check if this is a thread-local variable.
2210       if (Var->getTLSKind())
2211         // FIXME: Diagnostic!
2212         return false;
2213 
2214       // A dllimport variable never acts like a constant, unless we're
2215       // evaluating a value for use only in name mangling.
2216       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2217         // FIXME: Diagnostic!
2218         return false;
2219 
2220       // In CUDA/HIP device compilation, only device side variables have
2221       // constant addresses.
2222       if (Info.getCtx().getLangOpts().CUDA &&
2223           Info.getCtx().getLangOpts().CUDAIsDevice &&
2224           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2225         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2226              !Var->hasAttr<CUDAConstantAttr>() &&
2227              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2228              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2229             Var->hasAttr<HIPManagedAttr>())
2230           return false;
2231       }
2232     }
2233     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2234       // __declspec(dllimport) must be handled very carefully:
2235       // We must never initialize an expression with the thunk in C++.
2236       // Doing otherwise would allow the same id-expression to yield
2237       // different addresses for the same function in different translation
2238       // units.  However, this means that we must dynamically initialize the
2239       // expression with the contents of the import address table at runtime.
2240       //
2241       // The C language has no notion of ODR; furthermore, it has no notion of
2242       // dynamic initialization.  This means that we are permitted to
2243       // perform initialization with the address of the thunk.
2244       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2245           FD->hasAttr<DLLImportAttr>())
2246         // FIXME: Diagnostic!
2247         return false;
2248     }
2249   } else if (const auto *MTE =
2250                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2251     if (CheckedTemps.insert(MTE).second) {
2252       QualType TempType = getType(Base);
2253       if (TempType.isDestructedType()) {
2254         Info.FFDiag(MTE->getExprLoc(),
2255                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2256             << TempType;
2257         return false;
2258       }
2259 
2260       APValue *V = MTE->getOrCreateValue(false);
2261       assert(V && "evasluation result refers to uninitialised temporary");
2262       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2263                                  Info, MTE->getExprLoc(), TempType, *V,
2264                                  Kind, SourceLocation(), CheckedTemps))
2265         return false;
2266     }
2267   }
2268 
2269   // Allow address constant expressions to be past-the-end pointers. This is
2270   // an extension: the standard requires them to point to an object.
2271   if (!IsReferenceType)
2272     return true;
2273 
2274   // A reference constant expression must refer to an object.
2275   if (!Base) {
2276     // FIXME: diagnostic
2277     Info.CCEDiag(Loc);
2278     return true;
2279   }
2280 
2281   // Does this refer one past the end of some object?
2282   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2283     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2284       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2285     NoteLValueLocation(Info, Base);
2286   }
2287 
2288   return true;
2289 }
2290 
2291 /// Member pointers are constant expressions unless they point to a
2292 /// non-virtual dllimport member function.
2293 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2294                                                  SourceLocation Loc,
2295                                                  QualType Type,
2296                                                  const APValue &Value,
2297                                                  ConstantExprKind Kind) {
2298   const ValueDecl *Member = Value.getMemberPointerDecl();
2299   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2300   if (!FD)
2301     return true;
2302   if (FD->isConsteval()) {
2303     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2304     Info.Note(FD->getLocation(), diag::note_declared_at);
2305     return false;
2306   }
2307   return isForManglingOnly(Kind) || FD->isVirtual() ||
2308          !FD->hasAttr<DLLImportAttr>();
2309 }
2310 
2311 /// Check that this core constant expression is of literal type, and if not,
2312 /// produce an appropriate diagnostic.
2313 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2314                              const LValue *This = nullptr) {
2315   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2316     return true;
2317 
2318   // C++1y: A constant initializer for an object o [...] may also invoke
2319   // constexpr constructors for o and its subobjects even if those objects
2320   // are of non-literal class types.
2321   //
2322   // C++11 missed this detail for aggregates, so classes like this:
2323   //   struct foo_t { union { int i; volatile int j; } u; };
2324   // are not (obviously) initializable like so:
2325   //   __attribute__((__require_constant_initialization__))
2326   //   static const foo_t x = {{0}};
2327   // because "i" is a subobject with non-literal initialization (due to the
2328   // volatile member of the union). See:
2329   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2330   // Therefore, we use the C++1y behavior.
2331   if (This && Info.EvaluatingDecl == This->getLValueBase())
2332     return true;
2333 
2334   // Prvalue constant expressions must be of literal types.
2335   if (Info.getLangOpts().CPlusPlus11)
2336     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2337       << E->getType();
2338   else
2339     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2340   return false;
2341 }
2342 
2343 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2344                                   EvalInfo &Info, SourceLocation DiagLoc,
2345                                   QualType Type, const APValue &Value,
2346                                   ConstantExprKind Kind,
2347                                   SourceLocation SubobjectLoc,
2348                                   CheckedTemporaries &CheckedTemps) {
2349   if (!Value.hasValue()) {
2350     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2351       << true << Type;
2352     if (SubobjectLoc.isValid())
2353       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2354     return false;
2355   }
2356 
2357   // We allow _Atomic(T) to be initialized from anything that T can be
2358   // initialized from.
2359   if (const AtomicType *AT = Type->getAs<AtomicType>())
2360     Type = AT->getValueType();
2361 
2362   // Core issue 1454: For a literal constant expression of array or class type,
2363   // each subobject of its value shall have been initialized by a constant
2364   // expression.
2365   if (Value.isArray()) {
2366     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2367     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2368       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2369                                  Value.getArrayInitializedElt(I), Kind,
2370                                  SubobjectLoc, CheckedTemps))
2371         return false;
2372     }
2373     if (!Value.hasArrayFiller())
2374       return true;
2375     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2376                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2377                                  CheckedTemps);
2378   }
2379   if (Value.isUnion() && Value.getUnionField()) {
2380     return CheckEvaluationResult(
2381         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2382         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2383         CheckedTemps);
2384   }
2385   if (Value.isStruct()) {
2386     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2387     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2388       unsigned BaseIndex = 0;
2389       for (const CXXBaseSpecifier &BS : CD->bases()) {
2390         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2391                                    Value.getStructBase(BaseIndex), Kind,
2392                                    BS.getBeginLoc(), CheckedTemps))
2393           return false;
2394         ++BaseIndex;
2395       }
2396     }
2397     for (const auto *I : RD->fields()) {
2398       if (I->isUnnamedBitfield())
2399         continue;
2400 
2401       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2402                                  Value.getStructField(I->getFieldIndex()),
2403                                  Kind, I->getLocation(), CheckedTemps))
2404         return false;
2405     }
2406   }
2407 
2408   if (Value.isLValue() &&
2409       CERK == CheckEvaluationResultKind::ConstantExpression) {
2410     LValue LVal;
2411     LVal.setFrom(Info.Ctx, Value);
2412     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2413                                          CheckedTemps);
2414   }
2415 
2416   if (Value.isMemberPointer() &&
2417       CERK == CheckEvaluationResultKind::ConstantExpression)
2418     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2419 
2420   // Everything else is fine.
2421   return true;
2422 }
2423 
2424 /// Check that this core constant expression value is a valid value for a
2425 /// constant expression. If not, report an appropriate diagnostic. Does not
2426 /// check that the expression is of literal type.
2427 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2428                                     QualType Type, const APValue &Value,
2429                                     ConstantExprKind Kind) {
2430   // Nothing to check for a constant expression of type 'cv void'.
2431   if (Type->isVoidType())
2432     return true;
2433 
2434   CheckedTemporaries CheckedTemps;
2435   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2436                                Info, DiagLoc, Type, Value, Kind,
2437                                SourceLocation(), CheckedTemps);
2438 }
2439 
2440 /// Check that this evaluated value is fully-initialized and can be loaded by
2441 /// an lvalue-to-rvalue conversion.
2442 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2443                                   QualType Type, const APValue &Value) {
2444   CheckedTemporaries CheckedTemps;
2445   return CheckEvaluationResult(
2446       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2447       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2448 }
2449 
2450 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2451 /// "the allocated storage is deallocated within the evaluation".
2452 static bool CheckMemoryLeaks(EvalInfo &Info) {
2453   if (!Info.HeapAllocs.empty()) {
2454     // We can still fold to a constant despite a compile-time memory leak,
2455     // so long as the heap allocation isn't referenced in the result (we check
2456     // that in CheckConstantExpression).
2457     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2458                  diag::note_constexpr_memory_leak)
2459         << unsigned(Info.HeapAllocs.size() - 1);
2460   }
2461   return true;
2462 }
2463 
2464 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2465   // A null base expression indicates a null pointer.  These are always
2466   // evaluatable, and they are false unless the offset is zero.
2467   if (!Value.getLValueBase()) {
2468     Result = !Value.getLValueOffset().isZero();
2469     return true;
2470   }
2471 
2472   // We have a non-null base.  These are generally known to be true, but if it's
2473   // a weak declaration it can be null at runtime.
2474   Result = true;
2475   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2476   return !Decl || !Decl->isWeak();
2477 }
2478 
2479 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2480   switch (Val.getKind()) {
2481   case APValue::None:
2482   case APValue::Indeterminate:
2483     return false;
2484   case APValue::Int:
2485     Result = Val.getInt().getBoolValue();
2486     return true;
2487   case APValue::FixedPoint:
2488     Result = Val.getFixedPoint().getBoolValue();
2489     return true;
2490   case APValue::Float:
2491     Result = !Val.getFloat().isZero();
2492     return true;
2493   case APValue::ComplexInt:
2494     Result = Val.getComplexIntReal().getBoolValue() ||
2495              Val.getComplexIntImag().getBoolValue();
2496     return true;
2497   case APValue::ComplexFloat:
2498     Result = !Val.getComplexFloatReal().isZero() ||
2499              !Val.getComplexFloatImag().isZero();
2500     return true;
2501   case APValue::LValue:
2502     return EvalPointerValueAsBool(Val, Result);
2503   case APValue::MemberPointer:
2504     Result = Val.getMemberPointerDecl();
2505     return true;
2506   case APValue::Vector:
2507   case APValue::Array:
2508   case APValue::Struct:
2509   case APValue::Union:
2510   case APValue::AddrLabelDiff:
2511     return false;
2512   }
2513 
2514   llvm_unreachable("unknown APValue kind");
2515 }
2516 
2517 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2518                                        EvalInfo &Info) {
2519   assert(!E->isValueDependent());
2520   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2521   APValue Val;
2522   if (!Evaluate(Val, Info, E))
2523     return false;
2524   return HandleConversionToBool(Val, Result);
2525 }
2526 
2527 template<typename T>
2528 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2529                            const T &SrcValue, QualType DestType) {
2530   Info.CCEDiag(E, diag::note_constexpr_overflow)
2531     << SrcValue << DestType;
2532   return Info.noteUndefinedBehavior();
2533 }
2534 
2535 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2536                                  QualType SrcType, const APFloat &Value,
2537                                  QualType DestType, APSInt &Result) {
2538   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2539   // Determine whether we are converting to unsigned or signed.
2540   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2541 
2542   Result = APSInt(DestWidth, !DestSigned);
2543   bool ignored;
2544   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2545       & APFloat::opInvalidOp)
2546     return HandleOverflow(Info, E, Value, DestType);
2547   return true;
2548 }
2549 
2550 /// Get rounding mode used for evaluation of the specified expression.
2551 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2552 ///                       dynamic.
2553 /// If rounding mode is unknown at compile time, still try to evaluate the
2554 /// expression. If the result is exact, it does not depend on rounding mode.
2555 /// So return "tonearest" mode instead of "dynamic".
2556 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2557                                                 bool &DynamicRM) {
2558   llvm::RoundingMode RM =
2559       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2560   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2561   if (DynamicRM)
2562     RM = llvm::RoundingMode::NearestTiesToEven;
2563   return RM;
2564 }
2565 
2566 /// Check if the given evaluation result is allowed for constant evaluation.
2567 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2568                                      APFloat::opStatus St) {
2569   // In a constant context, assume that any dynamic rounding mode or FP
2570   // exception state matches the default floating-point environment.
2571   if (Info.InConstantContext)
2572     return true;
2573 
2574   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2575   if ((St & APFloat::opInexact) &&
2576       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2577     // Inexact result means that it depends on rounding mode. If the requested
2578     // mode is dynamic, the evaluation cannot be made in compile time.
2579     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2580     return false;
2581   }
2582 
2583   if ((St != APFloat::opOK) &&
2584       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2585        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2586        FPO.getAllowFEnvAccess())) {
2587     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2588     return false;
2589   }
2590 
2591   if ((St & APFloat::opStatus::opInvalidOp) &&
2592       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2593     // There is no usefully definable result.
2594     Info.FFDiag(E);
2595     return false;
2596   }
2597 
2598   // FIXME: if:
2599   // - evaluation triggered other FP exception, and
2600   // - exception mode is not "ignore", and
2601   // - the expression being evaluated is not a part of global variable
2602   //   initializer,
2603   // the evaluation probably need to be rejected.
2604   return true;
2605 }
2606 
2607 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2608                                    QualType SrcType, QualType DestType,
2609                                    APFloat &Result) {
2610   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2611   bool DynamicRM;
2612   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2613   APFloat::opStatus St;
2614   APFloat Value = Result;
2615   bool ignored;
2616   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2617   return checkFloatingPointResult(Info, E, St);
2618 }
2619 
2620 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2621                                  QualType DestType, QualType SrcType,
2622                                  const APSInt &Value) {
2623   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2624   // Figure out if this is a truncate, extend or noop cast.
2625   // If the input is signed, do a sign extend, noop, or truncate.
2626   APSInt Result = Value.extOrTrunc(DestWidth);
2627   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2628   if (DestType->isBooleanType())
2629     Result = Value.getBoolValue();
2630   return Result;
2631 }
2632 
2633 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2634                                  const FPOptions FPO,
2635                                  QualType SrcType, const APSInt &Value,
2636                                  QualType DestType, APFloat &Result) {
2637   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2638   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2639        APFloat::rmNearestTiesToEven);
2640   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2641       FPO.isFPConstrained()) {
2642     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2643     return false;
2644   }
2645   return true;
2646 }
2647 
2648 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2649                                   APValue &Value, const FieldDecl *FD) {
2650   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2651 
2652   if (!Value.isInt()) {
2653     // Trying to store a pointer-cast-to-integer into a bitfield.
2654     // FIXME: In this case, we should provide the diagnostic for casting
2655     // a pointer to an integer.
2656     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2657     Info.FFDiag(E);
2658     return false;
2659   }
2660 
2661   APSInt &Int = Value.getInt();
2662   unsigned OldBitWidth = Int.getBitWidth();
2663   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2664   if (NewBitWidth < OldBitWidth)
2665     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2666   return true;
2667 }
2668 
2669 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2670                                   llvm::APInt &Res) {
2671   APValue SVal;
2672   if (!Evaluate(SVal, Info, E))
2673     return false;
2674   if (SVal.isInt()) {
2675     Res = SVal.getInt();
2676     return true;
2677   }
2678   if (SVal.isFloat()) {
2679     Res = SVal.getFloat().bitcastToAPInt();
2680     return true;
2681   }
2682   if (SVal.isVector()) {
2683     QualType VecTy = E->getType();
2684     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2685     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2686     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2687     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2688     Res = llvm::APInt::getZero(VecSize);
2689     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2690       APValue &Elt = SVal.getVectorElt(i);
2691       llvm::APInt EltAsInt;
2692       if (Elt.isInt()) {
2693         EltAsInt = Elt.getInt();
2694       } else if (Elt.isFloat()) {
2695         EltAsInt = Elt.getFloat().bitcastToAPInt();
2696       } else {
2697         // Don't try to handle vectors of anything other than int or float
2698         // (not sure if it's possible to hit this case).
2699         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700         return false;
2701       }
2702       unsigned BaseEltSize = EltAsInt.getBitWidth();
2703       if (BigEndian)
2704         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2705       else
2706         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2707     }
2708     return true;
2709   }
2710   // Give up if the input isn't an int, float, or vector.  For example, we
2711   // reject "(v4i16)(intptr_t)&a".
2712   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2713   return false;
2714 }
2715 
2716 /// Perform the given integer operation, which is known to need at most BitWidth
2717 /// bits, and check for overflow in the original type (if that type was not an
2718 /// unsigned type).
2719 template<typename Operation>
2720 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2721                                  const APSInt &LHS, const APSInt &RHS,
2722                                  unsigned BitWidth, Operation Op,
2723                                  APSInt &Result) {
2724   if (LHS.isUnsigned()) {
2725     Result = Op(LHS, RHS);
2726     return true;
2727   }
2728 
2729   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2730   Result = Value.trunc(LHS.getBitWidth());
2731   if (Result.extend(BitWidth) != Value) {
2732     if (Info.checkingForUndefinedBehavior())
2733       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2734                                        diag::warn_integer_constant_overflow)
2735           << toString(Result, 10) << E->getType();
2736     return HandleOverflow(Info, E, Value, E->getType());
2737   }
2738   return true;
2739 }
2740 
2741 /// Perform the given binary integer operation.
2742 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2743                               BinaryOperatorKind Opcode, APSInt RHS,
2744                               APSInt &Result) {
2745   switch (Opcode) {
2746   default:
2747     Info.FFDiag(E);
2748     return false;
2749   case BO_Mul:
2750     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2751                                 std::multiplies<APSInt>(), Result);
2752   case BO_Add:
2753     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2754                                 std::plus<APSInt>(), Result);
2755   case BO_Sub:
2756     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757                                 std::minus<APSInt>(), Result);
2758   case BO_And: Result = LHS & RHS; return true;
2759   case BO_Xor: Result = LHS ^ RHS; return true;
2760   case BO_Or:  Result = LHS | RHS; return true;
2761   case BO_Div:
2762   case BO_Rem:
2763     if (RHS == 0) {
2764       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2765       return false;
2766     }
2767     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2768     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2769     // this operation and gives the two's complement result.
2770     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2771         LHS.isMinSignedValue())
2772       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2773                             E->getType());
2774     return true;
2775   case BO_Shl: {
2776     if (Info.getLangOpts().OpenCL)
2777       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2778       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2779                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2780                     RHS.isUnsigned());
2781     else if (RHS.isSigned() && RHS.isNegative()) {
2782       // During constant-folding, a negative shift is an opposite shift. Such
2783       // a shift is not a constant expression.
2784       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2785       RHS = -RHS;
2786       goto shift_right;
2787     }
2788   shift_left:
2789     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2790     // the shifted type.
2791     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2792     if (SA != RHS) {
2793       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2794         << RHS << E->getType() << LHS.getBitWidth();
2795     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2796       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2797       // operand, and must not overflow the corresponding unsigned type.
2798       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2799       // E1 x 2^E2 module 2^N.
2800       if (LHS.isNegative())
2801         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2802       else if (LHS.countLeadingZeros() < SA)
2803         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2804     }
2805     Result = LHS << SA;
2806     return true;
2807   }
2808   case BO_Shr: {
2809     if (Info.getLangOpts().OpenCL)
2810       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2811       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2812                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2813                     RHS.isUnsigned());
2814     else if (RHS.isSigned() && RHS.isNegative()) {
2815       // During constant-folding, a negative shift is an opposite shift. Such a
2816       // shift is not a constant expression.
2817       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2818       RHS = -RHS;
2819       goto shift_left;
2820     }
2821   shift_right:
2822     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2823     // shifted type.
2824     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2825     if (SA != RHS)
2826       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2827         << RHS << E->getType() << LHS.getBitWidth();
2828     Result = LHS >> SA;
2829     return true;
2830   }
2831 
2832   case BO_LT: Result = LHS < RHS; return true;
2833   case BO_GT: Result = LHS > RHS; return true;
2834   case BO_LE: Result = LHS <= RHS; return true;
2835   case BO_GE: Result = LHS >= RHS; return true;
2836   case BO_EQ: Result = LHS == RHS; return true;
2837   case BO_NE: Result = LHS != RHS; return true;
2838   case BO_Cmp:
2839     llvm_unreachable("BO_Cmp should be handled elsewhere");
2840   }
2841 }
2842 
2843 /// Perform the given binary floating-point operation, in-place, on LHS.
2844 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2845                                   APFloat &LHS, BinaryOperatorKind Opcode,
2846                                   const APFloat &RHS) {
2847   bool DynamicRM;
2848   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2849   APFloat::opStatus St;
2850   switch (Opcode) {
2851   default:
2852     Info.FFDiag(E);
2853     return false;
2854   case BO_Mul:
2855     St = LHS.multiply(RHS, RM);
2856     break;
2857   case BO_Add:
2858     St = LHS.add(RHS, RM);
2859     break;
2860   case BO_Sub:
2861     St = LHS.subtract(RHS, RM);
2862     break;
2863   case BO_Div:
2864     // [expr.mul]p4:
2865     //   If the second operand of / or % is zero the behavior is undefined.
2866     if (RHS.isZero())
2867       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2868     St = LHS.divide(RHS, RM);
2869     break;
2870   }
2871 
2872   // [expr.pre]p4:
2873   //   If during the evaluation of an expression, the result is not
2874   //   mathematically defined [...], the behavior is undefined.
2875   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2876   if (LHS.isNaN()) {
2877     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2878     return Info.noteUndefinedBehavior();
2879   }
2880 
2881   return checkFloatingPointResult(Info, E, St);
2882 }
2883 
2884 static bool handleLogicalOpForVector(const APInt &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APInt &RHSValue, APInt &Result) {
2887   bool LHS = (LHSValue != 0);
2888   bool RHS = (RHSValue != 0);
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
2896 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APFloat &RHSValue, APInt &Result) {
2899   bool LHS = !LHSValue.isZero();
2900   bool RHS = !RHSValue.isZero();
2901 
2902   if (Opcode == BO_LAnd)
2903     Result = LHS && RHS;
2904   else
2905     Result = LHS || RHS;
2906   return true;
2907 }
2908 
2909 static bool handleLogicalOpForVector(const APValue &LHSValue,
2910                                      BinaryOperatorKind Opcode,
2911                                      const APValue &RHSValue, APInt &Result) {
2912   // The result is always an int type, however operands match the first.
2913   if (LHSValue.getKind() == APValue::Int)
2914     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2915                                     RHSValue.getInt(), Result);
2916   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2917   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2918                                   RHSValue.getFloat(), Result);
2919 }
2920 
2921 template <typename APTy>
2922 static bool
2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2924                                const APTy &RHSValue, APInt &Result) {
2925   switch (Opcode) {
2926   default:
2927     llvm_unreachable("unsupported binary operator");
2928   case BO_EQ:
2929     Result = (LHSValue == RHSValue);
2930     break;
2931   case BO_NE:
2932     Result = (LHSValue != RHSValue);
2933     break;
2934   case BO_LT:
2935     Result = (LHSValue < RHSValue);
2936     break;
2937   case BO_GT:
2938     Result = (LHSValue > RHSValue);
2939     break;
2940   case BO_LE:
2941     Result = (LHSValue <= RHSValue);
2942     break;
2943   case BO_GE:
2944     Result = (LHSValue >= RHSValue);
2945     break;
2946   }
2947 
2948   // The boolean operations on these vector types use an instruction that
2949   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2950   // to -1 to make sure that we produce the correct value.
2951   Result.negate();
2952 
2953   return true;
2954 }
2955 
2956 static bool handleCompareOpForVector(const APValue &LHSValue,
2957                                      BinaryOperatorKind Opcode,
2958                                      const APValue &RHSValue, APInt &Result) {
2959   // The result is always an int type, however operands match the first.
2960   if (LHSValue.getKind() == APValue::Int)
2961     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2962                                           RHSValue.getInt(), Result);
2963   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2964   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2965                                         RHSValue.getFloat(), Result);
2966 }
2967 
2968 // Perform binary operations for vector types, in place on the LHS.
2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2970                                     BinaryOperatorKind Opcode,
2971                                     APValue &LHSValue,
2972                                     const APValue &RHSValue) {
2973   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2974          "Operation not supported on vector types");
2975 
2976   const auto *VT = E->getType()->castAs<VectorType>();
2977   unsigned NumElements = VT->getNumElements();
2978   QualType EltTy = VT->getElementType();
2979 
2980   // In the cases (typically C as I've observed) where we aren't evaluating
2981   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2982   // just give up.
2983   if (!LHSValue.isVector()) {
2984     assert(LHSValue.isLValue() &&
2985            "A vector result that isn't a vector OR uncalculated LValue");
2986     Info.FFDiag(E);
2987     return false;
2988   }
2989 
2990   assert(LHSValue.getVectorLength() == NumElements &&
2991          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2992 
2993   SmallVector<APValue, 4> ResultElements;
2994 
2995   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2996     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2997     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2998 
2999     if (EltTy->isIntegerType()) {
3000       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3001                        EltTy->isUnsignedIntegerType()};
3002       bool Success = true;
3003 
3004       if (BinaryOperator::isLogicalOp(Opcode))
3005         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006       else if (BinaryOperator::isComparisonOp(Opcode))
3007         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else
3009         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3010                                     RHSElt.getInt(), EltResult);
3011 
3012       if (!Success) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016       ResultElements.emplace_back(EltResult);
3017 
3018     } else if (EltTy->isFloatingType()) {
3019       assert(LHSElt.getKind() == APValue::Float &&
3020              RHSElt.getKind() == APValue::Float &&
3021              "Mismatched LHS/RHS/Result Type");
3022       APFloat LHSFloat = LHSElt.getFloat();
3023 
3024       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3025                                  RHSElt.getFloat())) {
3026         Info.FFDiag(E);
3027         return false;
3028       }
3029 
3030       ResultElements.emplace_back(LHSFloat);
3031     }
3032   }
3033 
3034   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3035   return true;
3036 }
3037 
3038 /// Cast an lvalue referring to a base subobject to a derived class, by
3039 /// truncating the lvalue's path to the given length.
3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3041                                const RecordDecl *TruncatedType,
3042                                unsigned TruncatedElements) {
3043   SubobjectDesignator &D = Result.Designator;
3044 
3045   // Check we actually point to a derived class object.
3046   if (TruncatedElements == D.Entries.size())
3047     return true;
3048   assert(TruncatedElements >= D.MostDerivedPathLength &&
3049          "not casting to a derived class");
3050   if (!Result.checkSubobject(Info, E, CSK_Derived))
3051     return false;
3052 
3053   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3054   const RecordDecl *RD = TruncatedType;
3055   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3056     if (RD->isInvalidDecl()) return false;
3057     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3058     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3059     if (isVirtualBaseClass(D.Entries[I]))
3060       Result.Offset -= Layout.getVBaseClassOffset(Base);
3061     else
3062       Result.Offset -= Layout.getBaseClassOffset(Base);
3063     RD = Base;
3064   }
3065   D.Entries.resize(TruncatedElements);
3066   return true;
3067 }
3068 
3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                                    const CXXRecordDecl *Derived,
3071                                    const CXXRecordDecl *Base,
3072                                    const ASTRecordLayout *RL = nullptr) {
3073   if (!RL) {
3074     if (Derived->isInvalidDecl()) return false;
3075     RL = &Info.Ctx.getASTRecordLayout(Derived);
3076   }
3077 
3078   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3079   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3080   return true;
3081 }
3082 
3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3084                              const CXXRecordDecl *DerivedDecl,
3085                              const CXXBaseSpecifier *Base) {
3086   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3087 
3088   if (!Base->isVirtual())
3089     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3090 
3091   SubobjectDesignator &D = Obj.Designator;
3092   if (D.Invalid)
3093     return false;
3094 
3095   // Extract most-derived object and corresponding type.
3096   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3097   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3098     return false;
3099 
3100   // Find the virtual base class.
3101   if (DerivedDecl->isInvalidDecl()) return false;
3102   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3103   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3104   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3105   return true;
3106 }
3107 
3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3109                                  QualType Type, LValue &Result) {
3110   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3111                                      PathE = E->path_end();
3112        PathI != PathE; ++PathI) {
3113     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3114                           *PathI))
3115       return false;
3116     Type = (*PathI)->getType();
3117   }
3118   return true;
3119 }
3120 
3121 /// Cast an lvalue referring to a derived class to a known base subobject.
3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3123                             const CXXRecordDecl *DerivedRD,
3124                             const CXXRecordDecl *BaseRD) {
3125   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3126                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3127   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3128     llvm_unreachable("Class must be derived from the passed in base class!");
3129 
3130   for (CXXBasePathElement &Elem : Paths.front())
3131     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3132       return false;
3133   return true;
3134 }
3135 
3136 /// Update LVal to refer to the given field, which must be a member of the type
3137 /// currently described by LVal.
3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3139                                const FieldDecl *FD,
3140                                const ASTRecordLayout *RL = nullptr) {
3141   if (!RL) {
3142     if (FD->getParent()->isInvalidDecl()) return false;
3143     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3144   }
3145 
3146   unsigned I = FD->getFieldIndex();
3147   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3148   LVal.addDecl(Info, E, FD);
3149   return true;
3150 }
3151 
3152 /// Update LVal to refer to the given indirect field.
3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3154                                        LValue &LVal,
3155                                        const IndirectFieldDecl *IFD) {
3156   for (const auto *C : IFD->chain())
3157     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3158       return false;
3159   return true;
3160 }
3161 
3162 /// Get the size of the given type in char units.
3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3164                          QualType Type, CharUnits &Size) {
3165   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3166   // extension.
3167   if (Type->isVoidType() || Type->isFunctionType()) {
3168     Size = CharUnits::One();
3169     return true;
3170   }
3171 
3172   if (Type->isDependentType()) {
3173     Info.FFDiag(Loc);
3174     return false;
3175   }
3176 
3177   if (!Type->isConstantSizeType()) {
3178     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3179     // FIXME: Better diagnostic.
3180     Info.FFDiag(Loc);
3181     return false;
3182   }
3183 
3184   Size = Info.Ctx.getTypeSizeInChars(Type);
3185   return true;
3186 }
3187 
3188 /// Update a pointer value to model pointer arithmetic.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param E - The expression being evaluated, for diagnostic purposes.
3191 /// \param LVal - The pointer value to be updated.
3192 /// \param EltTy - The pointee type represented by LVal.
3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3195                                         LValue &LVal, QualType EltTy,
3196                                         APSInt Adjustment) {
3197   CharUnits SizeOfPointee;
3198   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3199     return false;
3200 
3201   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3202   return true;
3203 }
3204 
3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3206                                         LValue &LVal, QualType EltTy,
3207                                         int64_t Adjustment) {
3208   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3209                                      APSInt::get(Adjustment));
3210 }
3211 
3212 /// Update an lvalue to refer to a component of a complex number.
3213 /// \param Info - Information about the ongoing evaluation.
3214 /// \param LVal - The lvalue to be updated.
3215 /// \param EltTy - The complex number's component type.
3216 /// \param Imag - False for the real component, true for the imaginary.
3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3218                                        LValue &LVal, QualType EltTy,
3219                                        bool Imag) {
3220   if (Imag) {
3221     CharUnits SizeOfComponent;
3222     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3223       return false;
3224     LVal.Offset += SizeOfComponent;
3225   }
3226   LVal.addComplex(Info, E, EltTy, Imag);
3227   return true;
3228 }
3229 
3230 /// Try to evaluate the initializer for a variable declaration.
3231 ///
3232 /// \param Info   Information about the ongoing evaluation.
3233 /// \param E      An expression to be used when printing diagnostics.
3234 /// \param VD     The variable whose initializer should be obtained.
3235 /// \param Version The version of the variable within the frame.
3236 /// \param Frame  The frame in which the variable was created. Must be null
3237 ///               if this variable is not local to the evaluation.
3238 /// \param Result Filled in with a pointer to the value of the variable.
3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3240                                 const VarDecl *VD, CallStackFrame *Frame,
3241                                 unsigned Version, APValue *&Result) {
3242   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3243 
3244   // If this is a local variable, dig out its value.
3245   if (Frame) {
3246     Result = Frame->getTemporary(VD, Version);
3247     if (Result)
3248       return true;
3249 
3250     if (!isa<ParmVarDecl>(VD)) {
3251       // Assume variables referenced within a lambda's call operator that were
3252       // not declared within the call operator are captures and during checking
3253       // of a potential constant expression, assume they are unknown constant
3254       // expressions.
3255       assert(isLambdaCallOperator(Frame->Callee) &&
3256              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3257              "missing value for local variable");
3258       if (Info.checkingPotentialConstantExpression())
3259         return false;
3260       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3261       // still reachable at all?
3262       Info.FFDiag(E->getBeginLoc(),
3263                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3264           << "captures not currently allowed";
3265       return false;
3266     }
3267   }
3268 
3269   // If we're currently evaluating the initializer of this declaration, use that
3270   // in-flight value.
3271   if (Info.EvaluatingDecl == Base) {
3272     Result = Info.EvaluatingDeclValue;
3273     return true;
3274   }
3275 
3276   if (isa<ParmVarDecl>(VD)) {
3277     // Assume parameters of a potential constant expression are usable in
3278     // constant expressions.
3279     if (!Info.checkingPotentialConstantExpression() ||
3280         !Info.CurrentCall->Callee ||
3281         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3282       if (Info.getLangOpts().CPlusPlus11) {
3283         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3284             << VD;
3285         NoteLValueLocation(Info, Base);
3286       } else {
3287         Info.FFDiag(E);
3288       }
3289     }
3290     return false;
3291   }
3292 
3293   // Dig out the initializer, and use the declaration which it's attached to.
3294   // FIXME: We should eventually check whether the variable has a reachable
3295   // initializing declaration.
3296   const Expr *Init = VD->getAnyInitializer(VD);
3297   if (!Init) {
3298     // Don't diagnose during potential constant expression checking; an
3299     // initializer might be added later.
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3302         << VD;
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   if (Init->isValueDependent()) {
3309     // The DeclRefExpr is not value-dependent, but the variable it refers to
3310     // has a value-dependent initializer. This should only happen in
3311     // constant-folding cases, where the variable is not actually of a suitable
3312     // type for use in a constant expression (otherwise the DeclRefExpr would
3313     // have been value-dependent too), so diagnose that.
3314     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3315     if (!Info.checkingPotentialConstantExpression()) {
3316       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3317                          ? diag::note_constexpr_ltor_non_constexpr
3318                          : diag::note_constexpr_ltor_non_integral, 1)
3319           << VD << VD->getType();
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   // Check that we can fold the initializer. In C++, we will have already done
3326   // this in the cases where it matters for conformance.
3327   SmallVector<PartialDiagnosticAt, 8> Notes;
3328   if (!VD->evaluateValue(Notes)) {
3329     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3330               Notes.size() + 1) << VD;
3331     NoteLValueLocation(Info, Base);
3332     Info.addNotes(Notes);
3333     return false;
3334   }
3335 
3336   // Check that the variable is actually usable in constant expressions. For a
3337   // const integral variable or a reference, we might have a non-constant
3338   // initializer that we can nonetheless evaluate the initializer for. Such
3339   // variables are not usable in constant expressions. In C++98, the
3340   // initializer also syntactically needs to be an ICE.
3341   //
3342   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3343   // expressions here; doing so would regress diagnostics for things like
3344   // reading from a volatile constexpr variable.
3345   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3346        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3347       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3348        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3349     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3350     NoteLValueLocation(Info, Base);
3351   }
3352 
3353   // Never use the initializer of a weak variable, not even for constant
3354   // folding. We can't be sure that this is the definition that will be used.
3355   if (VD->isWeak()) {
3356     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3357     NoteLValueLocation(Info, Base);
3358     return false;
3359   }
3360 
3361   Result = VD->getEvaluatedValue();
3362   return true;
3363 }
3364 
3365 /// Get the base index of the given base class within an APValue representing
3366 /// the given derived class.
3367 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3368                              const CXXRecordDecl *Base) {
3369   Base = Base->getCanonicalDecl();
3370   unsigned Index = 0;
3371   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3372          E = Derived->bases_end(); I != E; ++I, ++Index) {
3373     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3374       return Index;
3375   }
3376 
3377   llvm_unreachable("base class missing from derived class's bases list");
3378 }
3379 
3380 /// Extract the value of a character from a string literal.
3381 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3382                                             uint64_t Index) {
3383   assert(!isa<SourceLocExpr>(Lit) &&
3384          "SourceLocExpr should have already been converted to a StringLiteral");
3385 
3386   // FIXME: Support MakeStringConstant
3387   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3388     std::string Str;
3389     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3390     assert(Index <= Str.size() && "Index too large");
3391     return APSInt::getUnsigned(Str.c_str()[Index]);
3392   }
3393 
3394   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3395     Lit = PE->getFunctionName();
3396   const StringLiteral *S = cast<StringLiteral>(Lit);
3397   const ConstantArrayType *CAT =
3398       Info.Ctx.getAsConstantArrayType(S->getType());
3399   assert(CAT && "string literal isn't an array");
3400   QualType CharType = CAT->getElementType();
3401   assert(CharType->isIntegerType() && "unexpected character type");
3402 
3403   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3404                CharType->isUnsignedIntegerType());
3405   if (Index < S->getLength())
3406     Value = S->getCodeUnit(Index);
3407   return Value;
3408 }
3409 
3410 // Expand a string literal into an array of characters.
3411 //
3412 // FIXME: This is inefficient; we should probably introduce something similar
3413 // to the LLVM ConstantDataArray to make this cheaper.
3414 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3415                                 APValue &Result,
3416                                 QualType AllocType = QualType()) {
3417   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3418       AllocType.isNull() ? S->getType() : AllocType);
3419   assert(CAT && "string literal isn't an array");
3420   QualType CharType = CAT->getElementType();
3421   assert(CharType->isIntegerType() && "unexpected character type");
3422 
3423   unsigned Elts = CAT->getSize().getZExtValue();
3424   Result = APValue(APValue::UninitArray(),
3425                    std::min(S->getLength(), Elts), Elts);
3426   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3427                CharType->isUnsignedIntegerType());
3428   if (Result.hasArrayFiller())
3429     Result.getArrayFiller() = APValue(Value);
3430   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3431     Value = S->getCodeUnit(I);
3432     Result.getArrayInitializedElt(I) = APValue(Value);
3433   }
3434 }
3435 
3436 // Expand an array so that it has more than Index filled elements.
3437 static void expandArray(APValue &Array, unsigned Index) {
3438   unsigned Size = Array.getArraySize();
3439   assert(Index < Size);
3440 
3441   // Always at least double the number of elements for which we store a value.
3442   unsigned OldElts = Array.getArrayInitializedElts();
3443   unsigned NewElts = std::max(Index+1, OldElts * 2);
3444   NewElts = std::min(Size, std::max(NewElts, 8u));
3445 
3446   // Copy the data across.
3447   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3448   for (unsigned I = 0; I != OldElts; ++I)
3449     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3450   for (unsigned I = OldElts; I != NewElts; ++I)
3451     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3452   if (NewValue.hasArrayFiller())
3453     NewValue.getArrayFiller() = Array.getArrayFiller();
3454   Array.swap(NewValue);
3455 }
3456 
3457 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3458 /// conversion. If it's of class type, we may assume that the copy operation
3459 /// is trivial. Note that this is never true for a union type with fields
3460 /// (because the copy always "reads" the active member) and always true for
3461 /// a non-class type.
3462 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3463 static bool isReadByLvalueToRvalueConversion(QualType T) {
3464   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3465   return !RD || isReadByLvalueToRvalueConversion(RD);
3466 }
3467 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3468   // FIXME: A trivial copy of a union copies the object representation, even if
3469   // the union is empty.
3470   if (RD->isUnion())
3471     return !RD->field_empty();
3472   if (RD->isEmpty())
3473     return false;
3474 
3475   for (auto *Field : RD->fields())
3476     if (!Field->isUnnamedBitfield() &&
3477         isReadByLvalueToRvalueConversion(Field->getType()))
3478       return true;
3479 
3480   for (auto &BaseSpec : RD->bases())
3481     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3482       return true;
3483 
3484   return false;
3485 }
3486 
3487 /// Diagnose an attempt to read from any unreadable field within the specified
3488 /// type, which might be a class type.
3489 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3490                                   QualType T) {
3491   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3492   if (!RD)
3493     return false;
3494 
3495   if (!RD->hasMutableFields())
3496     return false;
3497 
3498   for (auto *Field : RD->fields()) {
3499     // If we're actually going to read this field in some way, then it can't
3500     // be mutable. If we're in a union, then assigning to a mutable field
3501     // (even an empty one) can change the active member, so that's not OK.
3502     // FIXME: Add core issue number for the union case.
3503     if (Field->isMutable() &&
3504         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3505       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3506       Info.Note(Field->getLocation(), diag::note_declared_at);
3507       return true;
3508     }
3509 
3510     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3511       return true;
3512   }
3513 
3514   for (auto &BaseSpec : RD->bases())
3515     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3516       return true;
3517 
3518   // All mutable fields were empty, and thus not actually read.
3519   return false;
3520 }
3521 
3522 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3523                                         APValue::LValueBase Base,
3524                                         bool MutableSubobject = false) {
3525   // A temporary or transient heap allocation we created.
3526   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3527     return true;
3528 
3529   switch (Info.IsEvaluatingDecl) {
3530   case EvalInfo::EvaluatingDeclKind::None:
3531     return false;
3532 
3533   case EvalInfo::EvaluatingDeclKind::Ctor:
3534     // The variable whose initializer we're evaluating.
3535     if (Info.EvaluatingDecl == Base)
3536       return true;
3537 
3538     // A temporary lifetime-extended by the variable whose initializer we're
3539     // evaluating.
3540     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3541       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3542         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3543     return false;
3544 
3545   case EvalInfo::EvaluatingDeclKind::Dtor:
3546     // C++2a [expr.const]p6:
3547     //   [during constant destruction] the lifetime of a and its non-mutable
3548     //   subobjects (but not its mutable subobjects) [are] considered to start
3549     //   within e.
3550     if (MutableSubobject || Base != Info.EvaluatingDecl)
3551       return false;
3552     // FIXME: We can meaningfully extend this to cover non-const objects, but
3553     // we will need special handling: we should be able to access only
3554     // subobjects of such objects that are themselves declared const.
3555     QualType T = getType(Base);
3556     return T.isConstQualified() || T->isReferenceType();
3557   }
3558 
3559   llvm_unreachable("unknown evaluating decl kind");
3560 }
3561 
3562 namespace {
3563 /// A handle to a complete object (an object that is not a subobject of
3564 /// another object).
3565 struct CompleteObject {
3566   /// The identity of the object.
3567   APValue::LValueBase Base;
3568   /// The value of the complete object.
3569   APValue *Value;
3570   /// The type of the complete object.
3571   QualType Type;
3572 
3573   CompleteObject() : Value(nullptr) {}
3574   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3575       : Base(Base), Value(Value), Type(Type) {}
3576 
3577   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3578     // If this isn't a "real" access (eg, if it's just accessing the type
3579     // info), allow it. We assume the type doesn't change dynamically for
3580     // subobjects of constexpr objects (even though we'd hit UB here if it
3581     // did). FIXME: Is this right?
3582     if (!isAnyAccess(AK))
3583       return true;
3584 
3585     // In C++14 onwards, it is permitted to read a mutable member whose
3586     // lifetime began within the evaluation.
3587     // FIXME: Should we also allow this in C++11?
3588     if (!Info.getLangOpts().CPlusPlus14)
3589       return false;
3590     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3591   }
3592 
3593   explicit operator bool() const { return !Type.isNull(); }
3594 };
3595 } // end anonymous namespace
3596 
3597 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3598                                  bool IsMutable = false) {
3599   // C++ [basic.type.qualifier]p1:
3600   // - A const object is an object of type const T or a non-mutable subobject
3601   //   of a const object.
3602   if (ObjType.isConstQualified() && !IsMutable)
3603     SubobjType.addConst();
3604   // - A volatile object is an object of type const T or a subobject of a
3605   //   volatile object.
3606   if (ObjType.isVolatileQualified())
3607     SubobjType.addVolatile();
3608   return SubobjType;
3609 }
3610 
3611 /// Find the designated sub-object of an rvalue.
3612 template<typename SubobjectHandler>
3613 typename SubobjectHandler::result_type
3614 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3615               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3616   if (Sub.Invalid)
3617     // A diagnostic will have already been produced.
3618     return handler.failed();
3619   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3620     if (Info.getLangOpts().CPlusPlus11)
3621       Info.FFDiag(E, Sub.isOnePastTheEnd()
3622                          ? diag::note_constexpr_access_past_end
3623                          : diag::note_constexpr_access_unsized_array)
3624           << handler.AccessKind;
3625     else
3626       Info.FFDiag(E);
3627     return handler.failed();
3628   }
3629 
3630   APValue *O = Obj.Value;
3631   QualType ObjType = Obj.Type;
3632   const FieldDecl *LastField = nullptr;
3633   const FieldDecl *VolatileField = nullptr;
3634 
3635   // Walk the designator's path to find the subobject.
3636   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3637     // Reading an indeterminate value is undefined, but assigning over one is OK.
3638     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3639         (O->isIndeterminate() &&
3640          !isValidIndeterminateAccess(handler.AccessKind))) {
3641       if (!Info.checkingPotentialConstantExpression())
3642         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3643             << handler.AccessKind << O->isIndeterminate();
3644       return handler.failed();
3645     }
3646 
3647     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3648     //    const and volatile semantics are not applied on an object under
3649     //    {con,de}struction.
3650     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3651         ObjType->isRecordType() &&
3652         Info.isEvaluatingCtorDtor(
3653             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3654                                          Sub.Entries.begin() + I)) !=
3655                           ConstructionPhase::None) {
3656       ObjType = Info.Ctx.getCanonicalType(ObjType);
3657       ObjType.removeLocalConst();
3658       ObjType.removeLocalVolatile();
3659     }
3660 
3661     // If this is our last pass, check that the final object type is OK.
3662     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3663       // Accesses to volatile objects are prohibited.
3664       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3665         if (Info.getLangOpts().CPlusPlus) {
3666           int DiagKind;
3667           SourceLocation Loc;
3668           const NamedDecl *Decl = nullptr;
3669           if (VolatileField) {
3670             DiagKind = 2;
3671             Loc = VolatileField->getLocation();
3672             Decl = VolatileField;
3673           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3674             DiagKind = 1;
3675             Loc = VD->getLocation();
3676             Decl = VD;
3677           } else {
3678             DiagKind = 0;
3679             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3680               Loc = E->getExprLoc();
3681           }
3682           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3683               << handler.AccessKind << DiagKind << Decl;
3684           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3685         } else {
3686           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3687         }
3688         return handler.failed();
3689       }
3690 
3691       // If we are reading an object of class type, there may still be more
3692       // things we need to check: if there are any mutable subobjects, we
3693       // cannot perform this read. (This only happens when performing a trivial
3694       // copy or assignment.)
3695       if (ObjType->isRecordType() &&
3696           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3697           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3698         return handler.failed();
3699     }
3700 
3701     if (I == N) {
3702       if (!handler.found(*O, ObjType))
3703         return false;
3704 
3705       // If we modified a bit-field, truncate it to the right width.
3706       if (isModification(handler.AccessKind) &&
3707           LastField && LastField->isBitField() &&
3708           !truncateBitfieldValue(Info, E, *O, LastField))
3709         return false;
3710 
3711       return true;
3712     }
3713 
3714     LastField = nullptr;
3715     if (ObjType->isArrayType()) {
3716       // Next subobject is an array element.
3717       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3718       assert(CAT && "vla in literal type?");
3719       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3720       if (CAT->getSize().ule(Index)) {
3721         // Note, it should not be possible to form a pointer with a valid
3722         // designator which points more than one past the end of the array.
3723         if (Info.getLangOpts().CPlusPlus11)
3724           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3725             << handler.AccessKind;
3726         else
3727           Info.FFDiag(E);
3728         return handler.failed();
3729       }
3730 
3731       ObjType = CAT->getElementType();
3732 
3733       if (O->getArrayInitializedElts() > Index)
3734         O = &O->getArrayInitializedElt(Index);
3735       else if (!isRead(handler.AccessKind)) {
3736         expandArray(*O, Index);
3737         O = &O->getArrayInitializedElt(Index);
3738       } else
3739         O = &O->getArrayFiller();
3740     } else if (ObjType->isAnyComplexType()) {
3741       // Next subobject is a complex number.
3742       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3743       if (Index > 1) {
3744         if (Info.getLangOpts().CPlusPlus11)
3745           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3746             << handler.AccessKind;
3747         else
3748           Info.FFDiag(E);
3749         return handler.failed();
3750       }
3751 
3752       ObjType = getSubobjectType(
3753           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3754 
3755       assert(I == N - 1 && "extracting subobject of scalar?");
3756       if (O->isComplexInt()) {
3757         return handler.found(Index ? O->getComplexIntImag()
3758                                    : O->getComplexIntReal(), ObjType);
3759       } else {
3760         assert(O->isComplexFloat());
3761         return handler.found(Index ? O->getComplexFloatImag()
3762                                    : O->getComplexFloatReal(), ObjType);
3763       }
3764     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3765       if (Field->isMutable() &&
3766           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3767         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3768           << handler.AccessKind << Field;
3769         Info.Note(Field->getLocation(), diag::note_declared_at);
3770         return handler.failed();
3771       }
3772 
3773       // Next subobject is a class, struct or union field.
3774       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3775       if (RD->isUnion()) {
3776         const FieldDecl *UnionField = O->getUnionField();
3777         if (!UnionField ||
3778             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3779           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3780             // Placement new onto an inactive union member makes it active.
3781             O->setUnion(Field, APValue());
3782           } else {
3783             // FIXME: If O->getUnionValue() is absent, report that there's no
3784             // active union member rather than reporting the prior active union
3785             // member. We'll need to fix nullptr_t to not use APValue() as its
3786             // representation first.
3787             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3788                 << handler.AccessKind << Field << !UnionField << UnionField;
3789             return handler.failed();
3790           }
3791         }
3792         O = &O->getUnionValue();
3793       } else
3794         O = &O->getStructField(Field->getFieldIndex());
3795 
3796       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3797       LastField = Field;
3798       if (Field->getType().isVolatileQualified())
3799         VolatileField = Field;
3800     } else {
3801       // Next subobject is a base class.
3802       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3803       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3804       O = &O->getStructBase(getBaseIndex(Derived, Base));
3805 
3806       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3807     }
3808   }
3809 }
3810 
3811 namespace {
3812 struct ExtractSubobjectHandler {
3813   EvalInfo &Info;
3814   const Expr *E;
3815   APValue &Result;
3816   const AccessKinds AccessKind;
3817 
3818   typedef bool result_type;
3819   bool failed() { return false; }
3820   bool found(APValue &Subobj, QualType SubobjType) {
3821     Result = Subobj;
3822     if (AccessKind == AK_ReadObjectRepresentation)
3823       return true;
3824     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3825   }
3826   bool found(APSInt &Value, QualType SubobjType) {
3827     Result = APValue(Value);
3828     return true;
3829   }
3830   bool found(APFloat &Value, QualType SubobjType) {
3831     Result = APValue(Value);
3832     return true;
3833   }
3834 };
3835 } // end anonymous namespace
3836 
3837 /// Extract the designated sub-object of an rvalue.
3838 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3839                              const CompleteObject &Obj,
3840                              const SubobjectDesignator &Sub, APValue &Result,
3841                              AccessKinds AK = AK_Read) {
3842   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3843   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3844   return findSubobject(Info, E, Obj, Sub, Handler);
3845 }
3846 
3847 namespace {
3848 struct ModifySubobjectHandler {
3849   EvalInfo &Info;
3850   APValue &NewVal;
3851   const Expr *E;
3852 
3853   typedef bool result_type;
3854   static const AccessKinds AccessKind = AK_Assign;
3855 
3856   bool checkConst(QualType QT) {
3857     // Assigning to a const object has undefined behavior.
3858     if (QT.isConstQualified()) {
3859       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3860       return false;
3861     }
3862     return true;
3863   }
3864 
3865   bool failed() { return false; }
3866   bool found(APValue &Subobj, QualType SubobjType) {
3867     if (!checkConst(SubobjType))
3868       return false;
3869     // We've been given ownership of NewVal, so just swap it in.
3870     Subobj.swap(NewVal);
3871     return true;
3872   }
3873   bool found(APSInt &Value, QualType SubobjType) {
3874     if (!checkConst(SubobjType))
3875       return false;
3876     if (!NewVal.isInt()) {
3877       // Maybe trying to write a cast pointer value into a complex?
3878       Info.FFDiag(E);
3879       return false;
3880     }
3881     Value = NewVal.getInt();
3882     return true;
3883   }
3884   bool found(APFloat &Value, QualType SubobjType) {
3885     if (!checkConst(SubobjType))
3886       return false;
3887     Value = NewVal.getFloat();
3888     return true;
3889   }
3890 };
3891 } // end anonymous namespace
3892 
3893 const AccessKinds ModifySubobjectHandler::AccessKind;
3894 
3895 /// Update the designated sub-object of an rvalue to the given value.
3896 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3897                             const CompleteObject &Obj,
3898                             const SubobjectDesignator &Sub,
3899                             APValue &NewVal) {
3900   ModifySubobjectHandler Handler = { Info, NewVal, E };
3901   return findSubobject(Info, E, Obj, Sub, Handler);
3902 }
3903 
3904 /// Find the position where two subobject designators diverge, or equivalently
3905 /// the length of the common initial subsequence.
3906 static unsigned FindDesignatorMismatch(QualType ObjType,
3907                                        const SubobjectDesignator &A,
3908                                        const SubobjectDesignator &B,
3909                                        bool &WasArrayIndex) {
3910   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3911   for (/**/; I != N; ++I) {
3912     if (!ObjType.isNull() &&
3913         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3914       // Next subobject is an array element.
3915       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3916         WasArrayIndex = true;
3917         return I;
3918       }
3919       if (ObjType->isAnyComplexType())
3920         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3921       else
3922         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3923     } else {
3924       if (A.Entries[I].getAsBaseOrMember() !=
3925           B.Entries[I].getAsBaseOrMember()) {
3926         WasArrayIndex = false;
3927         return I;
3928       }
3929       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3930         // Next subobject is a field.
3931         ObjType = FD->getType();
3932       else
3933         // Next subobject is a base class.
3934         ObjType = QualType();
3935     }
3936   }
3937   WasArrayIndex = false;
3938   return I;
3939 }
3940 
3941 /// Determine whether the given subobject designators refer to elements of the
3942 /// same array object.
3943 static bool AreElementsOfSameArray(QualType ObjType,
3944                                    const SubobjectDesignator &A,
3945                                    const SubobjectDesignator &B) {
3946   if (A.Entries.size() != B.Entries.size())
3947     return false;
3948 
3949   bool IsArray = A.MostDerivedIsArrayElement;
3950   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3951     // A is a subobject of the array element.
3952     return false;
3953 
3954   // If A (and B) designates an array element, the last entry will be the array
3955   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3956   // of length 1' case, and the entire path must match.
3957   bool WasArrayIndex;
3958   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3959   return CommonLength >= A.Entries.size() - IsArray;
3960 }
3961 
3962 /// Find the complete object to which an LValue refers.
3963 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3964                                          AccessKinds AK, const LValue &LVal,
3965                                          QualType LValType) {
3966   if (LVal.InvalidBase) {
3967     Info.FFDiag(E);
3968     return CompleteObject();
3969   }
3970 
3971   if (!LVal.Base) {
3972     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3973     return CompleteObject();
3974   }
3975 
3976   CallStackFrame *Frame = nullptr;
3977   unsigned Depth = 0;
3978   if (LVal.getLValueCallIndex()) {
3979     std::tie(Frame, Depth) =
3980         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3981     if (!Frame) {
3982       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3983         << AK << LVal.Base.is<const ValueDecl*>();
3984       NoteLValueLocation(Info, LVal.Base);
3985       return CompleteObject();
3986     }
3987   }
3988 
3989   bool IsAccess = isAnyAccess(AK);
3990 
3991   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3992   // is not a constant expression (even if the object is non-volatile). We also
3993   // apply this rule to C++98, in order to conform to the expected 'volatile'
3994   // semantics.
3995   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3996     if (Info.getLangOpts().CPlusPlus)
3997       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3998         << AK << LValType;
3999     else
4000       Info.FFDiag(E);
4001     return CompleteObject();
4002   }
4003 
4004   // Compute value storage location and type of base object.
4005   APValue *BaseVal = nullptr;
4006   QualType BaseType = getType(LVal.Base);
4007 
4008   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4009       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4010     // This is the object whose initializer we're evaluating, so its lifetime
4011     // started in the current evaluation.
4012     BaseVal = Info.EvaluatingDeclValue;
4013   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4014     // Allow reading from a GUID declaration.
4015     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4016       if (isModification(AK)) {
4017         // All the remaining cases do not permit modification of the object.
4018         Info.FFDiag(E, diag::note_constexpr_modify_global);
4019         return CompleteObject();
4020       }
4021       APValue &V = GD->getAsAPValue();
4022       if (V.isAbsent()) {
4023         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4024             << GD->getType();
4025         return CompleteObject();
4026       }
4027       return CompleteObject(LVal.Base, &V, GD->getType());
4028     }
4029 
4030     // Allow reading from template parameter objects.
4031     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4032       if (isModification(AK)) {
4033         Info.FFDiag(E, diag::note_constexpr_modify_global);
4034         return CompleteObject();
4035       }
4036       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4037                             TPO->getType());
4038     }
4039 
4040     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4041     // In C++11, constexpr, non-volatile variables initialized with constant
4042     // expressions are constant expressions too. Inside constexpr functions,
4043     // parameters are constant expressions even if they're non-const.
4044     // In C++1y, objects local to a constant expression (those with a Frame) are
4045     // both readable and writable inside constant expressions.
4046     // In C, such things can also be folded, although they are not ICEs.
4047     const VarDecl *VD = dyn_cast<VarDecl>(D);
4048     if (VD) {
4049       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4050         VD = VDef;
4051     }
4052     if (!VD || VD->isInvalidDecl()) {
4053       Info.FFDiag(E);
4054       return CompleteObject();
4055     }
4056 
4057     bool IsConstant = BaseType.isConstant(Info.Ctx);
4058 
4059     // Unless we're looking at a local variable or argument in a constexpr call,
4060     // the variable we're reading must be const.
4061     if (!Frame) {
4062       if (IsAccess && isa<ParmVarDecl>(VD)) {
4063         // Access of a parameter that's not associated with a frame isn't going
4064         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4065         // suitable diagnostic.
4066       } else if (Info.getLangOpts().CPlusPlus14 &&
4067                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4068         // OK, we can read and modify an object if we're in the process of
4069         // evaluating its initializer, because its lifetime began in this
4070         // evaluation.
4071       } else if (isModification(AK)) {
4072         // All the remaining cases do not permit modification of the object.
4073         Info.FFDiag(E, diag::note_constexpr_modify_global);
4074         return CompleteObject();
4075       } else if (VD->isConstexpr()) {
4076         // OK, we can read this variable.
4077       } else if (BaseType->isIntegralOrEnumerationType()) {
4078         if (!IsConstant) {
4079           if (!IsAccess)
4080             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4081           if (Info.getLangOpts().CPlusPlus) {
4082             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4083             Info.Note(VD->getLocation(), diag::note_declared_at);
4084           } else {
4085             Info.FFDiag(E);
4086           }
4087           return CompleteObject();
4088         }
4089       } else if (!IsAccess) {
4090         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4091       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4092                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4093         // This variable might end up being constexpr. Don't diagnose it yet.
4094       } else if (IsConstant) {
4095         // Keep evaluating to see what we can do. In particular, we support
4096         // folding of const floating-point types, in order to make static const
4097         // data members of such types (supported as an extension) more useful.
4098         if (Info.getLangOpts().CPlusPlus) {
4099           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4100                               ? diag::note_constexpr_ltor_non_constexpr
4101                               : diag::note_constexpr_ltor_non_integral, 1)
4102               << VD << BaseType;
4103           Info.Note(VD->getLocation(), diag::note_declared_at);
4104         } else {
4105           Info.CCEDiag(E);
4106         }
4107       } else {
4108         // Never allow reading a non-const value.
4109         if (Info.getLangOpts().CPlusPlus) {
4110           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4111                              ? diag::note_constexpr_ltor_non_constexpr
4112                              : diag::note_constexpr_ltor_non_integral, 1)
4113               << VD << BaseType;
4114           Info.Note(VD->getLocation(), diag::note_declared_at);
4115         } else {
4116           Info.FFDiag(E);
4117         }
4118         return CompleteObject();
4119       }
4120     }
4121 
4122     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4123       return CompleteObject();
4124   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4125     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4126     if (!Alloc) {
4127       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4128       return CompleteObject();
4129     }
4130     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4131                           LVal.Base.getDynamicAllocType());
4132   } else {
4133     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4134 
4135     if (!Frame) {
4136       if (const MaterializeTemporaryExpr *MTE =
4137               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4138         assert(MTE->getStorageDuration() == SD_Static &&
4139                "should have a frame for a non-global materialized temporary");
4140 
4141         // C++20 [expr.const]p4: [DR2126]
4142         //   An object or reference is usable in constant expressions if it is
4143         //   - a temporary object of non-volatile const-qualified literal type
4144         //     whose lifetime is extended to that of a variable that is usable
4145         //     in constant expressions
4146         //
4147         // C++20 [expr.const]p5:
4148         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4149         //   - a non-volatile glvalue that refers to an object that is usable
4150         //     in constant expressions, or
4151         //   - a non-volatile glvalue of literal type that refers to a
4152         //     non-volatile object whose lifetime began within the evaluation
4153         //     of E;
4154         //
4155         // C++11 misses the 'began within the evaluation of e' check and
4156         // instead allows all temporaries, including things like:
4157         //   int &&r = 1;
4158         //   int x = ++r;
4159         //   constexpr int k = r;
4160         // Therefore we use the C++14-onwards rules in C++11 too.
4161         //
4162         // Note that temporaries whose lifetimes began while evaluating a
4163         // variable's constructor are not usable while evaluating the
4164         // corresponding destructor, not even if they're of const-qualified
4165         // types.
4166         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4167             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4168           if (!IsAccess)
4169             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4170           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4171           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4172           return CompleteObject();
4173         }
4174 
4175         BaseVal = MTE->getOrCreateValue(false);
4176         assert(BaseVal && "got reference to unevaluated temporary");
4177       } else {
4178         if (!IsAccess)
4179           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4180         APValue Val;
4181         LVal.moveInto(Val);
4182         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4183             << AK
4184             << Val.getAsString(Info.Ctx,
4185                                Info.Ctx.getLValueReferenceType(LValType));
4186         NoteLValueLocation(Info, LVal.Base);
4187         return CompleteObject();
4188       }
4189     } else {
4190       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4191       assert(BaseVal && "missing value for temporary");
4192     }
4193   }
4194 
4195   // In C++14, we can't safely access any mutable state when we might be
4196   // evaluating after an unmodeled side effect. Parameters are modeled as state
4197   // in the caller, but aren't visible once the call returns, so they can be
4198   // modified in a speculatively-evaluated call.
4199   //
4200   // FIXME: Not all local state is mutable. Allow local constant subobjects
4201   // to be read here (but take care with 'mutable' fields).
4202   unsigned VisibleDepth = Depth;
4203   if (llvm::isa_and_nonnull<ParmVarDecl>(
4204           LVal.Base.dyn_cast<const ValueDecl *>()))
4205     ++VisibleDepth;
4206   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4207        Info.EvalStatus.HasSideEffects) ||
4208       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4209     return CompleteObject();
4210 
4211   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4212 }
4213 
4214 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4215 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4216 /// glvalue referred to by an entity of reference type.
4217 ///
4218 /// \param Info - Information about the ongoing evaluation.
4219 /// \param Conv - The expression for which we are performing the conversion.
4220 ///               Used for diagnostics.
4221 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4222 ///               case of a non-class type).
4223 /// \param LVal - The glvalue on which we are attempting to perform this action.
4224 /// \param RVal - The produced value will be placed here.
4225 /// \param WantObjectRepresentation - If true, we're looking for the object
4226 ///               representation rather than the value, and in particular,
4227 ///               there is no requirement that the result be fully initialized.
4228 static bool
4229 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4230                                const LValue &LVal, APValue &RVal,
4231                                bool WantObjectRepresentation = false) {
4232   if (LVal.Designator.Invalid)
4233     return false;
4234 
4235   // Check for special cases where there is no existing APValue to look at.
4236   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4237 
4238   AccessKinds AK =
4239       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4240 
4241   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4242     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4243       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4244       // initializer until now for such expressions. Such an expression can't be
4245       // an ICE in C, so this only matters for fold.
4246       if (Type.isVolatileQualified()) {
4247         Info.FFDiag(Conv);
4248         return false;
4249       }
4250       APValue Lit;
4251       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4252         return false;
4253       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4254       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4255     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4256       // Special-case character extraction so we don't have to construct an
4257       // APValue for the whole string.
4258       assert(LVal.Designator.Entries.size() <= 1 &&
4259              "Can only read characters from string literals");
4260       if (LVal.Designator.Entries.empty()) {
4261         // Fail for now for LValue to RValue conversion of an array.
4262         // (This shouldn't show up in C/C++, but it could be triggered by a
4263         // weird EvaluateAsRValue call from a tool.)
4264         Info.FFDiag(Conv);
4265         return false;
4266       }
4267       if (LVal.Designator.isOnePastTheEnd()) {
4268         if (Info.getLangOpts().CPlusPlus11)
4269           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4270         else
4271           Info.FFDiag(Conv);
4272         return false;
4273       }
4274       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4275       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4276       return true;
4277     }
4278   }
4279 
4280   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4281   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4282 }
4283 
4284 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4285 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4286                              QualType LValType, APValue &Val) {
4287   if (LVal.Designator.Invalid)
4288     return false;
4289 
4290   if (!Info.getLangOpts().CPlusPlus14) {
4291     Info.FFDiag(E);
4292     return false;
4293   }
4294 
4295   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4296   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4297 }
4298 
4299 namespace {
4300 struct CompoundAssignSubobjectHandler {
4301   EvalInfo &Info;
4302   const CompoundAssignOperator *E;
4303   QualType PromotedLHSType;
4304   BinaryOperatorKind Opcode;
4305   const APValue &RHS;
4306 
4307   static const AccessKinds AccessKind = AK_Assign;
4308 
4309   typedef bool result_type;
4310 
4311   bool checkConst(QualType QT) {
4312     // Assigning to a const object has undefined behavior.
4313     if (QT.isConstQualified()) {
4314       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4315       return false;
4316     }
4317     return true;
4318   }
4319 
4320   bool failed() { return false; }
4321   bool found(APValue &Subobj, QualType SubobjType) {
4322     switch (Subobj.getKind()) {
4323     case APValue::Int:
4324       return found(Subobj.getInt(), SubobjType);
4325     case APValue::Float:
4326       return found(Subobj.getFloat(), SubobjType);
4327     case APValue::ComplexInt:
4328     case APValue::ComplexFloat:
4329       // FIXME: Implement complex compound assignment.
4330       Info.FFDiag(E);
4331       return false;
4332     case APValue::LValue:
4333       return foundPointer(Subobj, SubobjType);
4334     case APValue::Vector:
4335       return foundVector(Subobj, SubobjType);
4336     default:
4337       // FIXME: can this happen?
4338       Info.FFDiag(E);
4339       return false;
4340     }
4341   }
4342 
4343   bool foundVector(APValue &Value, QualType SubobjType) {
4344     if (!checkConst(SubobjType))
4345       return false;
4346 
4347     if (!SubobjType->isVectorType()) {
4348       Info.FFDiag(E);
4349       return false;
4350     }
4351     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4352   }
4353 
4354   bool found(APSInt &Value, QualType SubobjType) {
4355     if (!checkConst(SubobjType))
4356       return false;
4357 
4358     if (!SubobjType->isIntegerType()) {
4359       // We don't support compound assignment on integer-cast-to-pointer
4360       // values.
4361       Info.FFDiag(E);
4362       return false;
4363     }
4364 
4365     if (RHS.isInt()) {
4366       APSInt LHS =
4367           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4368       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4369         return false;
4370       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4371       return true;
4372     } else if (RHS.isFloat()) {
4373       const FPOptions FPO = E->getFPFeaturesInEffect(
4374                                     Info.Ctx.getLangOpts());
4375       APFloat FValue(0.0);
4376       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4377                                   PromotedLHSType, FValue) &&
4378              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4379              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4380                                   Value);
4381     }
4382 
4383     Info.FFDiag(E);
4384     return false;
4385   }
4386   bool found(APFloat &Value, QualType SubobjType) {
4387     return checkConst(SubobjType) &&
4388            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4389                                   Value) &&
4390            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4391            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4392   }
4393   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4394     if (!checkConst(SubobjType))
4395       return false;
4396 
4397     QualType PointeeType;
4398     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4399       PointeeType = PT->getPointeeType();
4400 
4401     if (PointeeType.isNull() || !RHS.isInt() ||
4402         (Opcode != BO_Add && Opcode != BO_Sub)) {
4403       Info.FFDiag(E);
4404       return false;
4405     }
4406 
4407     APSInt Offset = RHS.getInt();
4408     if (Opcode == BO_Sub)
4409       negateAsSigned(Offset);
4410 
4411     LValue LVal;
4412     LVal.setFrom(Info.Ctx, Subobj);
4413     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4414       return false;
4415     LVal.moveInto(Subobj);
4416     return true;
4417   }
4418 };
4419 } // end anonymous namespace
4420 
4421 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4422 
4423 /// Perform a compound assignment of LVal <op>= RVal.
4424 static bool handleCompoundAssignment(EvalInfo &Info,
4425                                      const CompoundAssignOperator *E,
4426                                      const LValue &LVal, QualType LValType,
4427                                      QualType PromotedLValType,
4428                                      BinaryOperatorKind Opcode,
4429                                      const APValue &RVal) {
4430   if (LVal.Designator.Invalid)
4431     return false;
4432 
4433   if (!Info.getLangOpts().CPlusPlus14) {
4434     Info.FFDiag(E);
4435     return false;
4436   }
4437 
4438   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4439   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4440                                              RVal };
4441   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4442 }
4443 
4444 namespace {
4445 struct IncDecSubobjectHandler {
4446   EvalInfo &Info;
4447   const UnaryOperator *E;
4448   AccessKinds AccessKind;
4449   APValue *Old;
4450 
4451   typedef bool result_type;
4452 
4453   bool checkConst(QualType QT) {
4454     // Assigning to a const object has undefined behavior.
4455     if (QT.isConstQualified()) {
4456       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4457       return false;
4458     }
4459     return true;
4460   }
4461 
4462   bool failed() { return false; }
4463   bool found(APValue &Subobj, QualType SubobjType) {
4464     // Stash the old value. Also clear Old, so we don't clobber it later
4465     // if we're post-incrementing a complex.
4466     if (Old) {
4467       *Old = Subobj;
4468       Old = nullptr;
4469     }
4470 
4471     switch (Subobj.getKind()) {
4472     case APValue::Int:
4473       return found(Subobj.getInt(), SubobjType);
4474     case APValue::Float:
4475       return found(Subobj.getFloat(), SubobjType);
4476     case APValue::ComplexInt:
4477       return found(Subobj.getComplexIntReal(),
4478                    SubobjType->castAs<ComplexType>()->getElementType()
4479                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4480     case APValue::ComplexFloat:
4481       return found(Subobj.getComplexFloatReal(),
4482                    SubobjType->castAs<ComplexType>()->getElementType()
4483                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4484     case APValue::LValue:
4485       return foundPointer(Subobj, SubobjType);
4486     default:
4487       // FIXME: can this happen?
4488       Info.FFDiag(E);
4489       return false;
4490     }
4491   }
4492   bool found(APSInt &Value, QualType SubobjType) {
4493     if (!checkConst(SubobjType))
4494       return false;
4495 
4496     if (!SubobjType->isIntegerType()) {
4497       // We don't support increment / decrement on integer-cast-to-pointer
4498       // values.
4499       Info.FFDiag(E);
4500       return false;
4501     }
4502 
4503     if (Old) *Old = APValue(Value);
4504 
4505     // bool arithmetic promotes to int, and the conversion back to bool
4506     // doesn't reduce mod 2^n, so special-case it.
4507     if (SubobjType->isBooleanType()) {
4508       if (AccessKind == AK_Increment)
4509         Value = 1;
4510       else
4511         Value = !Value;
4512       return true;
4513     }
4514 
4515     bool WasNegative = Value.isNegative();
4516     if (AccessKind == AK_Increment) {
4517       ++Value;
4518 
4519       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4520         APSInt ActualValue(Value, /*IsUnsigned*/true);
4521         return HandleOverflow(Info, E, ActualValue, SubobjType);
4522       }
4523     } else {
4524       --Value;
4525 
4526       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4527         unsigned BitWidth = Value.getBitWidth();
4528         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4529         ActualValue.setBit(BitWidth);
4530         return HandleOverflow(Info, E, ActualValue, SubobjType);
4531       }
4532     }
4533     return true;
4534   }
4535   bool found(APFloat &Value, QualType SubobjType) {
4536     if (!checkConst(SubobjType))
4537       return false;
4538 
4539     if (Old) *Old = APValue(Value);
4540 
4541     APFloat One(Value.getSemantics(), 1);
4542     if (AccessKind == AK_Increment)
4543       Value.add(One, APFloat::rmNearestTiesToEven);
4544     else
4545       Value.subtract(One, APFloat::rmNearestTiesToEven);
4546     return true;
4547   }
4548   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4549     if (!checkConst(SubobjType))
4550       return false;
4551 
4552     QualType PointeeType;
4553     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4554       PointeeType = PT->getPointeeType();
4555     else {
4556       Info.FFDiag(E);
4557       return false;
4558     }
4559 
4560     LValue LVal;
4561     LVal.setFrom(Info.Ctx, Subobj);
4562     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4563                                      AccessKind == AK_Increment ? 1 : -1))
4564       return false;
4565     LVal.moveInto(Subobj);
4566     return true;
4567   }
4568 };
4569 } // end anonymous namespace
4570 
4571 /// Perform an increment or decrement on LVal.
4572 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4573                          QualType LValType, bool IsIncrement, APValue *Old) {
4574   if (LVal.Designator.Invalid)
4575     return false;
4576 
4577   if (!Info.getLangOpts().CPlusPlus14) {
4578     Info.FFDiag(E);
4579     return false;
4580   }
4581 
4582   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4583   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4584   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4585   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4586 }
4587 
4588 /// Build an lvalue for the object argument of a member function call.
4589 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4590                                    LValue &This) {
4591   if (Object->getType()->isPointerType() && Object->isPRValue())
4592     return EvaluatePointer(Object, This, Info);
4593 
4594   if (Object->isGLValue())
4595     return EvaluateLValue(Object, This, Info);
4596 
4597   if (Object->getType()->isLiteralType(Info.Ctx))
4598     return EvaluateTemporary(Object, This, Info);
4599 
4600   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4601   return false;
4602 }
4603 
4604 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4605 /// lvalue referring to the result.
4606 ///
4607 /// \param Info - Information about the ongoing evaluation.
4608 /// \param LV - An lvalue referring to the base of the member pointer.
4609 /// \param RHS - The member pointer expression.
4610 /// \param IncludeMember - Specifies whether the member itself is included in
4611 ///        the resulting LValue subobject designator. This is not possible when
4612 ///        creating a bound member function.
4613 /// \return The field or method declaration to which the member pointer refers,
4614 ///         or 0 if evaluation fails.
4615 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4616                                                   QualType LVType,
4617                                                   LValue &LV,
4618                                                   const Expr *RHS,
4619                                                   bool IncludeMember = true) {
4620   MemberPtr MemPtr;
4621   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4622     return nullptr;
4623 
4624   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4625   // member value, the behavior is undefined.
4626   if (!MemPtr.getDecl()) {
4627     // FIXME: Specific diagnostic.
4628     Info.FFDiag(RHS);
4629     return nullptr;
4630   }
4631 
4632   if (MemPtr.isDerivedMember()) {
4633     // This is a member of some derived class. Truncate LV appropriately.
4634     // The end of the derived-to-base path for the base object must match the
4635     // derived-to-base path for the member pointer.
4636     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4637         LV.Designator.Entries.size()) {
4638       Info.FFDiag(RHS);
4639       return nullptr;
4640     }
4641     unsigned PathLengthToMember =
4642         LV.Designator.Entries.size() - MemPtr.Path.size();
4643     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4644       const CXXRecordDecl *LVDecl = getAsBaseClass(
4645           LV.Designator.Entries[PathLengthToMember + I]);
4646       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4647       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4648         Info.FFDiag(RHS);
4649         return nullptr;
4650       }
4651     }
4652 
4653     // Truncate the lvalue to the appropriate derived class.
4654     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4655                             PathLengthToMember))
4656       return nullptr;
4657   } else if (!MemPtr.Path.empty()) {
4658     // Extend the LValue path with the member pointer's path.
4659     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4660                                   MemPtr.Path.size() + IncludeMember);
4661 
4662     // Walk down to the appropriate base class.
4663     if (const PointerType *PT = LVType->getAs<PointerType>())
4664       LVType = PT->getPointeeType();
4665     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4666     assert(RD && "member pointer access on non-class-type expression");
4667     // The first class in the path is that of the lvalue.
4668     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4669       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4670       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4671         return nullptr;
4672       RD = Base;
4673     }
4674     // Finally cast to the class containing the member.
4675     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4676                                 MemPtr.getContainingRecord()))
4677       return nullptr;
4678   }
4679 
4680   // Add the member. Note that we cannot build bound member functions here.
4681   if (IncludeMember) {
4682     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4683       if (!HandleLValueMember(Info, RHS, LV, FD))
4684         return nullptr;
4685     } else if (const IndirectFieldDecl *IFD =
4686                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4687       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4688         return nullptr;
4689     } else {
4690       llvm_unreachable("can't construct reference to bound member function");
4691     }
4692   }
4693 
4694   return MemPtr.getDecl();
4695 }
4696 
4697 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4698                                                   const BinaryOperator *BO,
4699                                                   LValue &LV,
4700                                                   bool IncludeMember = true) {
4701   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4702 
4703   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4704     if (Info.noteFailure()) {
4705       MemberPtr MemPtr;
4706       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4707     }
4708     return nullptr;
4709   }
4710 
4711   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4712                                    BO->getRHS(), IncludeMember);
4713 }
4714 
4715 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4716 /// the provided lvalue, which currently refers to the base object.
4717 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4718                                     LValue &Result) {
4719   SubobjectDesignator &D = Result.Designator;
4720   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4721     return false;
4722 
4723   QualType TargetQT = E->getType();
4724   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4725     TargetQT = PT->getPointeeType();
4726 
4727   // Check this cast lands within the final derived-to-base subobject path.
4728   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4729     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4730       << D.MostDerivedType << TargetQT;
4731     return false;
4732   }
4733 
4734   // Check the type of the final cast. We don't need to check the path,
4735   // since a cast can only be formed if the path is unique.
4736   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4737   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4738   const CXXRecordDecl *FinalType;
4739   if (NewEntriesSize == D.MostDerivedPathLength)
4740     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4741   else
4742     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4743   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4744     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4745       << D.MostDerivedType << TargetQT;
4746     return false;
4747   }
4748 
4749   // Truncate the lvalue to the appropriate derived class.
4750   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4751 }
4752 
4753 /// Get the value to use for a default-initialized object of type T.
4754 /// Return false if it encounters something invalid.
4755 static bool getDefaultInitValue(QualType T, APValue &Result) {
4756   bool Success = true;
4757   if (auto *RD = T->getAsCXXRecordDecl()) {
4758     if (RD->isInvalidDecl()) {
4759       Result = APValue();
4760       return false;
4761     }
4762     if (RD->isUnion()) {
4763       Result = APValue((const FieldDecl *)nullptr);
4764       return true;
4765     }
4766     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4767                      std::distance(RD->field_begin(), RD->field_end()));
4768 
4769     unsigned Index = 0;
4770     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4771                                                   End = RD->bases_end();
4772          I != End; ++I, ++Index)
4773       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4774 
4775     for (const auto *I : RD->fields()) {
4776       if (I->isUnnamedBitfield())
4777         continue;
4778       Success &= getDefaultInitValue(I->getType(),
4779                                      Result.getStructField(I->getFieldIndex()));
4780     }
4781     return Success;
4782   }
4783 
4784   if (auto *AT =
4785           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4786     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4787     if (Result.hasArrayFiller())
4788       Success &=
4789           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4790 
4791     return Success;
4792   }
4793 
4794   Result = APValue::IndeterminateValue();
4795   return true;
4796 }
4797 
4798 namespace {
4799 enum EvalStmtResult {
4800   /// Evaluation failed.
4801   ESR_Failed,
4802   /// Hit a 'return' statement.
4803   ESR_Returned,
4804   /// Evaluation succeeded.
4805   ESR_Succeeded,
4806   /// Hit a 'continue' statement.
4807   ESR_Continue,
4808   /// Hit a 'break' statement.
4809   ESR_Break,
4810   /// Still scanning for 'case' or 'default' statement.
4811   ESR_CaseNotFound
4812 };
4813 }
4814 
4815 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4816   // We don't need to evaluate the initializer for a static local.
4817   if (!VD->hasLocalStorage())
4818     return true;
4819 
4820   LValue Result;
4821   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4822                                                    ScopeKind::Block, Result);
4823 
4824   const Expr *InitE = VD->getInit();
4825   if (!InitE) {
4826     if (VD->getType()->isDependentType())
4827       return Info.noteSideEffect();
4828     return getDefaultInitValue(VD->getType(), Val);
4829   }
4830   if (InitE->isValueDependent())
4831     return false;
4832 
4833   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4834     // Wipe out any partially-computed value, to allow tracking that this
4835     // evaluation failed.
4836     Val = APValue();
4837     return false;
4838   }
4839 
4840   return true;
4841 }
4842 
4843 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4844   bool OK = true;
4845 
4846   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4847     OK &= EvaluateVarDecl(Info, VD);
4848 
4849   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4850     for (auto *BD : DD->bindings())
4851       if (auto *VD = BD->getHoldingVar())
4852         OK &= EvaluateDecl(Info, VD);
4853 
4854   return OK;
4855 }
4856 
4857 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4858   assert(E->isValueDependent());
4859   if (Info.noteSideEffect())
4860     return true;
4861   assert(E->containsErrors() && "valid value-dependent expression should never "
4862                                 "reach invalid code path.");
4863   return false;
4864 }
4865 
4866 /// Evaluate a condition (either a variable declaration or an expression).
4867 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4868                          const Expr *Cond, bool &Result) {
4869   if (Cond->isValueDependent())
4870     return false;
4871   FullExpressionRAII Scope(Info);
4872   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4873     return false;
4874   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4875     return false;
4876   return Scope.destroy();
4877 }
4878 
4879 namespace {
4880 /// A location where the result (returned value) of evaluating a
4881 /// statement should be stored.
4882 struct StmtResult {
4883   /// The APValue that should be filled in with the returned value.
4884   APValue &Value;
4885   /// The location containing the result, if any (used to support RVO).
4886   const LValue *Slot;
4887 };
4888 
4889 struct TempVersionRAII {
4890   CallStackFrame &Frame;
4891 
4892   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4893     Frame.pushTempVersion();
4894   }
4895 
4896   ~TempVersionRAII() {
4897     Frame.popTempVersion();
4898   }
4899 };
4900 
4901 }
4902 
4903 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4904                                    const Stmt *S,
4905                                    const SwitchCase *SC = nullptr);
4906 
4907 /// Evaluate the body of a loop, and translate the result as appropriate.
4908 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4909                                        const Stmt *Body,
4910                                        const SwitchCase *Case = nullptr) {
4911   BlockScopeRAII Scope(Info);
4912 
4913   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4914   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4915     ESR = ESR_Failed;
4916 
4917   switch (ESR) {
4918   case ESR_Break:
4919     return ESR_Succeeded;
4920   case ESR_Succeeded:
4921   case ESR_Continue:
4922     return ESR_Continue;
4923   case ESR_Failed:
4924   case ESR_Returned:
4925   case ESR_CaseNotFound:
4926     return ESR;
4927   }
4928   llvm_unreachable("Invalid EvalStmtResult!");
4929 }
4930 
4931 /// Evaluate a switch statement.
4932 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4933                                      const SwitchStmt *SS) {
4934   BlockScopeRAII Scope(Info);
4935 
4936   // Evaluate the switch condition.
4937   APSInt Value;
4938   {
4939     if (const Stmt *Init = SS->getInit()) {
4940       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4941       if (ESR != ESR_Succeeded) {
4942         if (ESR != ESR_Failed && !Scope.destroy())
4943           ESR = ESR_Failed;
4944         return ESR;
4945       }
4946     }
4947 
4948     FullExpressionRAII CondScope(Info);
4949     if (SS->getConditionVariable() &&
4950         !EvaluateDecl(Info, SS->getConditionVariable()))
4951       return ESR_Failed;
4952     if (SS->getCond()->isValueDependent()) {
4953       if (!EvaluateDependentExpr(SS->getCond(), Info))
4954         return ESR_Failed;
4955     } else {
4956       if (!EvaluateInteger(SS->getCond(), Value, Info))
4957         return ESR_Failed;
4958     }
4959     if (!CondScope.destroy())
4960       return ESR_Failed;
4961   }
4962 
4963   // Find the switch case corresponding to the value of the condition.
4964   // FIXME: Cache this lookup.
4965   const SwitchCase *Found = nullptr;
4966   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4967        SC = SC->getNextSwitchCase()) {
4968     if (isa<DefaultStmt>(SC)) {
4969       Found = SC;
4970       continue;
4971     }
4972 
4973     const CaseStmt *CS = cast<CaseStmt>(SC);
4974     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4975     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4976                               : LHS;
4977     if (LHS <= Value && Value <= RHS) {
4978       Found = SC;
4979       break;
4980     }
4981   }
4982 
4983   if (!Found)
4984     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4985 
4986   // Search the switch body for the switch case and evaluate it from there.
4987   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4988   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4989     return ESR_Failed;
4990 
4991   switch (ESR) {
4992   case ESR_Break:
4993     return ESR_Succeeded;
4994   case ESR_Succeeded:
4995   case ESR_Continue:
4996   case ESR_Failed:
4997   case ESR_Returned:
4998     return ESR;
4999   case ESR_CaseNotFound:
5000     // This can only happen if the switch case is nested within a statement
5001     // expression. We have no intention of supporting that.
5002     Info.FFDiag(Found->getBeginLoc(),
5003                 diag::note_constexpr_stmt_expr_unsupported);
5004     return ESR_Failed;
5005   }
5006   llvm_unreachable("Invalid EvalStmtResult!");
5007 }
5008 
5009 // Evaluate a statement.
5010 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5011                                    const Stmt *S, const SwitchCase *Case) {
5012   if (!Info.nextStep(S))
5013     return ESR_Failed;
5014 
5015   // If we're hunting down a 'case' or 'default' label, recurse through
5016   // substatements until we hit the label.
5017   if (Case) {
5018     switch (S->getStmtClass()) {
5019     case Stmt::CompoundStmtClass:
5020       // FIXME: Precompute which substatement of a compound statement we
5021       // would jump to, and go straight there rather than performing a
5022       // linear scan each time.
5023     case Stmt::LabelStmtClass:
5024     case Stmt::AttributedStmtClass:
5025     case Stmt::DoStmtClass:
5026       break;
5027 
5028     case Stmt::CaseStmtClass:
5029     case Stmt::DefaultStmtClass:
5030       if (Case == S)
5031         Case = nullptr;
5032       break;
5033 
5034     case Stmt::IfStmtClass: {
5035       // FIXME: Precompute which side of an 'if' we would jump to, and go
5036       // straight there rather than scanning both sides.
5037       const IfStmt *IS = cast<IfStmt>(S);
5038 
5039       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5040       // preceded by our switch label.
5041       BlockScopeRAII Scope(Info);
5042 
5043       // Step into the init statement in case it brings an (uninitialized)
5044       // variable into scope.
5045       if (const Stmt *Init = IS->getInit()) {
5046         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5047         if (ESR != ESR_CaseNotFound) {
5048           assert(ESR != ESR_Succeeded);
5049           return ESR;
5050         }
5051       }
5052 
5053       // Condition variable must be initialized if it exists.
5054       // FIXME: We can skip evaluating the body if there's a condition
5055       // variable, as there can't be any case labels within it.
5056       // (The same is true for 'for' statements.)
5057 
5058       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5059       if (ESR == ESR_Failed)
5060         return ESR;
5061       if (ESR != ESR_CaseNotFound)
5062         return Scope.destroy() ? ESR : ESR_Failed;
5063       if (!IS->getElse())
5064         return ESR_CaseNotFound;
5065 
5066       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5067       if (ESR == ESR_Failed)
5068         return ESR;
5069       if (ESR != ESR_CaseNotFound)
5070         return Scope.destroy() ? ESR : ESR_Failed;
5071       return ESR_CaseNotFound;
5072     }
5073 
5074     case Stmt::WhileStmtClass: {
5075       EvalStmtResult ESR =
5076           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5077       if (ESR != ESR_Continue)
5078         return ESR;
5079       break;
5080     }
5081 
5082     case Stmt::ForStmtClass: {
5083       const ForStmt *FS = cast<ForStmt>(S);
5084       BlockScopeRAII Scope(Info);
5085 
5086       // Step into the init statement in case it brings an (uninitialized)
5087       // variable into scope.
5088       if (const Stmt *Init = FS->getInit()) {
5089         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5090         if (ESR != ESR_CaseNotFound) {
5091           assert(ESR != ESR_Succeeded);
5092           return ESR;
5093         }
5094       }
5095 
5096       EvalStmtResult ESR =
5097           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5098       if (ESR != ESR_Continue)
5099         return ESR;
5100       if (const auto *Inc = FS->getInc()) {
5101         if (Inc->isValueDependent()) {
5102           if (!EvaluateDependentExpr(Inc, Info))
5103             return ESR_Failed;
5104         } else {
5105           FullExpressionRAII IncScope(Info);
5106           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5107             return ESR_Failed;
5108         }
5109       }
5110       break;
5111     }
5112 
5113     case Stmt::DeclStmtClass: {
5114       // Start the lifetime of any uninitialized variables we encounter. They
5115       // might be used by the selected branch of the switch.
5116       const DeclStmt *DS = cast<DeclStmt>(S);
5117       for (const auto *D : DS->decls()) {
5118         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5119           if (VD->hasLocalStorage() && !VD->getInit())
5120             if (!EvaluateVarDecl(Info, VD))
5121               return ESR_Failed;
5122           // FIXME: If the variable has initialization that can't be jumped
5123           // over, bail out of any immediately-surrounding compound-statement
5124           // too. There can't be any case labels here.
5125         }
5126       }
5127       return ESR_CaseNotFound;
5128     }
5129 
5130     default:
5131       return ESR_CaseNotFound;
5132     }
5133   }
5134 
5135   switch (S->getStmtClass()) {
5136   default:
5137     if (const Expr *E = dyn_cast<Expr>(S)) {
5138       if (E->isValueDependent()) {
5139         if (!EvaluateDependentExpr(E, Info))
5140           return ESR_Failed;
5141       } else {
5142         // Don't bother evaluating beyond an expression-statement which couldn't
5143         // be evaluated.
5144         // FIXME: Do we need the FullExpressionRAII object here?
5145         // VisitExprWithCleanups should create one when necessary.
5146         FullExpressionRAII Scope(Info);
5147         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5148           return ESR_Failed;
5149       }
5150       return ESR_Succeeded;
5151     }
5152 
5153     Info.FFDiag(S->getBeginLoc());
5154     return ESR_Failed;
5155 
5156   case Stmt::NullStmtClass:
5157     return ESR_Succeeded;
5158 
5159   case Stmt::DeclStmtClass: {
5160     const DeclStmt *DS = cast<DeclStmt>(S);
5161     for (const auto *D : DS->decls()) {
5162       // Each declaration initialization is its own full-expression.
5163       FullExpressionRAII Scope(Info);
5164       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5165         return ESR_Failed;
5166       if (!Scope.destroy())
5167         return ESR_Failed;
5168     }
5169     return ESR_Succeeded;
5170   }
5171 
5172   case Stmt::ReturnStmtClass: {
5173     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5174     FullExpressionRAII Scope(Info);
5175     if (RetExpr && RetExpr->isValueDependent()) {
5176       EvaluateDependentExpr(RetExpr, Info);
5177       // We know we returned, but we don't know what the value is.
5178       return ESR_Failed;
5179     }
5180     if (RetExpr &&
5181         !(Result.Slot
5182               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5183               : Evaluate(Result.Value, Info, RetExpr)))
5184       return ESR_Failed;
5185     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5186   }
5187 
5188   case Stmt::CompoundStmtClass: {
5189     BlockScopeRAII Scope(Info);
5190 
5191     const CompoundStmt *CS = cast<CompoundStmt>(S);
5192     for (const auto *BI : CS->body()) {
5193       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5194       if (ESR == ESR_Succeeded)
5195         Case = nullptr;
5196       else if (ESR != ESR_CaseNotFound) {
5197         if (ESR != ESR_Failed && !Scope.destroy())
5198           return ESR_Failed;
5199         return ESR;
5200       }
5201     }
5202     if (Case)
5203       return ESR_CaseNotFound;
5204     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5205   }
5206 
5207   case Stmt::IfStmtClass: {
5208     const IfStmt *IS = cast<IfStmt>(S);
5209 
5210     // Evaluate the condition, as either a var decl or as an expression.
5211     BlockScopeRAII Scope(Info);
5212     if (const Stmt *Init = IS->getInit()) {
5213       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5214       if (ESR != ESR_Succeeded) {
5215         if (ESR != ESR_Failed && !Scope.destroy())
5216           return ESR_Failed;
5217         return ESR;
5218       }
5219     }
5220     bool Cond;
5221     if (IS->isConsteval())
5222       Cond = IS->isNonNegatedConsteval();
5223     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5224                            Cond))
5225       return ESR_Failed;
5226 
5227     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5228       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5229       if (ESR != ESR_Succeeded) {
5230         if (ESR != ESR_Failed && !Scope.destroy())
5231           return ESR_Failed;
5232         return ESR;
5233       }
5234     }
5235     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5236   }
5237 
5238   case Stmt::WhileStmtClass: {
5239     const WhileStmt *WS = cast<WhileStmt>(S);
5240     while (true) {
5241       BlockScopeRAII Scope(Info);
5242       bool Continue;
5243       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5244                         Continue))
5245         return ESR_Failed;
5246       if (!Continue)
5247         break;
5248 
5249       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5250       if (ESR != ESR_Continue) {
5251         if (ESR != ESR_Failed && !Scope.destroy())
5252           return ESR_Failed;
5253         return ESR;
5254       }
5255       if (!Scope.destroy())
5256         return ESR_Failed;
5257     }
5258     return ESR_Succeeded;
5259   }
5260 
5261   case Stmt::DoStmtClass: {
5262     const DoStmt *DS = cast<DoStmt>(S);
5263     bool Continue;
5264     do {
5265       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5266       if (ESR != ESR_Continue)
5267         return ESR;
5268       Case = nullptr;
5269 
5270       if (DS->getCond()->isValueDependent()) {
5271         EvaluateDependentExpr(DS->getCond(), Info);
5272         // Bailout as we don't know whether to keep going or terminate the loop.
5273         return ESR_Failed;
5274       }
5275       FullExpressionRAII CondScope(Info);
5276       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5277           !CondScope.destroy())
5278         return ESR_Failed;
5279     } while (Continue);
5280     return ESR_Succeeded;
5281   }
5282 
5283   case Stmt::ForStmtClass: {
5284     const ForStmt *FS = cast<ForStmt>(S);
5285     BlockScopeRAII ForScope(Info);
5286     if (FS->getInit()) {
5287       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5288       if (ESR != ESR_Succeeded) {
5289         if (ESR != ESR_Failed && !ForScope.destroy())
5290           return ESR_Failed;
5291         return ESR;
5292       }
5293     }
5294     while (true) {
5295       BlockScopeRAII IterScope(Info);
5296       bool Continue = true;
5297       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5298                                          FS->getCond(), Continue))
5299         return ESR_Failed;
5300       if (!Continue)
5301         break;
5302 
5303       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5304       if (ESR != ESR_Continue) {
5305         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5306           return ESR_Failed;
5307         return ESR;
5308       }
5309 
5310       if (const auto *Inc = FS->getInc()) {
5311         if (Inc->isValueDependent()) {
5312           if (!EvaluateDependentExpr(Inc, Info))
5313             return ESR_Failed;
5314         } else {
5315           FullExpressionRAII IncScope(Info);
5316           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5317             return ESR_Failed;
5318         }
5319       }
5320 
5321       if (!IterScope.destroy())
5322         return ESR_Failed;
5323     }
5324     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5325   }
5326 
5327   case Stmt::CXXForRangeStmtClass: {
5328     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5329     BlockScopeRAII Scope(Info);
5330 
5331     // Evaluate the init-statement if present.
5332     if (FS->getInit()) {
5333       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5334       if (ESR != ESR_Succeeded) {
5335         if (ESR != ESR_Failed && !Scope.destroy())
5336           return ESR_Failed;
5337         return ESR;
5338       }
5339     }
5340 
5341     // Initialize the __range variable.
5342     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5343     if (ESR != ESR_Succeeded) {
5344       if (ESR != ESR_Failed && !Scope.destroy())
5345         return ESR_Failed;
5346       return ESR;
5347     }
5348 
5349     // In error-recovery cases it's possible to get here even if we failed to
5350     // synthesize the __begin and __end variables.
5351     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5352       return ESR_Failed;
5353 
5354     // Create the __begin and __end iterators.
5355     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5356     if (ESR != ESR_Succeeded) {
5357       if (ESR != ESR_Failed && !Scope.destroy())
5358         return ESR_Failed;
5359       return ESR;
5360     }
5361     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5362     if (ESR != ESR_Succeeded) {
5363       if (ESR != ESR_Failed && !Scope.destroy())
5364         return ESR_Failed;
5365       return ESR;
5366     }
5367 
5368     while (true) {
5369       // Condition: __begin != __end.
5370       {
5371         if (FS->getCond()->isValueDependent()) {
5372           EvaluateDependentExpr(FS->getCond(), Info);
5373           // We don't know whether to keep going or terminate the loop.
5374           return ESR_Failed;
5375         }
5376         bool Continue = true;
5377         FullExpressionRAII CondExpr(Info);
5378         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5379           return ESR_Failed;
5380         if (!Continue)
5381           break;
5382       }
5383 
5384       // User's variable declaration, initialized by *__begin.
5385       BlockScopeRAII InnerScope(Info);
5386       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5387       if (ESR != ESR_Succeeded) {
5388         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5389           return ESR_Failed;
5390         return ESR;
5391       }
5392 
5393       // Loop body.
5394       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5395       if (ESR != ESR_Continue) {
5396         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5397           return ESR_Failed;
5398         return ESR;
5399       }
5400       if (FS->getInc()->isValueDependent()) {
5401         if (!EvaluateDependentExpr(FS->getInc(), Info))
5402           return ESR_Failed;
5403       } else {
5404         // Increment: ++__begin
5405         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5406           return ESR_Failed;
5407       }
5408 
5409       if (!InnerScope.destroy())
5410         return ESR_Failed;
5411     }
5412 
5413     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5414   }
5415 
5416   case Stmt::SwitchStmtClass:
5417     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5418 
5419   case Stmt::ContinueStmtClass:
5420     return ESR_Continue;
5421 
5422   case Stmt::BreakStmtClass:
5423     return ESR_Break;
5424 
5425   case Stmt::LabelStmtClass:
5426     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5427 
5428   case Stmt::AttributedStmtClass:
5429     // As a general principle, C++11 attributes can be ignored without
5430     // any semantic impact.
5431     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5432                         Case);
5433 
5434   case Stmt::CaseStmtClass:
5435   case Stmt::DefaultStmtClass:
5436     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5437   case Stmt::CXXTryStmtClass:
5438     // Evaluate try blocks by evaluating all sub statements.
5439     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5440   }
5441 }
5442 
5443 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5444 /// default constructor. If so, we'll fold it whether or not it's marked as
5445 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5446 /// so we need special handling.
5447 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5448                                            const CXXConstructorDecl *CD,
5449                                            bool IsValueInitialization) {
5450   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5451     return false;
5452 
5453   // Value-initialization does not call a trivial default constructor, so such a
5454   // call is a core constant expression whether or not the constructor is
5455   // constexpr.
5456   if (!CD->isConstexpr() && !IsValueInitialization) {
5457     if (Info.getLangOpts().CPlusPlus11) {
5458       // FIXME: If DiagDecl is an implicitly-declared special member function,
5459       // we should be much more explicit about why it's not constexpr.
5460       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5461         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5462       Info.Note(CD->getLocation(), diag::note_declared_at);
5463     } else {
5464       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5465     }
5466   }
5467   return true;
5468 }
5469 
5470 /// CheckConstexprFunction - Check that a function can be called in a constant
5471 /// expression.
5472 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5473                                    const FunctionDecl *Declaration,
5474                                    const FunctionDecl *Definition,
5475                                    const Stmt *Body) {
5476   // Potential constant expressions can contain calls to declared, but not yet
5477   // defined, constexpr functions.
5478   if (Info.checkingPotentialConstantExpression() && !Definition &&
5479       Declaration->isConstexpr())
5480     return false;
5481 
5482   // Bail out if the function declaration itself is invalid.  We will
5483   // have produced a relevant diagnostic while parsing it, so just
5484   // note the problematic sub-expression.
5485   if (Declaration->isInvalidDecl()) {
5486     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5487     return false;
5488   }
5489 
5490   // DR1872: An instantiated virtual constexpr function can't be called in a
5491   // constant expression (prior to C++20). We can still constant-fold such a
5492   // call.
5493   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5494       cast<CXXMethodDecl>(Declaration)->isVirtual())
5495     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5496 
5497   if (Definition && Definition->isInvalidDecl()) {
5498     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5499     return false;
5500   }
5501 
5502   // Can we evaluate this function call?
5503   if (Definition && Definition->isConstexpr() && Body)
5504     return true;
5505 
5506   if (Info.getLangOpts().CPlusPlus11) {
5507     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5508 
5509     // If this function is not constexpr because it is an inherited
5510     // non-constexpr constructor, diagnose that directly.
5511     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5512     if (CD && CD->isInheritingConstructor()) {
5513       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5514       if (!Inherited->isConstexpr())
5515         DiagDecl = CD = Inherited;
5516     }
5517 
5518     // FIXME: If DiagDecl is an implicitly-declared special member function
5519     // or an inheriting constructor, we should be much more explicit about why
5520     // it's not constexpr.
5521     if (CD && CD->isInheritingConstructor())
5522       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5523         << CD->getInheritedConstructor().getConstructor()->getParent();
5524     else
5525       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5526         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5527     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5528   } else {
5529     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5530   }
5531   return false;
5532 }
5533 
5534 namespace {
5535 struct CheckDynamicTypeHandler {
5536   AccessKinds AccessKind;
5537   typedef bool result_type;
5538   bool failed() { return false; }
5539   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5540   bool found(APSInt &Value, QualType SubobjType) { return true; }
5541   bool found(APFloat &Value, QualType SubobjType) { return true; }
5542 };
5543 } // end anonymous namespace
5544 
5545 /// Check that we can access the notional vptr of an object / determine its
5546 /// dynamic type.
5547 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5548                              AccessKinds AK, bool Polymorphic) {
5549   if (This.Designator.Invalid)
5550     return false;
5551 
5552   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5553 
5554   if (!Obj)
5555     return false;
5556 
5557   if (!Obj.Value) {
5558     // The object is not usable in constant expressions, so we can't inspect
5559     // its value to see if it's in-lifetime or what the active union members
5560     // are. We can still check for a one-past-the-end lvalue.
5561     if (This.Designator.isOnePastTheEnd() ||
5562         This.Designator.isMostDerivedAnUnsizedArray()) {
5563       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5564                          ? diag::note_constexpr_access_past_end
5565                          : diag::note_constexpr_access_unsized_array)
5566           << AK;
5567       return false;
5568     } else if (Polymorphic) {
5569       // Conservatively refuse to perform a polymorphic operation if we would
5570       // not be able to read a notional 'vptr' value.
5571       APValue Val;
5572       This.moveInto(Val);
5573       QualType StarThisType =
5574           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5575       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5576           << AK << Val.getAsString(Info.Ctx, StarThisType);
5577       return false;
5578     }
5579     return true;
5580   }
5581 
5582   CheckDynamicTypeHandler Handler{AK};
5583   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5584 }
5585 
5586 /// Check that the pointee of the 'this' pointer in a member function call is
5587 /// either within its lifetime or in its period of construction or destruction.
5588 static bool
5589 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5590                                      const LValue &This,
5591                                      const CXXMethodDecl *NamedMember) {
5592   return checkDynamicType(
5593       Info, E, This,
5594       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5595 }
5596 
5597 struct DynamicType {
5598   /// The dynamic class type of the object.
5599   const CXXRecordDecl *Type;
5600   /// The corresponding path length in the lvalue.
5601   unsigned PathLength;
5602 };
5603 
5604 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5605                                              unsigned PathLength) {
5606   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5607       Designator.Entries.size() && "invalid path length");
5608   return (PathLength == Designator.MostDerivedPathLength)
5609              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5610              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5611 }
5612 
5613 /// Determine the dynamic type of an object.
5614 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5615                                                 LValue &This, AccessKinds AK) {
5616   // If we don't have an lvalue denoting an object of class type, there is no
5617   // meaningful dynamic type. (We consider objects of non-class type to have no
5618   // dynamic type.)
5619   if (!checkDynamicType(Info, E, This, AK, true))
5620     return None;
5621 
5622   // Refuse to compute a dynamic type in the presence of virtual bases. This
5623   // shouldn't happen other than in constant-folding situations, since literal
5624   // types can't have virtual bases.
5625   //
5626   // Note that consumers of DynamicType assume that the type has no virtual
5627   // bases, and will need modifications if this restriction is relaxed.
5628   const CXXRecordDecl *Class =
5629       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5630   if (!Class || Class->getNumVBases()) {
5631     Info.FFDiag(E);
5632     return None;
5633   }
5634 
5635   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5636   // binary search here instead. But the overwhelmingly common case is that
5637   // we're not in the middle of a constructor, so it probably doesn't matter
5638   // in practice.
5639   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5640   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5641        PathLength <= Path.size(); ++PathLength) {
5642     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5643                                       Path.slice(0, PathLength))) {
5644     case ConstructionPhase::Bases:
5645     case ConstructionPhase::DestroyingBases:
5646       // We're constructing or destroying a base class. This is not the dynamic
5647       // type.
5648       break;
5649 
5650     case ConstructionPhase::None:
5651     case ConstructionPhase::AfterBases:
5652     case ConstructionPhase::AfterFields:
5653     case ConstructionPhase::Destroying:
5654       // We've finished constructing the base classes and not yet started
5655       // destroying them again, so this is the dynamic type.
5656       return DynamicType{getBaseClassType(This.Designator, PathLength),
5657                          PathLength};
5658     }
5659   }
5660 
5661   // CWG issue 1517: we're constructing a base class of the object described by
5662   // 'This', so that object has not yet begun its period of construction and
5663   // any polymorphic operation on it results in undefined behavior.
5664   Info.FFDiag(E);
5665   return None;
5666 }
5667 
5668 /// Perform virtual dispatch.
5669 static const CXXMethodDecl *HandleVirtualDispatch(
5670     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5671     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5672   Optional<DynamicType> DynType = ComputeDynamicType(
5673       Info, E, This,
5674       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5675   if (!DynType)
5676     return nullptr;
5677 
5678   // Find the final overrider. It must be declared in one of the classes on the
5679   // path from the dynamic type to the static type.
5680   // FIXME: If we ever allow literal types to have virtual base classes, that
5681   // won't be true.
5682   const CXXMethodDecl *Callee = Found;
5683   unsigned PathLength = DynType->PathLength;
5684   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5685     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5686     const CXXMethodDecl *Overrider =
5687         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5688     if (Overrider) {
5689       Callee = Overrider;
5690       break;
5691     }
5692   }
5693 
5694   // C++2a [class.abstract]p6:
5695   //   the effect of making a virtual call to a pure virtual function [...] is
5696   //   undefined
5697   if (Callee->isPure()) {
5698     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5699     Info.Note(Callee->getLocation(), diag::note_declared_at);
5700     return nullptr;
5701   }
5702 
5703   // If necessary, walk the rest of the path to determine the sequence of
5704   // covariant adjustment steps to apply.
5705   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5706                                        Found->getReturnType())) {
5707     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5708     for (unsigned CovariantPathLength = PathLength + 1;
5709          CovariantPathLength != This.Designator.Entries.size();
5710          ++CovariantPathLength) {
5711       const CXXRecordDecl *NextClass =
5712           getBaseClassType(This.Designator, CovariantPathLength);
5713       const CXXMethodDecl *Next =
5714           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5715       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5716                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5717         CovariantAdjustmentPath.push_back(Next->getReturnType());
5718     }
5719     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5720                                          CovariantAdjustmentPath.back()))
5721       CovariantAdjustmentPath.push_back(Found->getReturnType());
5722   }
5723 
5724   // Perform 'this' adjustment.
5725   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5726     return nullptr;
5727 
5728   return Callee;
5729 }
5730 
5731 /// Perform the adjustment from a value returned by a virtual function to
5732 /// a value of the statically expected type, which may be a pointer or
5733 /// reference to a base class of the returned type.
5734 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5735                                             APValue &Result,
5736                                             ArrayRef<QualType> Path) {
5737   assert(Result.isLValue() &&
5738          "unexpected kind of APValue for covariant return");
5739   if (Result.isNullPointer())
5740     return true;
5741 
5742   LValue LVal;
5743   LVal.setFrom(Info.Ctx, Result);
5744 
5745   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5746   for (unsigned I = 1; I != Path.size(); ++I) {
5747     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5748     assert(OldClass && NewClass && "unexpected kind of covariant return");
5749     if (OldClass != NewClass &&
5750         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5751       return false;
5752     OldClass = NewClass;
5753   }
5754 
5755   LVal.moveInto(Result);
5756   return true;
5757 }
5758 
5759 /// Determine whether \p Base, which is known to be a direct base class of
5760 /// \p Derived, is a public base class.
5761 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5762                               const CXXRecordDecl *Base) {
5763   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5764     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5765     if (BaseClass && declaresSameEntity(BaseClass, Base))
5766       return BaseSpec.getAccessSpecifier() == AS_public;
5767   }
5768   llvm_unreachable("Base is not a direct base of Derived");
5769 }
5770 
5771 /// Apply the given dynamic cast operation on the provided lvalue.
5772 ///
5773 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5774 /// to find a suitable target subobject.
5775 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5776                               LValue &Ptr) {
5777   // We can't do anything with a non-symbolic pointer value.
5778   SubobjectDesignator &D = Ptr.Designator;
5779   if (D.Invalid)
5780     return false;
5781 
5782   // C++ [expr.dynamic.cast]p6:
5783   //   If v is a null pointer value, the result is a null pointer value.
5784   if (Ptr.isNullPointer() && !E->isGLValue())
5785     return true;
5786 
5787   // For all the other cases, we need the pointer to point to an object within
5788   // its lifetime / period of construction / destruction, and we need to know
5789   // its dynamic type.
5790   Optional<DynamicType> DynType =
5791       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5792   if (!DynType)
5793     return false;
5794 
5795   // C++ [expr.dynamic.cast]p7:
5796   //   If T is "pointer to cv void", then the result is a pointer to the most
5797   //   derived object
5798   if (E->getType()->isVoidPointerType())
5799     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5800 
5801   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5802   assert(C && "dynamic_cast target is not void pointer nor class");
5803   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5804 
5805   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5806     // C++ [expr.dynamic.cast]p9:
5807     if (!E->isGLValue()) {
5808       //   The value of a failed cast to pointer type is the null pointer value
5809       //   of the required result type.
5810       Ptr.setNull(Info.Ctx, E->getType());
5811       return true;
5812     }
5813 
5814     //   A failed cast to reference type throws [...] std::bad_cast.
5815     unsigned DiagKind;
5816     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5817                    DynType->Type->isDerivedFrom(C)))
5818       DiagKind = 0;
5819     else if (!Paths || Paths->begin() == Paths->end())
5820       DiagKind = 1;
5821     else if (Paths->isAmbiguous(CQT))
5822       DiagKind = 2;
5823     else {
5824       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5825       DiagKind = 3;
5826     }
5827     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5828         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5829         << Info.Ctx.getRecordType(DynType->Type)
5830         << E->getType().getUnqualifiedType();
5831     return false;
5832   };
5833 
5834   // Runtime check, phase 1:
5835   //   Walk from the base subobject towards the derived object looking for the
5836   //   target type.
5837   for (int PathLength = Ptr.Designator.Entries.size();
5838        PathLength >= (int)DynType->PathLength; --PathLength) {
5839     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5840     if (declaresSameEntity(Class, C))
5841       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5842     // We can only walk across public inheritance edges.
5843     if (PathLength > (int)DynType->PathLength &&
5844         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5845                            Class))
5846       return RuntimeCheckFailed(nullptr);
5847   }
5848 
5849   // Runtime check, phase 2:
5850   //   Search the dynamic type for an unambiguous public base of type C.
5851   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5852                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5853   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5854       Paths.front().Access == AS_public) {
5855     // Downcast to the dynamic type...
5856     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5857       return false;
5858     // ... then upcast to the chosen base class subobject.
5859     for (CXXBasePathElement &Elem : Paths.front())
5860       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5861         return false;
5862     return true;
5863   }
5864 
5865   // Otherwise, the runtime check fails.
5866   return RuntimeCheckFailed(&Paths);
5867 }
5868 
5869 namespace {
5870 struct StartLifetimeOfUnionMemberHandler {
5871   EvalInfo &Info;
5872   const Expr *LHSExpr;
5873   const FieldDecl *Field;
5874   bool DuringInit;
5875   bool Failed = false;
5876   static const AccessKinds AccessKind = AK_Assign;
5877 
5878   typedef bool result_type;
5879   bool failed() { return Failed; }
5880   bool found(APValue &Subobj, QualType SubobjType) {
5881     // We are supposed to perform no initialization but begin the lifetime of
5882     // the object. We interpret that as meaning to do what default
5883     // initialization of the object would do if all constructors involved were
5884     // trivial:
5885     //  * All base, non-variant member, and array element subobjects' lifetimes
5886     //    begin
5887     //  * No variant members' lifetimes begin
5888     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5889     assert(SubobjType->isUnionType());
5890     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5891       // This union member is already active. If it's also in-lifetime, there's
5892       // nothing to do.
5893       if (Subobj.getUnionValue().hasValue())
5894         return true;
5895     } else if (DuringInit) {
5896       // We're currently in the process of initializing a different union
5897       // member.  If we carried on, that initialization would attempt to
5898       // store to an inactive union member, resulting in undefined behavior.
5899       Info.FFDiag(LHSExpr,
5900                   diag::note_constexpr_union_member_change_during_init);
5901       return false;
5902     }
5903     APValue Result;
5904     Failed = !getDefaultInitValue(Field->getType(), Result);
5905     Subobj.setUnion(Field, Result);
5906     return true;
5907   }
5908   bool found(APSInt &Value, QualType SubobjType) {
5909     llvm_unreachable("wrong value kind for union object");
5910   }
5911   bool found(APFloat &Value, QualType SubobjType) {
5912     llvm_unreachable("wrong value kind for union object");
5913   }
5914 };
5915 } // end anonymous namespace
5916 
5917 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5918 
5919 /// Handle a builtin simple-assignment or a call to a trivial assignment
5920 /// operator whose left-hand side might involve a union member access. If it
5921 /// does, implicitly start the lifetime of any accessed union elements per
5922 /// C++20 [class.union]5.
5923 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5924                                           const LValue &LHS) {
5925   if (LHS.InvalidBase || LHS.Designator.Invalid)
5926     return false;
5927 
5928   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5929   // C++ [class.union]p5:
5930   //   define the set S(E) of subexpressions of E as follows:
5931   unsigned PathLength = LHS.Designator.Entries.size();
5932   for (const Expr *E = LHSExpr; E != nullptr;) {
5933     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5934     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5935       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5936       // Note that we can't implicitly start the lifetime of a reference,
5937       // so we don't need to proceed any further if we reach one.
5938       if (!FD || FD->getType()->isReferenceType())
5939         break;
5940 
5941       //    ... and also contains A.B if B names a union member ...
5942       if (FD->getParent()->isUnion()) {
5943         //    ... of a non-class, non-array type, or of a class type with a
5944         //    trivial default constructor that is not deleted, or an array of
5945         //    such types.
5946         auto *RD =
5947             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5948         if (!RD || RD->hasTrivialDefaultConstructor())
5949           UnionPathLengths.push_back({PathLength - 1, FD});
5950       }
5951 
5952       E = ME->getBase();
5953       --PathLength;
5954       assert(declaresSameEntity(FD,
5955                                 LHS.Designator.Entries[PathLength]
5956                                     .getAsBaseOrMember().getPointer()));
5957 
5958       //   -- If E is of the form A[B] and is interpreted as a built-in array
5959       //      subscripting operator, S(E) is [S(the array operand, if any)].
5960     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5961       // Step over an ArrayToPointerDecay implicit cast.
5962       auto *Base = ASE->getBase()->IgnoreImplicit();
5963       if (!Base->getType()->isArrayType())
5964         break;
5965 
5966       E = Base;
5967       --PathLength;
5968 
5969     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5970       // Step over a derived-to-base conversion.
5971       E = ICE->getSubExpr();
5972       if (ICE->getCastKind() == CK_NoOp)
5973         continue;
5974       if (ICE->getCastKind() != CK_DerivedToBase &&
5975           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5976         break;
5977       // Walk path backwards as we walk up from the base to the derived class.
5978       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5979         --PathLength;
5980         (void)Elt;
5981         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5982                                   LHS.Designator.Entries[PathLength]
5983                                       .getAsBaseOrMember().getPointer()));
5984       }
5985 
5986     //   -- Otherwise, S(E) is empty.
5987     } else {
5988       break;
5989     }
5990   }
5991 
5992   // Common case: no unions' lifetimes are started.
5993   if (UnionPathLengths.empty())
5994     return true;
5995 
5996   //   if modification of X [would access an inactive union member], an object
5997   //   of the type of X is implicitly created
5998   CompleteObject Obj =
5999       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6000   if (!Obj)
6001     return false;
6002   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6003            llvm::reverse(UnionPathLengths)) {
6004     // Form a designator for the union object.
6005     SubobjectDesignator D = LHS.Designator;
6006     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6007 
6008     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6009                       ConstructionPhase::AfterBases;
6010     StartLifetimeOfUnionMemberHandler StartLifetime{
6011         Info, LHSExpr, LengthAndField.second, DuringInit};
6012     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6013       return false;
6014   }
6015 
6016   return true;
6017 }
6018 
6019 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6020                             CallRef Call, EvalInfo &Info,
6021                             bool NonNull = false) {
6022   LValue LV;
6023   // Create the parameter slot and register its destruction. For a vararg
6024   // argument, create a temporary.
6025   // FIXME: For calling conventions that destroy parameters in the callee,
6026   // should we consider performing destruction when the function returns
6027   // instead?
6028   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6029                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6030                                                        ScopeKind::Call, LV);
6031   if (!EvaluateInPlace(V, Info, LV, Arg))
6032     return false;
6033 
6034   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6035   // undefined behavior, so is non-constant.
6036   if (NonNull && V.isLValue() && V.isNullPointer()) {
6037     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6038     return false;
6039   }
6040 
6041   return true;
6042 }
6043 
6044 /// Evaluate the arguments to a function call.
6045 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6046                          EvalInfo &Info, const FunctionDecl *Callee,
6047                          bool RightToLeft = false) {
6048   bool Success = true;
6049   llvm::SmallBitVector ForbiddenNullArgs;
6050   if (Callee->hasAttr<NonNullAttr>()) {
6051     ForbiddenNullArgs.resize(Args.size());
6052     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6053       if (!Attr->args_size()) {
6054         ForbiddenNullArgs.set();
6055         break;
6056       } else
6057         for (auto Idx : Attr->args()) {
6058           unsigned ASTIdx = Idx.getASTIndex();
6059           if (ASTIdx >= Args.size())
6060             continue;
6061           ForbiddenNullArgs[ASTIdx] = true;
6062         }
6063     }
6064   }
6065   for (unsigned I = 0; I < Args.size(); I++) {
6066     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6067     const ParmVarDecl *PVD =
6068         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6069     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6070     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6071       // If we're checking for a potential constant expression, evaluate all
6072       // initializers even if some of them fail.
6073       if (!Info.noteFailure())
6074         return false;
6075       Success = false;
6076     }
6077   }
6078   return Success;
6079 }
6080 
6081 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6082 /// constructor or assignment operator.
6083 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6084                               const Expr *E, APValue &Result,
6085                               bool CopyObjectRepresentation) {
6086   // Find the reference argument.
6087   CallStackFrame *Frame = Info.CurrentCall;
6088   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6089   if (!RefValue) {
6090     Info.FFDiag(E);
6091     return false;
6092   }
6093 
6094   // Copy out the contents of the RHS object.
6095   LValue RefLValue;
6096   RefLValue.setFrom(Info.Ctx, *RefValue);
6097   return handleLValueToRValueConversion(
6098       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6099       CopyObjectRepresentation);
6100 }
6101 
6102 /// Evaluate a function call.
6103 static bool HandleFunctionCall(SourceLocation CallLoc,
6104                                const FunctionDecl *Callee, const LValue *This,
6105                                ArrayRef<const Expr *> Args, CallRef Call,
6106                                const Stmt *Body, EvalInfo &Info,
6107                                APValue &Result, const LValue *ResultSlot) {
6108   if (!Info.CheckCallLimit(CallLoc))
6109     return false;
6110 
6111   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6112 
6113   // For a trivial copy or move assignment, perform an APValue copy. This is
6114   // essential for unions, where the operations performed by the assignment
6115   // operator cannot be represented as statements.
6116   //
6117   // Skip this for non-union classes with no fields; in that case, the defaulted
6118   // copy/move does not actually read the object.
6119   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6120   if (MD && MD->isDefaulted() &&
6121       (MD->getParent()->isUnion() ||
6122        (MD->isTrivial() &&
6123         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6124     assert(This &&
6125            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6126     APValue RHSValue;
6127     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6128                            MD->getParent()->isUnion()))
6129       return false;
6130     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6131                           RHSValue))
6132       return false;
6133     This->moveInto(Result);
6134     return true;
6135   } else if (MD && isLambdaCallOperator(MD)) {
6136     // We're in a lambda; determine the lambda capture field maps unless we're
6137     // just constexpr checking a lambda's call operator. constexpr checking is
6138     // done before the captures have been added to the closure object (unless
6139     // we're inferring constexpr-ness), so we don't have access to them in this
6140     // case. But since we don't need the captures to constexpr check, we can
6141     // just ignore them.
6142     if (!Info.checkingPotentialConstantExpression())
6143       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6144                                         Frame.LambdaThisCaptureField);
6145   }
6146 
6147   StmtResult Ret = {Result, ResultSlot};
6148   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6149   if (ESR == ESR_Succeeded) {
6150     if (Callee->getReturnType()->isVoidType())
6151       return true;
6152     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6153   }
6154   return ESR == ESR_Returned;
6155 }
6156 
6157 /// Evaluate a constructor call.
6158 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6159                                   CallRef Call,
6160                                   const CXXConstructorDecl *Definition,
6161                                   EvalInfo &Info, APValue &Result) {
6162   SourceLocation CallLoc = E->getExprLoc();
6163   if (!Info.CheckCallLimit(CallLoc))
6164     return false;
6165 
6166   const CXXRecordDecl *RD = Definition->getParent();
6167   if (RD->getNumVBases()) {
6168     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6169     return false;
6170   }
6171 
6172   EvalInfo::EvaluatingConstructorRAII EvalObj(
6173       Info,
6174       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6175       RD->getNumBases());
6176   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6177 
6178   // FIXME: Creating an APValue just to hold a nonexistent return value is
6179   // wasteful.
6180   APValue RetVal;
6181   StmtResult Ret = {RetVal, nullptr};
6182 
6183   // If it's a delegating constructor, delegate.
6184   if (Definition->isDelegatingConstructor()) {
6185     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6186     if ((*I)->getInit()->isValueDependent()) {
6187       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6188         return false;
6189     } else {
6190       FullExpressionRAII InitScope(Info);
6191       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6192           !InitScope.destroy())
6193         return false;
6194     }
6195     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6196   }
6197 
6198   // For a trivial copy or move constructor, perform an APValue copy. This is
6199   // essential for unions (or classes with anonymous union members), where the
6200   // operations performed by the constructor cannot be represented by
6201   // ctor-initializers.
6202   //
6203   // Skip this for empty non-union classes; we should not perform an
6204   // lvalue-to-rvalue conversion on them because their copy constructor does not
6205   // actually read them.
6206   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6207       (Definition->getParent()->isUnion() ||
6208        (Definition->isTrivial() &&
6209         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6210     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6211                              Definition->getParent()->isUnion());
6212   }
6213 
6214   // Reserve space for the struct members.
6215   if (!Result.hasValue()) {
6216     if (!RD->isUnion())
6217       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6218                        std::distance(RD->field_begin(), RD->field_end()));
6219     else
6220       // A union starts with no active member.
6221       Result = APValue((const FieldDecl*)nullptr);
6222   }
6223 
6224   if (RD->isInvalidDecl()) return false;
6225   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6226 
6227   // A scope for temporaries lifetime-extended by reference members.
6228   BlockScopeRAII LifetimeExtendedScope(Info);
6229 
6230   bool Success = true;
6231   unsigned BasesSeen = 0;
6232 #ifndef NDEBUG
6233   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6234 #endif
6235   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6236   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6237     // We might be initializing the same field again if this is an indirect
6238     // field initialization.
6239     if (FieldIt == RD->field_end() ||
6240         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6241       assert(Indirect && "fields out of order?");
6242       return;
6243     }
6244 
6245     // Default-initialize any fields with no explicit initializer.
6246     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6247       assert(FieldIt != RD->field_end() && "missing field?");
6248       if (!FieldIt->isUnnamedBitfield())
6249         Success &= getDefaultInitValue(
6250             FieldIt->getType(),
6251             Result.getStructField(FieldIt->getFieldIndex()));
6252     }
6253     ++FieldIt;
6254   };
6255   for (const auto *I : Definition->inits()) {
6256     LValue Subobject = This;
6257     LValue SubobjectParent = This;
6258     APValue *Value = &Result;
6259 
6260     // Determine the subobject to initialize.
6261     FieldDecl *FD = nullptr;
6262     if (I->isBaseInitializer()) {
6263       QualType BaseType(I->getBaseClass(), 0);
6264 #ifndef NDEBUG
6265       // Non-virtual base classes are initialized in the order in the class
6266       // definition. We have already checked for virtual base classes.
6267       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6268       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6269              "base class initializers not in expected order");
6270       ++BaseIt;
6271 #endif
6272       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6273                                   BaseType->getAsCXXRecordDecl(), &Layout))
6274         return false;
6275       Value = &Result.getStructBase(BasesSeen++);
6276     } else if ((FD = I->getMember())) {
6277       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6278         return false;
6279       if (RD->isUnion()) {
6280         Result = APValue(FD);
6281         Value = &Result.getUnionValue();
6282       } else {
6283         SkipToField(FD, false);
6284         Value = &Result.getStructField(FD->getFieldIndex());
6285       }
6286     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6287       // Walk the indirect field decl's chain to find the object to initialize,
6288       // and make sure we've initialized every step along it.
6289       auto IndirectFieldChain = IFD->chain();
6290       for (auto *C : IndirectFieldChain) {
6291         FD = cast<FieldDecl>(C);
6292         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6293         // Switch the union field if it differs. This happens if we had
6294         // preceding zero-initialization, and we're now initializing a union
6295         // subobject other than the first.
6296         // FIXME: In this case, the values of the other subobjects are
6297         // specified, since zero-initialization sets all padding bits to zero.
6298         if (!Value->hasValue() ||
6299             (Value->isUnion() && Value->getUnionField() != FD)) {
6300           if (CD->isUnion())
6301             *Value = APValue(FD);
6302           else
6303             // FIXME: This immediately starts the lifetime of all members of
6304             // an anonymous struct. It would be preferable to strictly start
6305             // member lifetime in initialization order.
6306             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6307         }
6308         // Store Subobject as its parent before updating it for the last element
6309         // in the chain.
6310         if (C == IndirectFieldChain.back())
6311           SubobjectParent = Subobject;
6312         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6313           return false;
6314         if (CD->isUnion())
6315           Value = &Value->getUnionValue();
6316         else {
6317           if (C == IndirectFieldChain.front() && !RD->isUnion())
6318             SkipToField(FD, true);
6319           Value = &Value->getStructField(FD->getFieldIndex());
6320         }
6321       }
6322     } else {
6323       llvm_unreachable("unknown base initializer kind");
6324     }
6325 
6326     // Need to override This for implicit field initializers as in this case
6327     // This refers to innermost anonymous struct/union containing initializer,
6328     // not to currently constructed class.
6329     const Expr *Init = I->getInit();
6330     if (Init->isValueDependent()) {
6331       if (!EvaluateDependentExpr(Init, Info))
6332         return false;
6333     } else {
6334       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6335                                     isa<CXXDefaultInitExpr>(Init));
6336       FullExpressionRAII InitScope(Info);
6337       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6338           (FD && FD->isBitField() &&
6339            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6340         // If we're checking for a potential constant expression, evaluate all
6341         // initializers even if some of them fail.
6342         if (!Info.noteFailure())
6343           return false;
6344         Success = false;
6345       }
6346     }
6347 
6348     // This is the point at which the dynamic type of the object becomes this
6349     // class type.
6350     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6351       EvalObj.finishedConstructingBases();
6352   }
6353 
6354   // Default-initialize any remaining fields.
6355   if (!RD->isUnion()) {
6356     for (; FieldIt != RD->field_end(); ++FieldIt) {
6357       if (!FieldIt->isUnnamedBitfield())
6358         Success &= getDefaultInitValue(
6359             FieldIt->getType(),
6360             Result.getStructField(FieldIt->getFieldIndex()));
6361     }
6362   }
6363 
6364   EvalObj.finishedConstructingFields();
6365 
6366   return Success &&
6367          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6368          LifetimeExtendedScope.destroy();
6369 }
6370 
6371 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6372                                   ArrayRef<const Expr*> Args,
6373                                   const CXXConstructorDecl *Definition,
6374                                   EvalInfo &Info, APValue &Result) {
6375   CallScopeRAII CallScope(Info);
6376   CallRef Call = Info.CurrentCall->createCall(Definition);
6377   if (!EvaluateArgs(Args, Call, Info, Definition))
6378     return false;
6379 
6380   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6381          CallScope.destroy();
6382 }
6383 
6384 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6385                                   const LValue &This, APValue &Value,
6386                                   QualType T) {
6387   // Objects can only be destroyed while they're within their lifetimes.
6388   // FIXME: We have no representation for whether an object of type nullptr_t
6389   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6390   // as indeterminate instead?
6391   if (Value.isAbsent() && !T->isNullPtrType()) {
6392     APValue Printable;
6393     This.moveInto(Printable);
6394     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6395       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6396     return false;
6397   }
6398 
6399   // Invent an expression for location purposes.
6400   // FIXME: We shouldn't need to do this.
6401   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6402 
6403   // For arrays, destroy elements right-to-left.
6404   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6405     uint64_t Size = CAT->getSize().getZExtValue();
6406     QualType ElemT = CAT->getElementType();
6407 
6408     LValue ElemLV = This;
6409     ElemLV.addArray(Info, &LocE, CAT);
6410     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6411       return false;
6412 
6413     // Ensure that we have actual array elements available to destroy; the
6414     // destructors might mutate the value, so we can't run them on the array
6415     // filler.
6416     if (Size && Size > Value.getArrayInitializedElts())
6417       expandArray(Value, Value.getArraySize() - 1);
6418 
6419     for (; Size != 0; --Size) {
6420       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6421       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6422           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6423         return false;
6424     }
6425 
6426     // End the lifetime of this array now.
6427     Value = APValue();
6428     return true;
6429   }
6430 
6431   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6432   if (!RD) {
6433     if (T.isDestructedType()) {
6434       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6435       return false;
6436     }
6437 
6438     Value = APValue();
6439     return true;
6440   }
6441 
6442   if (RD->getNumVBases()) {
6443     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6444     return false;
6445   }
6446 
6447   const CXXDestructorDecl *DD = RD->getDestructor();
6448   if (!DD && !RD->hasTrivialDestructor()) {
6449     Info.FFDiag(CallLoc);
6450     return false;
6451   }
6452 
6453   if (!DD || DD->isTrivial() ||
6454       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6455     // A trivial destructor just ends the lifetime of the object. Check for
6456     // this case before checking for a body, because we might not bother
6457     // building a body for a trivial destructor. Note that it doesn't matter
6458     // whether the destructor is constexpr in this case; all trivial
6459     // destructors are constexpr.
6460     //
6461     // If an anonymous union would be destroyed, some enclosing destructor must
6462     // have been explicitly defined, and the anonymous union destruction should
6463     // have no effect.
6464     Value = APValue();
6465     return true;
6466   }
6467 
6468   if (!Info.CheckCallLimit(CallLoc))
6469     return false;
6470 
6471   const FunctionDecl *Definition = nullptr;
6472   const Stmt *Body = DD->getBody(Definition);
6473 
6474   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6475     return false;
6476 
6477   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6478 
6479   // We're now in the period of destruction of this object.
6480   unsigned BasesLeft = RD->getNumBases();
6481   EvalInfo::EvaluatingDestructorRAII EvalObj(
6482       Info,
6483       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6484   if (!EvalObj.DidInsert) {
6485     // C++2a [class.dtor]p19:
6486     //   the behavior is undefined if the destructor is invoked for an object
6487     //   whose lifetime has ended
6488     // (Note that formally the lifetime ends when the period of destruction
6489     // begins, even though certain uses of the object remain valid until the
6490     // period of destruction ends.)
6491     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6492     return false;
6493   }
6494 
6495   // FIXME: Creating an APValue just to hold a nonexistent return value is
6496   // wasteful.
6497   APValue RetVal;
6498   StmtResult Ret = {RetVal, nullptr};
6499   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6500     return false;
6501 
6502   // A union destructor does not implicitly destroy its members.
6503   if (RD->isUnion())
6504     return true;
6505 
6506   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6507 
6508   // We don't have a good way to iterate fields in reverse, so collect all the
6509   // fields first and then walk them backwards.
6510   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6511   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6512     if (FD->isUnnamedBitfield())
6513       continue;
6514 
6515     LValue Subobject = This;
6516     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6517       return false;
6518 
6519     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6520     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6521                                FD->getType()))
6522       return false;
6523   }
6524 
6525   if (BasesLeft != 0)
6526     EvalObj.startedDestroyingBases();
6527 
6528   // Destroy base classes in reverse order.
6529   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6530     --BasesLeft;
6531 
6532     QualType BaseType = Base.getType();
6533     LValue Subobject = This;
6534     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6535                                 BaseType->getAsCXXRecordDecl(), &Layout))
6536       return false;
6537 
6538     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6539     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6540                                BaseType))
6541       return false;
6542   }
6543   assert(BasesLeft == 0 && "NumBases was wrong?");
6544 
6545   // The period of destruction ends now. The object is gone.
6546   Value = APValue();
6547   return true;
6548 }
6549 
6550 namespace {
6551 struct DestroyObjectHandler {
6552   EvalInfo &Info;
6553   const Expr *E;
6554   const LValue &This;
6555   const AccessKinds AccessKind;
6556 
6557   typedef bool result_type;
6558   bool failed() { return false; }
6559   bool found(APValue &Subobj, QualType SubobjType) {
6560     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6561                                  SubobjType);
6562   }
6563   bool found(APSInt &Value, QualType SubobjType) {
6564     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6565     return false;
6566   }
6567   bool found(APFloat &Value, QualType SubobjType) {
6568     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6569     return false;
6570   }
6571 };
6572 }
6573 
6574 /// Perform a destructor or pseudo-destructor call on the given object, which
6575 /// might in general not be a complete object.
6576 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6577                               const LValue &This, QualType ThisType) {
6578   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6579   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6580   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6581 }
6582 
6583 /// Destroy and end the lifetime of the given complete object.
6584 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6585                               APValue::LValueBase LVBase, APValue &Value,
6586                               QualType T) {
6587   // If we've had an unmodeled side-effect, we can't rely on mutable state
6588   // (such as the object we're about to destroy) being correct.
6589   if (Info.EvalStatus.HasSideEffects)
6590     return false;
6591 
6592   LValue LV;
6593   LV.set({LVBase});
6594   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6595 }
6596 
6597 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6598 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6599                                   LValue &Result) {
6600   if (Info.checkingPotentialConstantExpression() ||
6601       Info.SpeculativeEvaluationDepth)
6602     return false;
6603 
6604   // This is permitted only within a call to std::allocator<T>::allocate.
6605   auto Caller = Info.getStdAllocatorCaller("allocate");
6606   if (!Caller) {
6607     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6608                                      ? diag::note_constexpr_new_untyped
6609                                      : diag::note_constexpr_new);
6610     return false;
6611   }
6612 
6613   QualType ElemType = Caller.ElemType;
6614   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6615     Info.FFDiag(E->getExprLoc(),
6616                 diag::note_constexpr_new_not_complete_object_type)
6617         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6618     return false;
6619   }
6620 
6621   APSInt ByteSize;
6622   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6623     return false;
6624   bool IsNothrow = false;
6625   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6626     EvaluateIgnoredValue(Info, E->getArg(I));
6627     IsNothrow |= E->getType()->isNothrowT();
6628   }
6629 
6630   CharUnits ElemSize;
6631   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6632     return false;
6633   APInt Size, Remainder;
6634   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6635   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6636   if (Remainder != 0) {
6637     // This likely indicates a bug in the implementation of 'std::allocator'.
6638     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6639         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6640     return false;
6641   }
6642 
6643   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6644     if (IsNothrow) {
6645       Result.setNull(Info.Ctx, E->getType());
6646       return true;
6647     }
6648 
6649     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6650     return false;
6651   }
6652 
6653   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6654                                                      ArrayType::Normal, 0);
6655   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6656   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6657   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6658   return true;
6659 }
6660 
6661 static bool hasVirtualDestructor(QualType T) {
6662   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6663     if (CXXDestructorDecl *DD = RD->getDestructor())
6664       return DD->isVirtual();
6665   return false;
6666 }
6667 
6668 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6669   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6670     if (CXXDestructorDecl *DD = RD->getDestructor())
6671       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6672   return nullptr;
6673 }
6674 
6675 /// Check that the given object is a suitable pointer to a heap allocation that
6676 /// still exists and is of the right kind for the purpose of a deletion.
6677 ///
6678 /// On success, returns the heap allocation to deallocate. On failure, produces
6679 /// a diagnostic and returns None.
6680 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6681                                             const LValue &Pointer,
6682                                             DynAlloc::Kind DeallocKind) {
6683   auto PointerAsString = [&] {
6684     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6685   };
6686 
6687   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6688   if (!DA) {
6689     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6690         << PointerAsString();
6691     if (Pointer.Base)
6692       NoteLValueLocation(Info, Pointer.Base);
6693     return None;
6694   }
6695 
6696   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6697   if (!Alloc) {
6698     Info.FFDiag(E, diag::note_constexpr_double_delete);
6699     return None;
6700   }
6701 
6702   QualType AllocType = Pointer.Base.getDynamicAllocType();
6703   if (DeallocKind != (*Alloc)->getKind()) {
6704     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6705         << DeallocKind << (*Alloc)->getKind() << AllocType;
6706     NoteLValueLocation(Info, Pointer.Base);
6707     return None;
6708   }
6709 
6710   bool Subobject = false;
6711   if (DeallocKind == DynAlloc::New) {
6712     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6713                 Pointer.Designator.isOnePastTheEnd();
6714   } else {
6715     Subobject = Pointer.Designator.Entries.size() != 1 ||
6716                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6717   }
6718   if (Subobject) {
6719     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6720         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6721     return None;
6722   }
6723 
6724   return Alloc;
6725 }
6726 
6727 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6728 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6729   if (Info.checkingPotentialConstantExpression() ||
6730       Info.SpeculativeEvaluationDepth)
6731     return false;
6732 
6733   // This is permitted only within a call to std::allocator<T>::deallocate.
6734   if (!Info.getStdAllocatorCaller("deallocate")) {
6735     Info.FFDiag(E->getExprLoc());
6736     return true;
6737   }
6738 
6739   LValue Pointer;
6740   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6741     return false;
6742   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6743     EvaluateIgnoredValue(Info, E->getArg(I));
6744 
6745   if (Pointer.Designator.Invalid)
6746     return false;
6747 
6748   // Deleting a null pointer would have no effect, but it's not permitted by
6749   // std::allocator<T>::deallocate's contract.
6750   if (Pointer.isNullPointer()) {
6751     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6752     return true;
6753   }
6754 
6755   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6756     return false;
6757 
6758   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6759   return true;
6760 }
6761 
6762 //===----------------------------------------------------------------------===//
6763 // Generic Evaluation
6764 //===----------------------------------------------------------------------===//
6765 namespace {
6766 
6767 class BitCastBuffer {
6768   // FIXME: We're going to need bit-level granularity when we support
6769   // bit-fields.
6770   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6771   // we don't support a host or target where that is the case. Still, we should
6772   // use a more generic type in case we ever do.
6773   SmallVector<Optional<unsigned char>, 32> Bytes;
6774 
6775   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6776                 "Need at least 8 bit unsigned char");
6777 
6778   bool TargetIsLittleEndian;
6779 
6780 public:
6781   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6782       : Bytes(Width.getQuantity()),
6783         TargetIsLittleEndian(TargetIsLittleEndian) {}
6784 
6785   LLVM_NODISCARD
6786   bool readObject(CharUnits Offset, CharUnits Width,
6787                   SmallVectorImpl<unsigned char> &Output) const {
6788     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6789       // If a byte of an integer is uninitialized, then the whole integer is
6790       // uninitialized.
6791       if (!Bytes[I.getQuantity()])
6792         return false;
6793       Output.push_back(*Bytes[I.getQuantity()]);
6794     }
6795     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6796       std::reverse(Output.begin(), Output.end());
6797     return true;
6798   }
6799 
6800   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6801     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6802       std::reverse(Input.begin(), Input.end());
6803 
6804     size_t Index = 0;
6805     for (unsigned char Byte : Input) {
6806       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6807       Bytes[Offset.getQuantity() + Index] = Byte;
6808       ++Index;
6809     }
6810   }
6811 
6812   size_t size() { return Bytes.size(); }
6813 };
6814 
6815 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6816 /// target would represent the value at runtime.
6817 class APValueToBufferConverter {
6818   EvalInfo &Info;
6819   BitCastBuffer Buffer;
6820   const CastExpr *BCE;
6821 
6822   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6823                            const CastExpr *BCE)
6824       : Info(Info),
6825         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6826         BCE(BCE) {}
6827 
6828   bool visit(const APValue &Val, QualType Ty) {
6829     return visit(Val, Ty, CharUnits::fromQuantity(0));
6830   }
6831 
6832   // Write out Val with type Ty into Buffer starting at Offset.
6833   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6834     assert((size_t)Offset.getQuantity() <= Buffer.size());
6835 
6836     // As a special case, nullptr_t has an indeterminate value.
6837     if (Ty->isNullPtrType())
6838       return true;
6839 
6840     // Dig through Src to find the byte at SrcOffset.
6841     switch (Val.getKind()) {
6842     case APValue::Indeterminate:
6843     case APValue::None:
6844       return true;
6845 
6846     case APValue::Int:
6847       return visitInt(Val.getInt(), Ty, Offset);
6848     case APValue::Float:
6849       return visitFloat(Val.getFloat(), Ty, Offset);
6850     case APValue::Array:
6851       return visitArray(Val, Ty, Offset);
6852     case APValue::Struct:
6853       return visitRecord(Val, Ty, Offset);
6854 
6855     case APValue::ComplexInt:
6856     case APValue::ComplexFloat:
6857     case APValue::Vector:
6858     case APValue::FixedPoint:
6859       // FIXME: We should support these.
6860 
6861     case APValue::Union:
6862     case APValue::MemberPointer:
6863     case APValue::AddrLabelDiff: {
6864       Info.FFDiag(BCE->getBeginLoc(),
6865                   diag::note_constexpr_bit_cast_unsupported_type)
6866           << Ty;
6867       return false;
6868     }
6869 
6870     case APValue::LValue:
6871       llvm_unreachable("LValue subobject in bit_cast?");
6872     }
6873     llvm_unreachable("Unhandled APValue::ValueKind");
6874   }
6875 
6876   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6877     const RecordDecl *RD = Ty->getAsRecordDecl();
6878     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6879 
6880     // Visit the base classes.
6881     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6882       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6883         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6884         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6885 
6886         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6887                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6888           return false;
6889       }
6890     }
6891 
6892     // Visit the fields.
6893     unsigned FieldIdx = 0;
6894     for (FieldDecl *FD : RD->fields()) {
6895       if (FD->isBitField()) {
6896         Info.FFDiag(BCE->getBeginLoc(),
6897                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6898         return false;
6899       }
6900 
6901       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6902 
6903       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6904              "only bit-fields can have sub-char alignment");
6905       CharUnits FieldOffset =
6906           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6907       QualType FieldTy = FD->getType();
6908       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6909         return false;
6910       ++FieldIdx;
6911     }
6912 
6913     return true;
6914   }
6915 
6916   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6917     const auto *CAT =
6918         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6919     if (!CAT)
6920       return false;
6921 
6922     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6923     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6924     unsigned ArraySize = Val.getArraySize();
6925     // First, initialize the initialized elements.
6926     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6927       const APValue &SubObj = Val.getArrayInitializedElt(I);
6928       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6929         return false;
6930     }
6931 
6932     // Next, initialize the rest of the array using the filler.
6933     if (Val.hasArrayFiller()) {
6934       const APValue &Filler = Val.getArrayFiller();
6935       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6936         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6937           return false;
6938       }
6939     }
6940 
6941     return true;
6942   }
6943 
6944   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6945     APSInt AdjustedVal = Val;
6946     unsigned Width = AdjustedVal.getBitWidth();
6947     if (Ty->isBooleanType()) {
6948       Width = Info.Ctx.getTypeSize(Ty);
6949       AdjustedVal = AdjustedVal.extend(Width);
6950     }
6951 
6952     SmallVector<unsigned char, 8> Bytes(Width / 8);
6953     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6954     Buffer.writeObject(Offset, Bytes);
6955     return true;
6956   }
6957 
6958   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6959     APSInt AsInt(Val.bitcastToAPInt());
6960     return visitInt(AsInt, Ty, Offset);
6961   }
6962 
6963 public:
6964   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6965                                          const CastExpr *BCE) {
6966     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6967     APValueToBufferConverter Converter(Info, DstSize, BCE);
6968     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6969       return None;
6970     return Converter.Buffer;
6971   }
6972 };
6973 
6974 /// Write an BitCastBuffer into an APValue.
6975 class BufferToAPValueConverter {
6976   EvalInfo &Info;
6977   const BitCastBuffer &Buffer;
6978   const CastExpr *BCE;
6979 
6980   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6981                            const CastExpr *BCE)
6982       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6983 
6984   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6985   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6986   // Ideally this will be unreachable.
6987   llvm::NoneType unsupportedType(QualType Ty) {
6988     Info.FFDiag(BCE->getBeginLoc(),
6989                 diag::note_constexpr_bit_cast_unsupported_type)
6990         << Ty;
6991     return None;
6992   }
6993 
6994   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6995     Info.FFDiag(BCE->getBeginLoc(),
6996                 diag::note_constexpr_bit_cast_unrepresentable_value)
6997         << Ty << toString(Val, /*Radix=*/10);
6998     return None;
6999   }
7000 
7001   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7002                           const EnumType *EnumSugar = nullptr) {
7003     if (T->isNullPtrType()) {
7004       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7005       return APValue((Expr *)nullptr,
7006                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7007                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7008     }
7009 
7010     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7011 
7012     // Work around floating point types that contain unused padding bytes. This
7013     // is really just `long double` on x86, which is the only fundamental type
7014     // with padding bytes.
7015     if (T->isRealFloatingType()) {
7016       const llvm::fltSemantics &Semantics =
7017           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7018       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7019       assert(NumBits % 8 == 0);
7020       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7021       if (NumBytes != SizeOf)
7022         SizeOf = NumBytes;
7023     }
7024 
7025     SmallVector<uint8_t, 8> Bytes;
7026     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7027       // If this is std::byte or unsigned char, then its okay to store an
7028       // indeterminate value.
7029       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7030       bool IsUChar =
7031           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7032                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7033       if (!IsStdByte && !IsUChar) {
7034         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7035         Info.FFDiag(BCE->getExprLoc(),
7036                     diag::note_constexpr_bit_cast_indet_dest)
7037             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7038         return None;
7039       }
7040 
7041       return APValue::IndeterminateValue();
7042     }
7043 
7044     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7045     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7046 
7047     if (T->isIntegralOrEnumerationType()) {
7048       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7049 
7050       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7051       if (IntWidth != Val.getBitWidth()) {
7052         APSInt Truncated = Val.trunc(IntWidth);
7053         if (Truncated.extend(Val.getBitWidth()) != Val)
7054           return unrepresentableValue(QualType(T, 0), Val);
7055         Val = Truncated;
7056       }
7057 
7058       return APValue(Val);
7059     }
7060 
7061     if (T->isRealFloatingType()) {
7062       const llvm::fltSemantics &Semantics =
7063           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7064       return APValue(APFloat(Semantics, Val));
7065     }
7066 
7067     return unsupportedType(QualType(T, 0));
7068   }
7069 
7070   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7071     const RecordDecl *RD = RTy->getAsRecordDecl();
7072     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7073 
7074     unsigned NumBases = 0;
7075     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7076       NumBases = CXXRD->getNumBases();
7077 
7078     APValue ResultVal(APValue::UninitStruct(), NumBases,
7079                       std::distance(RD->field_begin(), RD->field_end()));
7080 
7081     // Visit the base classes.
7082     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7083       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7084         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7085         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7086         if (BaseDecl->isEmpty() ||
7087             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7088           continue;
7089 
7090         Optional<APValue> SubObj = visitType(
7091             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7092         if (!SubObj)
7093           return None;
7094         ResultVal.getStructBase(I) = *SubObj;
7095       }
7096     }
7097 
7098     // Visit the fields.
7099     unsigned FieldIdx = 0;
7100     for (FieldDecl *FD : RD->fields()) {
7101       // FIXME: We don't currently support bit-fields. A lot of the logic for
7102       // this is in CodeGen, so we need to factor it around.
7103       if (FD->isBitField()) {
7104         Info.FFDiag(BCE->getBeginLoc(),
7105                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7106         return None;
7107       }
7108 
7109       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7110       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7111 
7112       CharUnits FieldOffset =
7113           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7114           Offset;
7115       QualType FieldTy = FD->getType();
7116       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7117       if (!SubObj)
7118         return None;
7119       ResultVal.getStructField(FieldIdx) = *SubObj;
7120       ++FieldIdx;
7121     }
7122 
7123     return ResultVal;
7124   }
7125 
7126   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7127     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7128     assert(!RepresentationType.isNull() &&
7129            "enum forward decl should be caught by Sema");
7130     const auto *AsBuiltin =
7131         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7132     // Recurse into the underlying type. Treat std::byte transparently as
7133     // unsigned char.
7134     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7135   }
7136 
7137   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7138     size_t Size = Ty->getSize().getLimitedValue();
7139     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7140 
7141     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7142     for (size_t I = 0; I != Size; ++I) {
7143       Optional<APValue> ElementValue =
7144           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7145       if (!ElementValue)
7146         return None;
7147       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7148     }
7149 
7150     return ArrayValue;
7151   }
7152 
7153   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7154     return unsupportedType(QualType(Ty, 0));
7155   }
7156 
7157   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7158     QualType Can = Ty.getCanonicalType();
7159 
7160     switch (Can->getTypeClass()) {
7161 #define TYPE(Class, Base)                                                      \
7162   case Type::Class:                                                            \
7163     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7164 #define ABSTRACT_TYPE(Class, Base)
7165 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7166   case Type::Class:                                                            \
7167     llvm_unreachable("non-canonical type should be impossible!");
7168 #define DEPENDENT_TYPE(Class, Base)                                            \
7169   case Type::Class:                                                            \
7170     llvm_unreachable(                                                          \
7171         "dependent types aren't supported in the constant evaluator!");
7172 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7173   case Type::Class:                                                            \
7174     llvm_unreachable("either dependent or not canonical!");
7175 #include "clang/AST/TypeNodes.inc"
7176     }
7177     llvm_unreachable("Unhandled Type::TypeClass");
7178   }
7179 
7180 public:
7181   // Pull out a full value of type DstType.
7182   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7183                                    const CastExpr *BCE) {
7184     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7185     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7186   }
7187 };
7188 
7189 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7190                                                  QualType Ty, EvalInfo *Info,
7191                                                  const ASTContext &Ctx,
7192                                                  bool CheckingDest) {
7193   Ty = Ty.getCanonicalType();
7194 
7195   auto diag = [&](int Reason) {
7196     if (Info)
7197       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7198           << CheckingDest << (Reason == 4) << Reason;
7199     return false;
7200   };
7201   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7202     if (Info)
7203       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7204           << NoteTy << Construct << Ty;
7205     return false;
7206   };
7207 
7208   if (Ty->isUnionType())
7209     return diag(0);
7210   if (Ty->isPointerType())
7211     return diag(1);
7212   if (Ty->isMemberPointerType())
7213     return diag(2);
7214   if (Ty.isVolatileQualified())
7215     return diag(3);
7216 
7217   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7218     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7219       for (CXXBaseSpecifier &BS : CXXRD->bases())
7220         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7221                                                   CheckingDest))
7222           return note(1, BS.getType(), BS.getBeginLoc());
7223     }
7224     for (FieldDecl *FD : Record->fields()) {
7225       if (FD->getType()->isReferenceType())
7226         return diag(4);
7227       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7228                                                 CheckingDest))
7229         return note(0, FD->getType(), FD->getBeginLoc());
7230     }
7231   }
7232 
7233   if (Ty->isArrayType() &&
7234       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7235                                             Info, Ctx, CheckingDest))
7236     return false;
7237 
7238   return true;
7239 }
7240 
7241 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7242                                              const ASTContext &Ctx,
7243                                              const CastExpr *BCE) {
7244   bool DestOK = checkBitCastConstexprEligibilityType(
7245       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7246   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7247                                 BCE->getBeginLoc(),
7248                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7249   return SourceOK;
7250 }
7251 
7252 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7253                                         APValue &SourceValue,
7254                                         const CastExpr *BCE) {
7255   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7256          "no host or target supports non 8-bit chars");
7257   assert(SourceValue.isLValue() &&
7258          "LValueToRValueBitcast requires an lvalue operand!");
7259 
7260   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7261     return false;
7262 
7263   LValue SourceLValue;
7264   APValue SourceRValue;
7265   SourceLValue.setFrom(Info.Ctx, SourceValue);
7266   if (!handleLValueToRValueConversion(
7267           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7268           SourceRValue, /*WantObjectRepresentation=*/true))
7269     return false;
7270 
7271   // Read out SourceValue into a char buffer.
7272   Optional<BitCastBuffer> Buffer =
7273       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7274   if (!Buffer)
7275     return false;
7276 
7277   // Write out the buffer into a new APValue.
7278   Optional<APValue> MaybeDestValue =
7279       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7280   if (!MaybeDestValue)
7281     return false;
7282 
7283   DestValue = std::move(*MaybeDestValue);
7284   return true;
7285 }
7286 
7287 template <class Derived>
7288 class ExprEvaluatorBase
7289   : public ConstStmtVisitor<Derived, bool> {
7290 private:
7291   Derived &getDerived() { return static_cast<Derived&>(*this); }
7292   bool DerivedSuccess(const APValue &V, const Expr *E) {
7293     return getDerived().Success(V, E);
7294   }
7295   bool DerivedZeroInitialization(const Expr *E) {
7296     return getDerived().ZeroInitialization(E);
7297   }
7298 
7299   // Check whether a conditional operator with a non-constant condition is a
7300   // potential constant expression. If neither arm is a potential constant
7301   // expression, then the conditional operator is not either.
7302   template<typename ConditionalOperator>
7303   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7304     assert(Info.checkingPotentialConstantExpression());
7305 
7306     // Speculatively evaluate both arms.
7307     SmallVector<PartialDiagnosticAt, 8> Diag;
7308     {
7309       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7310       StmtVisitorTy::Visit(E->getFalseExpr());
7311       if (Diag.empty())
7312         return;
7313     }
7314 
7315     {
7316       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7317       Diag.clear();
7318       StmtVisitorTy::Visit(E->getTrueExpr());
7319       if (Diag.empty())
7320         return;
7321     }
7322 
7323     Error(E, diag::note_constexpr_conditional_never_const);
7324   }
7325 
7326 
7327   template<typename ConditionalOperator>
7328   bool HandleConditionalOperator(const ConditionalOperator *E) {
7329     bool BoolResult;
7330     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7331       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7332         CheckPotentialConstantConditional(E);
7333         return false;
7334       }
7335       if (Info.noteFailure()) {
7336         StmtVisitorTy::Visit(E->getTrueExpr());
7337         StmtVisitorTy::Visit(E->getFalseExpr());
7338       }
7339       return false;
7340     }
7341 
7342     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7343     return StmtVisitorTy::Visit(EvalExpr);
7344   }
7345 
7346 protected:
7347   EvalInfo &Info;
7348   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7349   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7350 
7351   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7352     return Info.CCEDiag(E, D);
7353   }
7354 
7355   bool ZeroInitialization(const Expr *E) { return Error(E); }
7356 
7357 public:
7358   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7359 
7360   EvalInfo &getEvalInfo() { return Info; }
7361 
7362   /// Report an evaluation error. This should only be called when an error is
7363   /// first discovered. When propagating an error, just return false.
7364   bool Error(const Expr *E, diag::kind D) {
7365     Info.FFDiag(E, D);
7366     return false;
7367   }
7368   bool Error(const Expr *E) {
7369     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7370   }
7371 
7372   bool VisitStmt(const Stmt *) {
7373     llvm_unreachable("Expression evaluator should not be called on stmts");
7374   }
7375   bool VisitExpr(const Expr *E) {
7376     return Error(E);
7377   }
7378 
7379   bool VisitConstantExpr(const ConstantExpr *E) {
7380     if (E->hasAPValueResult())
7381       return DerivedSuccess(E->getAPValueResult(), E);
7382 
7383     return StmtVisitorTy::Visit(E->getSubExpr());
7384   }
7385 
7386   bool VisitParenExpr(const ParenExpr *E)
7387     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7388   bool VisitUnaryExtension(const UnaryOperator *E)
7389     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7390   bool VisitUnaryPlus(const UnaryOperator *E)
7391     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7392   bool VisitChooseExpr(const ChooseExpr *E)
7393     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7394   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7395     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7396   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7397     { return StmtVisitorTy::Visit(E->getReplacement()); }
7398   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7399     TempVersionRAII RAII(*Info.CurrentCall);
7400     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7401     return StmtVisitorTy::Visit(E->getExpr());
7402   }
7403   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7404     TempVersionRAII RAII(*Info.CurrentCall);
7405     // The initializer may not have been parsed yet, or might be erroneous.
7406     if (!E->getExpr())
7407       return Error(E);
7408     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7409     return StmtVisitorTy::Visit(E->getExpr());
7410   }
7411 
7412   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7413     FullExpressionRAII Scope(Info);
7414     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7415   }
7416 
7417   // Temporaries are registered when created, so we don't care about
7418   // CXXBindTemporaryExpr.
7419   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7420     return StmtVisitorTy::Visit(E->getSubExpr());
7421   }
7422 
7423   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7424     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7425     return static_cast<Derived*>(this)->VisitCastExpr(E);
7426   }
7427   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7428     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7429       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7430     return static_cast<Derived*>(this)->VisitCastExpr(E);
7431   }
7432   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7433     return static_cast<Derived*>(this)->VisitCastExpr(E);
7434   }
7435 
7436   bool VisitBinaryOperator(const BinaryOperator *E) {
7437     switch (E->getOpcode()) {
7438     default:
7439       return Error(E);
7440 
7441     case BO_Comma:
7442       VisitIgnoredValue(E->getLHS());
7443       return StmtVisitorTy::Visit(E->getRHS());
7444 
7445     case BO_PtrMemD:
7446     case BO_PtrMemI: {
7447       LValue Obj;
7448       if (!HandleMemberPointerAccess(Info, E, Obj))
7449         return false;
7450       APValue Result;
7451       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7452         return false;
7453       return DerivedSuccess(Result, E);
7454     }
7455     }
7456   }
7457 
7458   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7459     return StmtVisitorTy::Visit(E->getSemanticForm());
7460   }
7461 
7462   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7463     // Evaluate and cache the common expression. We treat it as a temporary,
7464     // even though it's not quite the same thing.
7465     LValue CommonLV;
7466     if (!Evaluate(Info.CurrentCall->createTemporary(
7467                       E->getOpaqueValue(),
7468                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7469                       ScopeKind::FullExpression, CommonLV),
7470                   Info, E->getCommon()))
7471       return false;
7472 
7473     return HandleConditionalOperator(E);
7474   }
7475 
7476   bool VisitConditionalOperator(const ConditionalOperator *E) {
7477     bool IsBcpCall = false;
7478     // If the condition (ignoring parens) is a __builtin_constant_p call,
7479     // the result is a constant expression if it can be folded without
7480     // side-effects. This is an important GNU extension. See GCC PR38377
7481     // for discussion.
7482     if (const CallExpr *CallCE =
7483           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7484       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7485         IsBcpCall = true;
7486 
7487     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7488     // constant expression; we can't check whether it's potentially foldable.
7489     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7490     // it would return 'false' in this mode.
7491     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7492       return false;
7493 
7494     FoldConstant Fold(Info, IsBcpCall);
7495     if (!HandleConditionalOperator(E)) {
7496       Fold.keepDiagnostics();
7497       return false;
7498     }
7499 
7500     return true;
7501   }
7502 
7503   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7504     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7505       return DerivedSuccess(*Value, E);
7506 
7507     const Expr *Source = E->getSourceExpr();
7508     if (!Source)
7509       return Error(E);
7510     if (Source == E) {
7511       assert(0 && "OpaqueValueExpr recursively refers to itself");
7512       return Error(E);
7513     }
7514     return StmtVisitorTy::Visit(Source);
7515   }
7516 
7517   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7518     for (const Expr *SemE : E->semantics()) {
7519       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7520         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7521         // result expression: there could be two different LValues that would
7522         // refer to the same object in that case, and we can't model that.
7523         if (SemE == E->getResultExpr())
7524           return Error(E);
7525 
7526         // Unique OVEs get evaluated if and when we encounter them when
7527         // emitting the rest of the semantic form, rather than eagerly.
7528         if (OVE->isUnique())
7529           continue;
7530 
7531         LValue LV;
7532         if (!Evaluate(Info.CurrentCall->createTemporary(
7533                           OVE, getStorageType(Info.Ctx, OVE),
7534                           ScopeKind::FullExpression, LV),
7535                       Info, OVE->getSourceExpr()))
7536           return false;
7537       } else if (SemE == E->getResultExpr()) {
7538         if (!StmtVisitorTy::Visit(SemE))
7539           return false;
7540       } else {
7541         if (!EvaluateIgnoredValue(Info, SemE))
7542           return false;
7543       }
7544     }
7545     return true;
7546   }
7547 
7548   bool VisitCallExpr(const CallExpr *E) {
7549     APValue Result;
7550     if (!handleCallExpr(E, Result, nullptr))
7551       return false;
7552     return DerivedSuccess(Result, E);
7553   }
7554 
7555   bool handleCallExpr(const CallExpr *E, APValue &Result,
7556                      const LValue *ResultSlot) {
7557     CallScopeRAII CallScope(Info);
7558 
7559     const Expr *Callee = E->getCallee()->IgnoreParens();
7560     QualType CalleeType = Callee->getType();
7561 
7562     const FunctionDecl *FD = nullptr;
7563     LValue *This = nullptr, ThisVal;
7564     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7565     bool HasQualifier = false;
7566 
7567     CallRef Call;
7568 
7569     // Extract function decl and 'this' pointer from the callee.
7570     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7571       const CXXMethodDecl *Member = nullptr;
7572       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7573         // Explicit bound member calls, such as x.f() or p->g();
7574         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7575           return false;
7576         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7577         if (!Member)
7578           return Error(Callee);
7579         This = &ThisVal;
7580         HasQualifier = ME->hasQualifier();
7581       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7582         // Indirect bound member calls ('.*' or '->*').
7583         const ValueDecl *D =
7584             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7585         if (!D)
7586           return false;
7587         Member = dyn_cast<CXXMethodDecl>(D);
7588         if (!Member)
7589           return Error(Callee);
7590         This = &ThisVal;
7591       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7592         if (!Info.getLangOpts().CPlusPlus20)
7593           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7594         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7595                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7596       } else
7597         return Error(Callee);
7598       FD = Member;
7599     } else if (CalleeType->isFunctionPointerType()) {
7600       LValue CalleeLV;
7601       if (!EvaluatePointer(Callee, CalleeLV, Info))
7602         return false;
7603 
7604       if (!CalleeLV.getLValueOffset().isZero())
7605         return Error(Callee);
7606       FD = dyn_cast_or_null<FunctionDecl>(
7607           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7608       if (!FD)
7609         return Error(Callee);
7610       // Don't call function pointers which have been cast to some other type.
7611       // Per DR (no number yet), the caller and callee can differ in noexcept.
7612       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7613         CalleeType->getPointeeType(), FD->getType())) {
7614         return Error(E);
7615       }
7616 
7617       // For an (overloaded) assignment expression, evaluate the RHS before the
7618       // LHS.
7619       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7620       if (OCE && OCE->isAssignmentOp()) {
7621         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7622         Call = Info.CurrentCall->createCall(FD);
7623         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7624                           Info, FD, /*RightToLeft=*/true))
7625           return false;
7626       }
7627 
7628       // Overloaded operator calls to member functions are represented as normal
7629       // calls with '*this' as the first argument.
7630       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7631       if (MD && !MD->isStatic()) {
7632         // FIXME: When selecting an implicit conversion for an overloaded
7633         // operator delete, we sometimes try to evaluate calls to conversion
7634         // operators without a 'this' parameter!
7635         if (Args.empty())
7636           return Error(E);
7637 
7638         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7639           return false;
7640         This = &ThisVal;
7641 
7642         // If this is syntactically a simple assignment using a trivial
7643         // assignment operator, start the lifetimes of union members as needed,
7644         // per C++20 [class.union]5.
7645         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7646             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7647             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7648           return false;
7649 
7650         Args = Args.slice(1);
7651       } else if (MD && MD->isLambdaStaticInvoker()) {
7652         // Map the static invoker for the lambda back to the call operator.
7653         // Conveniently, we don't have to slice out the 'this' argument (as is
7654         // being done for the non-static case), since a static member function
7655         // doesn't have an implicit argument passed in.
7656         const CXXRecordDecl *ClosureClass = MD->getParent();
7657         assert(
7658             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7659             "Number of captures must be zero for conversion to function-ptr");
7660 
7661         const CXXMethodDecl *LambdaCallOp =
7662             ClosureClass->getLambdaCallOperator();
7663 
7664         // Set 'FD', the function that will be called below, to the call
7665         // operator.  If the closure object represents a generic lambda, find
7666         // the corresponding specialization of the call operator.
7667 
7668         if (ClosureClass->isGenericLambda()) {
7669           assert(MD->isFunctionTemplateSpecialization() &&
7670                  "A generic lambda's static-invoker function must be a "
7671                  "template specialization");
7672           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7673           FunctionTemplateDecl *CallOpTemplate =
7674               LambdaCallOp->getDescribedFunctionTemplate();
7675           void *InsertPos = nullptr;
7676           FunctionDecl *CorrespondingCallOpSpecialization =
7677               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7678           assert(CorrespondingCallOpSpecialization &&
7679                  "We must always have a function call operator specialization "
7680                  "that corresponds to our static invoker specialization");
7681           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7682         } else
7683           FD = LambdaCallOp;
7684       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7685         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7686             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7687           LValue Ptr;
7688           if (!HandleOperatorNewCall(Info, E, Ptr))
7689             return false;
7690           Ptr.moveInto(Result);
7691           return CallScope.destroy();
7692         } else {
7693           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7694         }
7695       }
7696     } else
7697       return Error(E);
7698 
7699     // Evaluate the arguments now if we've not already done so.
7700     if (!Call) {
7701       Call = Info.CurrentCall->createCall(FD);
7702       if (!EvaluateArgs(Args, Call, Info, FD))
7703         return false;
7704     }
7705 
7706     SmallVector<QualType, 4> CovariantAdjustmentPath;
7707     if (This) {
7708       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7709       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7710         // Perform virtual dispatch, if necessary.
7711         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7712                                    CovariantAdjustmentPath);
7713         if (!FD)
7714           return false;
7715       } else {
7716         // Check that the 'this' pointer points to an object of the right type.
7717         // FIXME: If this is an assignment operator call, we may need to change
7718         // the active union member before we check this.
7719         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7720           return false;
7721       }
7722     }
7723 
7724     // Destructor calls are different enough that they have their own codepath.
7725     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7726       assert(This && "no 'this' pointer for destructor call");
7727       return HandleDestruction(Info, E, *This,
7728                                Info.Ctx.getRecordType(DD->getParent())) &&
7729              CallScope.destroy();
7730     }
7731 
7732     const FunctionDecl *Definition = nullptr;
7733     Stmt *Body = FD->getBody(Definition);
7734 
7735     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7736         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7737                             Body, Info, Result, ResultSlot))
7738       return false;
7739 
7740     if (!CovariantAdjustmentPath.empty() &&
7741         !HandleCovariantReturnAdjustment(Info, E, Result,
7742                                          CovariantAdjustmentPath))
7743       return false;
7744 
7745     return CallScope.destroy();
7746   }
7747 
7748   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7749     return StmtVisitorTy::Visit(E->getInitializer());
7750   }
7751   bool VisitInitListExpr(const InitListExpr *E) {
7752     if (E->getNumInits() == 0)
7753       return DerivedZeroInitialization(E);
7754     if (E->getNumInits() == 1)
7755       return StmtVisitorTy::Visit(E->getInit(0));
7756     return Error(E);
7757   }
7758   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7759     return DerivedZeroInitialization(E);
7760   }
7761   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7762     return DerivedZeroInitialization(E);
7763   }
7764   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7765     return DerivedZeroInitialization(E);
7766   }
7767 
7768   /// A member expression where the object is a prvalue is itself a prvalue.
7769   bool VisitMemberExpr(const MemberExpr *E) {
7770     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7771            "missing temporary materialization conversion");
7772     assert(!E->isArrow() && "missing call to bound member function?");
7773 
7774     APValue Val;
7775     if (!Evaluate(Val, Info, E->getBase()))
7776       return false;
7777 
7778     QualType BaseTy = E->getBase()->getType();
7779 
7780     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7781     if (!FD) return Error(E);
7782     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7783     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7784            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7785 
7786     // Note: there is no lvalue base here. But this case should only ever
7787     // happen in C or in C++98, where we cannot be evaluating a constexpr
7788     // constructor, which is the only case the base matters.
7789     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7790     SubobjectDesignator Designator(BaseTy);
7791     Designator.addDeclUnchecked(FD);
7792 
7793     APValue Result;
7794     return extractSubobject(Info, E, Obj, Designator, Result) &&
7795            DerivedSuccess(Result, E);
7796   }
7797 
7798   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7799     APValue Val;
7800     if (!Evaluate(Val, Info, E->getBase()))
7801       return false;
7802 
7803     if (Val.isVector()) {
7804       SmallVector<uint32_t, 4> Indices;
7805       E->getEncodedElementAccess(Indices);
7806       if (Indices.size() == 1) {
7807         // Return scalar.
7808         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7809       } else {
7810         // Construct new APValue vector.
7811         SmallVector<APValue, 4> Elts;
7812         for (unsigned I = 0; I < Indices.size(); ++I) {
7813           Elts.push_back(Val.getVectorElt(Indices[I]));
7814         }
7815         APValue VecResult(Elts.data(), Indices.size());
7816         return DerivedSuccess(VecResult, E);
7817       }
7818     }
7819 
7820     return false;
7821   }
7822 
7823   bool VisitCastExpr(const CastExpr *E) {
7824     switch (E->getCastKind()) {
7825     default:
7826       break;
7827 
7828     case CK_AtomicToNonAtomic: {
7829       APValue AtomicVal;
7830       // This does not need to be done in place even for class/array types:
7831       // atomic-to-non-atomic conversion implies copying the object
7832       // representation.
7833       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7834         return false;
7835       return DerivedSuccess(AtomicVal, E);
7836     }
7837 
7838     case CK_NoOp:
7839     case CK_UserDefinedConversion:
7840       return StmtVisitorTy::Visit(E->getSubExpr());
7841 
7842     case CK_LValueToRValue: {
7843       LValue LVal;
7844       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7845         return false;
7846       APValue RVal;
7847       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7848       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7849                                           LVal, RVal))
7850         return false;
7851       return DerivedSuccess(RVal, E);
7852     }
7853     case CK_LValueToRValueBitCast: {
7854       APValue DestValue, SourceValue;
7855       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7856         return false;
7857       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7858         return false;
7859       return DerivedSuccess(DestValue, E);
7860     }
7861 
7862     case CK_AddressSpaceConversion: {
7863       APValue Value;
7864       if (!Evaluate(Value, Info, E->getSubExpr()))
7865         return false;
7866       return DerivedSuccess(Value, E);
7867     }
7868     }
7869 
7870     return Error(E);
7871   }
7872 
7873   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7874     return VisitUnaryPostIncDec(UO);
7875   }
7876   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7877     return VisitUnaryPostIncDec(UO);
7878   }
7879   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7880     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7881       return Error(UO);
7882 
7883     LValue LVal;
7884     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7885       return false;
7886     APValue RVal;
7887     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7888                       UO->isIncrementOp(), &RVal))
7889       return false;
7890     return DerivedSuccess(RVal, UO);
7891   }
7892 
7893   bool VisitStmtExpr(const StmtExpr *E) {
7894     // We will have checked the full-expressions inside the statement expression
7895     // when they were completed, and don't need to check them again now.
7896     llvm::SaveAndRestore<bool> NotCheckingForUB(
7897         Info.CheckingForUndefinedBehavior, false);
7898 
7899     const CompoundStmt *CS = E->getSubStmt();
7900     if (CS->body_empty())
7901       return true;
7902 
7903     BlockScopeRAII Scope(Info);
7904     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7905                                            BE = CS->body_end();
7906          /**/; ++BI) {
7907       if (BI + 1 == BE) {
7908         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7909         if (!FinalExpr) {
7910           Info.FFDiag((*BI)->getBeginLoc(),
7911                       diag::note_constexpr_stmt_expr_unsupported);
7912           return false;
7913         }
7914         return this->Visit(FinalExpr) && Scope.destroy();
7915       }
7916 
7917       APValue ReturnValue;
7918       StmtResult Result = { ReturnValue, nullptr };
7919       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7920       if (ESR != ESR_Succeeded) {
7921         // FIXME: If the statement-expression terminated due to 'return',
7922         // 'break', or 'continue', it would be nice to propagate that to
7923         // the outer statement evaluation rather than bailing out.
7924         if (ESR != ESR_Failed)
7925           Info.FFDiag((*BI)->getBeginLoc(),
7926                       diag::note_constexpr_stmt_expr_unsupported);
7927         return false;
7928       }
7929     }
7930 
7931     llvm_unreachable("Return from function from the loop above.");
7932   }
7933 
7934   /// Visit a value which is evaluated, but whose value is ignored.
7935   void VisitIgnoredValue(const Expr *E) {
7936     EvaluateIgnoredValue(Info, E);
7937   }
7938 
7939   /// Potentially visit a MemberExpr's base expression.
7940   void VisitIgnoredBaseExpression(const Expr *E) {
7941     // While MSVC doesn't evaluate the base expression, it does diagnose the
7942     // presence of side-effecting behavior.
7943     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7944       return;
7945     VisitIgnoredValue(E);
7946   }
7947 };
7948 
7949 } // namespace
7950 
7951 //===----------------------------------------------------------------------===//
7952 // Common base class for lvalue and temporary evaluation.
7953 //===----------------------------------------------------------------------===//
7954 namespace {
7955 template<class Derived>
7956 class LValueExprEvaluatorBase
7957   : public ExprEvaluatorBase<Derived> {
7958 protected:
7959   LValue &Result;
7960   bool InvalidBaseOK;
7961   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7962   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7963 
7964   bool Success(APValue::LValueBase B) {
7965     Result.set(B);
7966     return true;
7967   }
7968 
7969   bool evaluatePointer(const Expr *E, LValue &Result) {
7970     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7971   }
7972 
7973 public:
7974   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7975       : ExprEvaluatorBaseTy(Info), Result(Result),
7976         InvalidBaseOK(InvalidBaseOK) {}
7977 
7978   bool Success(const APValue &V, const Expr *E) {
7979     Result.setFrom(this->Info.Ctx, V);
7980     return true;
7981   }
7982 
7983   bool VisitMemberExpr(const MemberExpr *E) {
7984     // Handle non-static data members.
7985     QualType BaseTy;
7986     bool EvalOK;
7987     if (E->isArrow()) {
7988       EvalOK = evaluatePointer(E->getBase(), Result);
7989       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7990     } else if (E->getBase()->isPRValue()) {
7991       assert(E->getBase()->getType()->isRecordType());
7992       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7993       BaseTy = E->getBase()->getType();
7994     } else {
7995       EvalOK = this->Visit(E->getBase());
7996       BaseTy = E->getBase()->getType();
7997     }
7998     if (!EvalOK) {
7999       if (!InvalidBaseOK)
8000         return false;
8001       Result.setInvalid(E);
8002       return true;
8003     }
8004 
8005     const ValueDecl *MD = E->getMemberDecl();
8006     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8007       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8008              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8009       (void)BaseTy;
8010       if (!HandleLValueMember(this->Info, E, Result, FD))
8011         return false;
8012     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8013       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8014         return false;
8015     } else
8016       return this->Error(E);
8017 
8018     if (MD->getType()->isReferenceType()) {
8019       APValue RefValue;
8020       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8021                                           RefValue))
8022         return false;
8023       return Success(RefValue, E);
8024     }
8025     return true;
8026   }
8027 
8028   bool VisitBinaryOperator(const BinaryOperator *E) {
8029     switch (E->getOpcode()) {
8030     default:
8031       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8032 
8033     case BO_PtrMemD:
8034     case BO_PtrMemI:
8035       return HandleMemberPointerAccess(this->Info, E, Result);
8036     }
8037   }
8038 
8039   bool VisitCastExpr(const CastExpr *E) {
8040     switch (E->getCastKind()) {
8041     default:
8042       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8043 
8044     case CK_DerivedToBase:
8045     case CK_UncheckedDerivedToBase:
8046       if (!this->Visit(E->getSubExpr()))
8047         return false;
8048 
8049       // Now figure out the necessary offset to add to the base LV to get from
8050       // the derived class to the base class.
8051       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8052                                   Result);
8053     }
8054   }
8055 };
8056 }
8057 
8058 //===----------------------------------------------------------------------===//
8059 // LValue Evaluation
8060 //
8061 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8062 // function designators (in C), decl references to void objects (in C), and
8063 // temporaries (if building with -Wno-address-of-temporary).
8064 //
8065 // LValue evaluation produces values comprising a base expression of one of the
8066 // following types:
8067 // - Declarations
8068 //  * VarDecl
8069 //  * FunctionDecl
8070 // - Literals
8071 //  * CompoundLiteralExpr in C (and in global scope in C++)
8072 //  * StringLiteral
8073 //  * PredefinedExpr
8074 //  * ObjCStringLiteralExpr
8075 //  * ObjCEncodeExpr
8076 //  * AddrLabelExpr
8077 //  * BlockExpr
8078 //  * CallExpr for a MakeStringConstant builtin
8079 // - typeid(T) expressions, as TypeInfoLValues
8080 // - Locals and temporaries
8081 //  * MaterializeTemporaryExpr
8082 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8083 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8084 //    from the AST (FIXME).
8085 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8086 //    CallIndex, for a lifetime-extended temporary.
8087 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8088 //    immediate invocation.
8089 // plus an offset in bytes.
8090 //===----------------------------------------------------------------------===//
8091 namespace {
8092 class LValueExprEvaluator
8093   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8094 public:
8095   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8096     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8097 
8098   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8099   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8100 
8101   bool VisitDeclRefExpr(const DeclRefExpr *E);
8102   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8103   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8104   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8105   bool VisitMemberExpr(const MemberExpr *E);
8106   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8107   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8108   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8109   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8110   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8111   bool VisitUnaryDeref(const UnaryOperator *E);
8112   bool VisitUnaryReal(const UnaryOperator *E);
8113   bool VisitUnaryImag(const UnaryOperator *E);
8114   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8115     return VisitUnaryPreIncDec(UO);
8116   }
8117   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8118     return VisitUnaryPreIncDec(UO);
8119   }
8120   bool VisitBinAssign(const BinaryOperator *BO);
8121   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8122 
8123   bool VisitCastExpr(const CastExpr *E) {
8124     switch (E->getCastKind()) {
8125     default:
8126       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8127 
8128     case CK_LValueBitCast:
8129       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8130       if (!Visit(E->getSubExpr()))
8131         return false;
8132       Result.Designator.setInvalid();
8133       return true;
8134 
8135     case CK_BaseToDerived:
8136       if (!Visit(E->getSubExpr()))
8137         return false;
8138       return HandleBaseToDerivedCast(Info, E, Result);
8139 
8140     case CK_Dynamic:
8141       if (!Visit(E->getSubExpr()))
8142         return false;
8143       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8144     }
8145   }
8146 };
8147 } // end anonymous namespace
8148 
8149 /// Evaluate an expression as an lvalue. This can be legitimately called on
8150 /// expressions which are not glvalues, in three cases:
8151 ///  * function designators in C, and
8152 ///  * "extern void" objects
8153 ///  * @selector() expressions in Objective-C
8154 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8155                            bool InvalidBaseOK) {
8156   assert(!E->isValueDependent());
8157   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8158          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8159   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8160 }
8161 
8162 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8163   const NamedDecl *D = E->getDecl();
8164   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8165     return Success(cast<ValueDecl>(D));
8166   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8167     return VisitVarDecl(E, VD);
8168   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8169     return Visit(BD->getBinding());
8170   return Error(E);
8171 }
8172 
8173 
8174 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8175 
8176   // If we are within a lambda's call operator, check whether the 'VD' referred
8177   // to within 'E' actually represents a lambda-capture that maps to a
8178   // data-member/field within the closure object, and if so, evaluate to the
8179   // field or what the field refers to.
8180   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8181       isa<DeclRefExpr>(E) &&
8182       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8183     // We don't always have a complete capture-map when checking or inferring if
8184     // the function call operator meets the requirements of a constexpr function
8185     // - but we don't need to evaluate the captures to determine constexprness
8186     // (dcl.constexpr C++17).
8187     if (Info.checkingPotentialConstantExpression())
8188       return false;
8189 
8190     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8191       // Start with 'Result' referring to the complete closure object...
8192       Result = *Info.CurrentCall->This;
8193       // ... then update it to refer to the field of the closure object
8194       // that represents the capture.
8195       if (!HandleLValueMember(Info, E, Result, FD))
8196         return false;
8197       // And if the field is of reference type, update 'Result' to refer to what
8198       // the field refers to.
8199       if (FD->getType()->isReferenceType()) {
8200         APValue RVal;
8201         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8202                                             RVal))
8203           return false;
8204         Result.setFrom(Info.Ctx, RVal);
8205       }
8206       return true;
8207     }
8208   }
8209 
8210   CallStackFrame *Frame = nullptr;
8211   unsigned Version = 0;
8212   if (VD->hasLocalStorage()) {
8213     // Only if a local variable was declared in the function currently being
8214     // evaluated, do we expect to be able to find its value in the current
8215     // frame. (Otherwise it was likely declared in an enclosing context and
8216     // could either have a valid evaluatable value (for e.g. a constexpr
8217     // variable) or be ill-formed (and trigger an appropriate evaluation
8218     // diagnostic)).
8219     CallStackFrame *CurrFrame = Info.CurrentCall;
8220     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8221       // Function parameters are stored in some caller's frame. (Usually the
8222       // immediate caller, but for an inherited constructor they may be more
8223       // distant.)
8224       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8225         if (CurrFrame->Arguments) {
8226           VD = CurrFrame->Arguments.getOrigParam(PVD);
8227           Frame =
8228               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8229           Version = CurrFrame->Arguments.Version;
8230         }
8231       } else {
8232         Frame = CurrFrame;
8233         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8234       }
8235     }
8236   }
8237 
8238   if (!VD->getType()->isReferenceType()) {
8239     if (Frame) {
8240       Result.set({VD, Frame->Index, Version});
8241       return true;
8242     }
8243     return Success(VD);
8244   }
8245 
8246   if (!Info.getLangOpts().CPlusPlus11) {
8247     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8248         << VD << VD->getType();
8249     Info.Note(VD->getLocation(), diag::note_declared_at);
8250   }
8251 
8252   APValue *V;
8253   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8254     return false;
8255   if (!V->hasValue()) {
8256     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8257     // adjust the diagnostic to say that.
8258     if (!Info.checkingPotentialConstantExpression())
8259       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8260     return false;
8261   }
8262   return Success(*V, E);
8263 }
8264 
8265 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8266     const MaterializeTemporaryExpr *E) {
8267   // Walk through the expression to find the materialized temporary itself.
8268   SmallVector<const Expr *, 2> CommaLHSs;
8269   SmallVector<SubobjectAdjustment, 2> Adjustments;
8270   const Expr *Inner =
8271       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8272 
8273   // If we passed any comma operators, evaluate their LHSs.
8274   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8275     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8276       return false;
8277 
8278   // A materialized temporary with static storage duration can appear within the
8279   // result of a constant expression evaluation, so we need to preserve its
8280   // value for use outside this evaluation.
8281   APValue *Value;
8282   if (E->getStorageDuration() == SD_Static) {
8283     // FIXME: What about SD_Thread?
8284     Value = E->getOrCreateValue(true);
8285     *Value = APValue();
8286     Result.set(E);
8287   } else {
8288     Value = &Info.CurrentCall->createTemporary(
8289         E, E->getType(),
8290         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8291                                                      : ScopeKind::Block,
8292         Result);
8293   }
8294 
8295   QualType Type = Inner->getType();
8296 
8297   // Materialize the temporary itself.
8298   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8299     *Value = APValue();
8300     return false;
8301   }
8302 
8303   // Adjust our lvalue to refer to the desired subobject.
8304   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8305     --I;
8306     switch (Adjustments[I].Kind) {
8307     case SubobjectAdjustment::DerivedToBaseAdjustment:
8308       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8309                                 Type, Result))
8310         return false;
8311       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8312       break;
8313 
8314     case SubobjectAdjustment::FieldAdjustment:
8315       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8316         return false;
8317       Type = Adjustments[I].Field->getType();
8318       break;
8319 
8320     case SubobjectAdjustment::MemberPointerAdjustment:
8321       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8322                                      Adjustments[I].Ptr.RHS))
8323         return false;
8324       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8325       break;
8326     }
8327   }
8328 
8329   return true;
8330 }
8331 
8332 bool
8333 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8334   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8335          "lvalue compound literal in c++?");
8336   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8337   // only see this when folding in C, so there's no standard to follow here.
8338   return Success(E);
8339 }
8340 
8341 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8342   TypeInfoLValue TypeInfo;
8343 
8344   if (!E->isPotentiallyEvaluated()) {
8345     if (E->isTypeOperand())
8346       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8347     else
8348       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8349   } else {
8350     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8351       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8352         << E->getExprOperand()->getType()
8353         << E->getExprOperand()->getSourceRange();
8354     }
8355 
8356     if (!Visit(E->getExprOperand()))
8357       return false;
8358 
8359     Optional<DynamicType> DynType =
8360         ComputeDynamicType(Info, E, Result, AK_TypeId);
8361     if (!DynType)
8362       return false;
8363 
8364     TypeInfo =
8365         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8366   }
8367 
8368   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8369 }
8370 
8371 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8372   return Success(E->getGuidDecl());
8373 }
8374 
8375 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8376   // Handle static data members.
8377   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8378     VisitIgnoredBaseExpression(E->getBase());
8379     return VisitVarDecl(E, VD);
8380   }
8381 
8382   // Handle static member functions.
8383   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8384     if (MD->isStatic()) {
8385       VisitIgnoredBaseExpression(E->getBase());
8386       return Success(MD);
8387     }
8388   }
8389 
8390   // Handle non-static data members.
8391   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8392 }
8393 
8394 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8395   // FIXME: Deal with vectors as array subscript bases.
8396   if (E->getBase()->getType()->isVectorType())
8397     return Error(E);
8398 
8399   APSInt Index;
8400   bool Success = true;
8401 
8402   // C++17's rules require us to evaluate the LHS first, regardless of which
8403   // side is the base.
8404   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8405     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8406                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8407       if (!Info.noteFailure())
8408         return false;
8409       Success = false;
8410     }
8411   }
8412 
8413   return Success &&
8414          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8415 }
8416 
8417 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8418   return evaluatePointer(E->getSubExpr(), Result);
8419 }
8420 
8421 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8422   if (!Visit(E->getSubExpr()))
8423     return false;
8424   // __real is a no-op on scalar lvalues.
8425   if (E->getSubExpr()->getType()->isAnyComplexType())
8426     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8427   return true;
8428 }
8429 
8430 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8431   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8432          "lvalue __imag__ on scalar?");
8433   if (!Visit(E->getSubExpr()))
8434     return false;
8435   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8436   return true;
8437 }
8438 
8439 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8440   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8441     return Error(UO);
8442 
8443   if (!this->Visit(UO->getSubExpr()))
8444     return false;
8445 
8446   return handleIncDec(
8447       this->Info, UO, Result, UO->getSubExpr()->getType(),
8448       UO->isIncrementOp(), nullptr);
8449 }
8450 
8451 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8452     const CompoundAssignOperator *CAO) {
8453   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8454     return Error(CAO);
8455 
8456   bool Success = true;
8457 
8458   // C++17 onwards require that we evaluate the RHS first.
8459   APValue RHS;
8460   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8461     if (!Info.noteFailure())
8462       return false;
8463     Success = false;
8464   }
8465 
8466   // The overall lvalue result is the result of evaluating the LHS.
8467   if (!this->Visit(CAO->getLHS()) || !Success)
8468     return false;
8469 
8470   return handleCompoundAssignment(
8471       this->Info, CAO,
8472       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8473       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8474 }
8475 
8476 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8477   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8478     return Error(E);
8479 
8480   bool Success = true;
8481 
8482   // C++17 onwards require that we evaluate the RHS first.
8483   APValue NewVal;
8484   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8485     if (!Info.noteFailure())
8486       return false;
8487     Success = false;
8488   }
8489 
8490   if (!this->Visit(E->getLHS()) || !Success)
8491     return false;
8492 
8493   if (Info.getLangOpts().CPlusPlus20 &&
8494       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8495     return false;
8496 
8497   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8498                           NewVal);
8499 }
8500 
8501 //===----------------------------------------------------------------------===//
8502 // Pointer Evaluation
8503 //===----------------------------------------------------------------------===//
8504 
8505 /// Attempts to compute the number of bytes available at the pointer
8506 /// returned by a function with the alloc_size attribute. Returns true if we
8507 /// were successful. Places an unsigned number into `Result`.
8508 ///
8509 /// This expects the given CallExpr to be a call to a function with an
8510 /// alloc_size attribute.
8511 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8512                                             const CallExpr *Call,
8513                                             llvm::APInt &Result) {
8514   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8515 
8516   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8517   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8518   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8519   if (Call->getNumArgs() <= SizeArgNo)
8520     return false;
8521 
8522   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8523     Expr::EvalResult ExprResult;
8524     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8525       return false;
8526     Into = ExprResult.Val.getInt();
8527     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8528       return false;
8529     Into = Into.zextOrSelf(BitsInSizeT);
8530     return true;
8531   };
8532 
8533   APSInt SizeOfElem;
8534   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8535     return false;
8536 
8537   if (!AllocSize->getNumElemsParam().isValid()) {
8538     Result = std::move(SizeOfElem);
8539     return true;
8540   }
8541 
8542   APSInt NumberOfElems;
8543   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8544   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8545     return false;
8546 
8547   bool Overflow;
8548   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8549   if (Overflow)
8550     return false;
8551 
8552   Result = std::move(BytesAvailable);
8553   return true;
8554 }
8555 
8556 /// Convenience function. LVal's base must be a call to an alloc_size
8557 /// function.
8558 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8559                                             const LValue &LVal,
8560                                             llvm::APInt &Result) {
8561   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8562          "Can't get the size of a non alloc_size function");
8563   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8564   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8565   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8566 }
8567 
8568 /// Attempts to evaluate the given LValueBase as the result of a call to
8569 /// a function with the alloc_size attribute. If it was possible to do so, this
8570 /// function will return true, make Result's Base point to said function call,
8571 /// and mark Result's Base as invalid.
8572 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8573                                       LValue &Result) {
8574   if (Base.isNull())
8575     return false;
8576 
8577   // Because we do no form of static analysis, we only support const variables.
8578   //
8579   // Additionally, we can't support parameters, nor can we support static
8580   // variables (in the latter case, use-before-assign isn't UB; in the former,
8581   // we have no clue what they'll be assigned to).
8582   const auto *VD =
8583       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8584   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8585     return false;
8586 
8587   const Expr *Init = VD->getAnyInitializer();
8588   if (!Init)
8589     return false;
8590 
8591   const Expr *E = Init->IgnoreParens();
8592   if (!tryUnwrapAllocSizeCall(E))
8593     return false;
8594 
8595   // Store E instead of E unwrapped so that the type of the LValue's base is
8596   // what the user wanted.
8597   Result.setInvalid(E);
8598 
8599   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8600   Result.addUnsizedArray(Info, E, Pointee);
8601   return true;
8602 }
8603 
8604 namespace {
8605 class PointerExprEvaluator
8606   : public ExprEvaluatorBase<PointerExprEvaluator> {
8607   LValue &Result;
8608   bool InvalidBaseOK;
8609 
8610   bool Success(const Expr *E) {
8611     Result.set(E);
8612     return true;
8613   }
8614 
8615   bool evaluateLValue(const Expr *E, LValue &Result) {
8616     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8617   }
8618 
8619   bool evaluatePointer(const Expr *E, LValue &Result) {
8620     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8621   }
8622 
8623   bool visitNonBuiltinCallExpr(const CallExpr *E);
8624 public:
8625 
8626   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8627       : ExprEvaluatorBaseTy(info), Result(Result),
8628         InvalidBaseOK(InvalidBaseOK) {}
8629 
8630   bool Success(const APValue &V, const Expr *E) {
8631     Result.setFrom(Info.Ctx, V);
8632     return true;
8633   }
8634   bool ZeroInitialization(const Expr *E) {
8635     Result.setNull(Info.Ctx, E->getType());
8636     return true;
8637   }
8638 
8639   bool VisitBinaryOperator(const BinaryOperator *E);
8640   bool VisitCastExpr(const CastExpr* E);
8641   bool VisitUnaryAddrOf(const UnaryOperator *E);
8642   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8643       { return Success(E); }
8644   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8645     if (E->isExpressibleAsConstantInitializer())
8646       return Success(E);
8647     if (Info.noteFailure())
8648       EvaluateIgnoredValue(Info, E->getSubExpr());
8649     return Error(E);
8650   }
8651   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8652       { return Success(E); }
8653   bool VisitCallExpr(const CallExpr *E);
8654   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8655   bool VisitBlockExpr(const BlockExpr *E) {
8656     if (!E->getBlockDecl()->hasCaptures())
8657       return Success(E);
8658     return Error(E);
8659   }
8660   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8661     // Can't look at 'this' when checking a potential constant expression.
8662     if (Info.checkingPotentialConstantExpression())
8663       return false;
8664     if (!Info.CurrentCall->This) {
8665       if (Info.getLangOpts().CPlusPlus11)
8666         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8667       else
8668         Info.FFDiag(E);
8669       return false;
8670     }
8671     Result = *Info.CurrentCall->This;
8672     // If we are inside a lambda's call operator, the 'this' expression refers
8673     // to the enclosing '*this' object (either by value or reference) which is
8674     // either copied into the closure object's field that represents the '*this'
8675     // or refers to '*this'.
8676     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8677       // Ensure we actually have captured 'this'. (an error will have
8678       // been previously reported if not).
8679       if (!Info.CurrentCall->LambdaThisCaptureField)
8680         return false;
8681 
8682       // Update 'Result' to refer to the data member/field of the closure object
8683       // that represents the '*this' capture.
8684       if (!HandleLValueMember(Info, E, Result,
8685                              Info.CurrentCall->LambdaThisCaptureField))
8686         return false;
8687       // If we captured '*this' by reference, replace the field with its referent.
8688       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8689               ->isPointerType()) {
8690         APValue RVal;
8691         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8692                                             RVal))
8693           return false;
8694 
8695         Result.setFrom(Info.Ctx, RVal);
8696       }
8697     }
8698     return true;
8699   }
8700 
8701   bool VisitCXXNewExpr(const CXXNewExpr *E);
8702 
8703   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8704     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8705     APValue LValResult = E->EvaluateInContext(
8706         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8707     Result.setFrom(Info.Ctx, LValResult);
8708     return true;
8709   }
8710 
8711   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8712     std::string ResultStr = E->ComputeName(Info.Ctx);
8713 
8714     QualType CharTy = Info.Ctx.CharTy.withConst();
8715     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8716                ResultStr.size() + 1);
8717     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8718                                                      ArrayType::Normal, 0);
8719 
8720     StringLiteral *SL =
8721         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8722                               /*Pascal*/ false, ArrayTy, E->getLocation());
8723 
8724     evaluateLValue(SL, Result);
8725     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8726     return true;
8727   }
8728 
8729   // FIXME: Missing: @protocol, @selector
8730 };
8731 } // end anonymous namespace
8732 
8733 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8734                             bool InvalidBaseOK) {
8735   assert(!E->isValueDependent());
8736   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8737   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8738 }
8739 
8740 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8741   if (E->getOpcode() != BO_Add &&
8742       E->getOpcode() != BO_Sub)
8743     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8744 
8745   const Expr *PExp = E->getLHS();
8746   const Expr *IExp = E->getRHS();
8747   if (IExp->getType()->isPointerType())
8748     std::swap(PExp, IExp);
8749 
8750   bool EvalPtrOK = evaluatePointer(PExp, Result);
8751   if (!EvalPtrOK && !Info.noteFailure())
8752     return false;
8753 
8754   llvm::APSInt Offset;
8755   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8756     return false;
8757 
8758   if (E->getOpcode() == BO_Sub)
8759     negateAsSigned(Offset);
8760 
8761   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8762   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8763 }
8764 
8765 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8766   return evaluateLValue(E->getSubExpr(), Result);
8767 }
8768 
8769 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8770   const Expr *SubExpr = E->getSubExpr();
8771 
8772   switch (E->getCastKind()) {
8773   default:
8774     break;
8775   case CK_BitCast:
8776   case CK_CPointerToObjCPointerCast:
8777   case CK_BlockPointerToObjCPointerCast:
8778   case CK_AnyPointerToBlockPointerCast:
8779   case CK_AddressSpaceConversion:
8780     if (!Visit(SubExpr))
8781       return false;
8782     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8783     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8784     // also static_casts, but we disallow them as a resolution to DR1312.
8785     if (!E->getType()->isVoidPointerType()) {
8786       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8787           !Result.IsNullPtr &&
8788           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8789                                           E->getType()->getPointeeType()) &&
8790           Info.getStdAllocatorCaller("allocate")) {
8791         // Inside a call to std::allocator::allocate and friends, we permit
8792         // casting from void* back to cv1 T* for a pointer that points to a
8793         // cv2 T.
8794       } else {
8795         Result.Designator.setInvalid();
8796         if (SubExpr->getType()->isVoidPointerType())
8797           CCEDiag(E, diag::note_constexpr_invalid_cast)
8798             << 3 << SubExpr->getType();
8799         else
8800           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8801       }
8802     }
8803     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8804       ZeroInitialization(E);
8805     return true;
8806 
8807   case CK_DerivedToBase:
8808   case CK_UncheckedDerivedToBase:
8809     if (!evaluatePointer(E->getSubExpr(), Result))
8810       return false;
8811     if (!Result.Base && Result.Offset.isZero())
8812       return true;
8813 
8814     // Now figure out the necessary offset to add to the base LV to get from
8815     // the derived class to the base class.
8816     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8817                                   castAs<PointerType>()->getPointeeType(),
8818                                 Result);
8819 
8820   case CK_BaseToDerived:
8821     if (!Visit(E->getSubExpr()))
8822       return false;
8823     if (!Result.Base && Result.Offset.isZero())
8824       return true;
8825     return HandleBaseToDerivedCast(Info, E, Result);
8826 
8827   case CK_Dynamic:
8828     if (!Visit(E->getSubExpr()))
8829       return false;
8830     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8831 
8832   case CK_NullToPointer:
8833     VisitIgnoredValue(E->getSubExpr());
8834     return ZeroInitialization(E);
8835 
8836   case CK_IntegralToPointer: {
8837     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8838 
8839     APValue Value;
8840     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8841       break;
8842 
8843     if (Value.isInt()) {
8844       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8845       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8846       Result.Base = (Expr*)nullptr;
8847       Result.InvalidBase = false;
8848       Result.Offset = CharUnits::fromQuantity(N);
8849       Result.Designator.setInvalid();
8850       Result.IsNullPtr = false;
8851       return true;
8852     } else {
8853       // Cast is of an lvalue, no need to change value.
8854       Result.setFrom(Info.Ctx, Value);
8855       return true;
8856     }
8857   }
8858 
8859   case CK_ArrayToPointerDecay: {
8860     if (SubExpr->isGLValue()) {
8861       if (!evaluateLValue(SubExpr, Result))
8862         return false;
8863     } else {
8864       APValue &Value = Info.CurrentCall->createTemporary(
8865           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8866       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8867         return false;
8868     }
8869     // The result is a pointer to the first element of the array.
8870     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8871     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8872       Result.addArray(Info, E, CAT);
8873     else
8874       Result.addUnsizedArray(Info, E, AT->getElementType());
8875     return true;
8876   }
8877 
8878   case CK_FunctionToPointerDecay:
8879     return evaluateLValue(SubExpr, Result);
8880 
8881   case CK_LValueToRValue: {
8882     LValue LVal;
8883     if (!evaluateLValue(E->getSubExpr(), LVal))
8884       return false;
8885 
8886     APValue RVal;
8887     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8888     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8889                                         LVal, RVal))
8890       return InvalidBaseOK &&
8891              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8892     return Success(RVal, E);
8893   }
8894   }
8895 
8896   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8897 }
8898 
8899 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8900                                 UnaryExprOrTypeTrait ExprKind) {
8901   // C++ [expr.alignof]p3:
8902   //     When alignof is applied to a reference type, the result is the
8903   //     alignment of the referenced type.
8904   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8905     T = Ref->getPointeeType();
8906 
8907   if (T.getQualifiers().hasUnaligned())
8908     return CharUnits::One();
8909 
8910   const bool AlignOfReturnsPreferred =
8911       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8912 
8913   // __alignof is defined to return the preferred alignment.
8914   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8915   // as well.
8916   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8917     return Info.Ctx.toCharUnitsFromBits(
8918       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8919   // alignof and _Alignof are defined to return the ABI alignment.
8920   else if (ExprKind == UETT_AlignOf)
8921     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8922   else
8923     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8924 }
8925 
8926 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8927                                 UnaryExprOrTypeTrait ExprKind) {
8928   E = E->IgnoreParens();
8929 
8930   // The kinds of expressions that we have special-case logic here for
8931   // should be kept up to date with the special checks for those
8932   // expressions in Sema.
8933 
8934   // alignof decl is always accepted, even if it doesn't make sense: we default
8935   // to 1 in those cases.
8936   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8937     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8938                                  /*RefAsPointee*/true);
8939 
8940   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8941     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8942                                  /*RefAsPointee*/true);
8943 
8944   return GetAlignOfType(Info, E->getType(), ExprKind);
8945 }
8946 
8947 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8948   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8949     return Info.Ctx.getDeclAlign(VD);
8950   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8951     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8952   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8953 }
8954 
8955 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8956 /// __builtin_is_aligned and __builtin_assume_aligned.
8957 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8958                                  EvalInfo &Info, APSInt &Alignment) {
8959   if (!EvaluateInteger(E, Alignment, Info))
8960     return false;
8961   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8962     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8963     return false;
8964   }
8965   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8966   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8967   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8968     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8969         << MaxValue << ForType << Alignment;
8970     return false;
8971   }
8972   // Ensure both alignment and source value have the same bit width so that we
8973   // don't assert when computing the resulting value.
8974   APSInt ExtAlignment =
8975       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8976   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8977          "Alignment should not be changed by ext/trunc");
8978   Alignment = ExtAlignment;
8979   assert(Alignment.getBitWidth() == SrcWidth);
8980   return true;
8981 }
8982 
8983 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8984 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8985   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8986     return true;
8987 
8988   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8989     return false;
8990 
8991   Result.setInvalid(E);
8992   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8993   Result.addUnsizedArray(Info, E, PointeeTy);
8994   return true;
8995 }
8996 
8997 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8998   if (IsConstantCall(E))
8999     return Success(E);
9000 
9001   if (unsigned BuiltinOp = E->getBuiltinCallee())
9002     return VisitBuiltinCallExpr(E, BuiltinOp);
9003 
9004   return visitNonBuiltinCallExpr(E);
9005 }
9006 
9007 // Determine if T is a character type for which we guarantee that
9008 // sizeof(T) == 1.
9009 static bool isOneByteCharacterType(QualType T) {
9010   return T->isCharType() || T->isChar8Type();
9011 }
9012 
9013 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9014                                                 unsigned BuiltinOp) {
9015   switch (BuiltinOp) {
9016   case Builtin::BI__builtin_addressof:
9017     return evaluateLValue(E->getArg(0), Result);
9018   case Builtin::BI__builtin_assume_aligned: {
9019     // We need to be very careful here because: if the pointer does not have the
9020     // asserted alignment, then the behavior is undefined, and undefined
9021     // behavior is non-constant.
9022     if (!evaluatePointer(E->getArg(0), Result))
9023       return false;
9024 
9025     LValue OffsetResult(Result);
9026     APSInt Alignment;
9027     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9028                               Alignment))
9029       return false;
9030     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9031 
9032     if (E->getNumArgs() > 2) {
9033       APSInt Offset;
9034       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9035         return false;
9036 
9037       int64_t AdditionalOffset = -Offset.getZExtValue();
9038       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9039     }
9040 
9041     // If there is a base object, then it must have the correct alignment.
9042     if (OffsetResult.Base) {
9043       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9044 
9045       if (BaseAlignment < Align) {
9046         Result.Designator.setInvalid();
9047         // FIXME: Add support to Diagnostic for long / long long.
9048         CCEDiag(E->getArg(0),
9049                 diag::note_constexpr_baa_insufficient_alignment) << 0
9050           << (unsigned)BaseAlignment.getQuantity()
9051           << (unsigned)Align.getQuantity();
9052         return false;
9053       }
9054     }
9055 
9056     // The offset must also have the correct alignment.
9057     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9058       Result.Designator.setInvalid();
9059 
9060       (OffsetResult.Base
9061            ? CCEDiag(E->getArg(0),
9062                      diag::note_constexpr_baa_insufficient_alignment) << 1
9063            : CCEDiag(E->getArg(0),
9064                      diag::note_constexpr_baa_value_insufficient_alignment))
9065         << (int)OffsetResult.Offset.getQuantity()
9066         << (unsigned)Align.getQuantity();
9067       return false;
9068     }
9069 
9070     return true;
9071   }
9072   case Builtin::BI__builtin_align_up:
9073   case Builtin::BI__builtin_align_down: {
9074     if (!evaluatePointer(E->getArg(0), Result))
9075       return false;
9076     APSInt Alignment;
9077     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9078                               Alignment))
9079       return false;
9080     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9081     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9082     // For align_up/align_down, we can return the same value if the alignment
9083     // is known to be greater or equal to the requested value.
9084     if (PtrAlign.getQuantity() >= Alignment)
9085       return true;
9086 
9087     // The alignment could be greater than the minimum at run-time, so we cannot
9088     // infer much about the resulting pointer value. One case is possible:
9089     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9090     // can infer the correct index if the requested alignment is smaller than
9091     // the base alignment so we can perform the computation on the offset.
9092     if (BaseAlignment.getQuantity() >= Alignment) {
9093       assert(Alignment.getBitWidth() <= 64 &&
9094              "Cannot handle > 64-bit address-space");
9095       uint64_t Alignment64 = Alignment.getZExtValue();
9096       CharUnits NewOffset = CharUnits::fromQuantity(
9097           BuiltinOp == Builtin::BI__builtin_align_down
9098               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9099               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9100       Result.adjustOffset(NewOffset - Result.Offset);
9101       // TODO: diagnose out-of-bounds values/only allow for arrays?
9102       return true;
9103     }
9104     // Otherwise, we cannot constant-evaluate the result.
9105     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9106         << Alignment;
9107     return false;
9108   }
9109   case Builtin::BI__builtin_operator_new:
9110     return HandleOperatorNewCall(Info, E, Result);
9111   case Builtin::BI__builtin_launder:
9112     return evaluatePointer(E->getArg(0), Result);
9113   case Builtin::BIstrchr:
9114   case Builtin::BIwcschr:
9115   case Builtin::BImemchr:
9116   case Builtin::BIwmemchr:
9117     if (Info.getLangOpts().CPlusPlus11)
9118       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9119         << /*isConstexpr*/0 << /*isConstructor*/0
9120         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9121     else
9122       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9123     LLVM_FALLTHROUGH;
9124   case Builtin::BI__builtin_strchr:
9125   case Builtin::BI__builtin_wcschr:
9126   case Builtin::BI__builtin_memchr:
9127   case Builtin::BI__builtin_char_memchr:
9128   case Builtin::BI__builtin_wmemchr: {
9129     if (!Visit(E->getArg(0)))
9130       return false;
9131     APSInt Desired;
9132     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9133       return false;
9134     uint64_t MaxLength = uint64_t(-1);
9135     if (BuiltinOp != Builtin::BIstrchr &&
9136         BuiltinOp != Builtin::BIwcschr &&
9137         BuiltinOp != Builtin::BI__builtin_strchr &&
9138         BuiltinOp != Builtin::BI__builtin_wcschr) {
9139       APSInt N;
9140       if (!EvaluateInteger(E->getArg(2), N, Info))
9141         return false;
9142       MaxLength = N.getExtValue();
9143     }
9144     // We cannot find the value if there are no candidates to match against.
9145     if (MaxLength == 0u)
9146       return ZeroInitialization(E);
9147     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9148         Result.Designator.Invalid)
9149       return false;
9150     QualType CharTy = Result.Designator.getType(Info.Ctx);
9151     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9152                      BuiltinOp == Builtin::BI__builtin_memchr;
9153     assert(IsRawByte ||
9154            Info.Ctx.hasSameUnqualifiedType(
9155                CharTy, E->getArg(0)->getType()->getPointeeType()));
9156     // Pointers to const void may point to objects of incomplete type.
9157     if (IsRawByte && CharTy->isIncompleteType()) {
9158       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9159       return false;
9160     }
9161     // Give up on byte-oriented matching against multibyte elements.
9162     // FIXME: We can compare the bytes in the correct order.
9163     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9164       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9165           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9166           << CharTy;
9167       return false;
9168     }
9169     // Figure out what value we're actually looking for (after converting to
9170     // the corresponding unsigned type if necessary).
9171     uint64_t DesiredVal;
9172     bool StopAtNull = false;
9173     switch (BuiltinOp) {
9174     case Builtin::BIstrchr:
9175     case Builtin::BI__builtin_strchr:
9176       // strchr compares directly to the passed integer, and therefore
9177       // always fails if given an int that is not a char.
9178       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9179                                                   E->getArg(1)->getType(),
9180                                                   Desired),
9181                                Desired))
9182         return ZeroInitialization(E);
9183       StopAtNull = true;
9184       LLVM_FALLTHROUGH;
9185     case Builtin::BImemchr:
9186     case Builtin::BI__builtin_memchr:
9187     case Builtin::BI__builtin_char_memchr:
9188       // memchr compares by converting both sides to unsigned char. That's also
9189       // correct for strchr if we get this far (to cope with plain char being
9190       // unsigned in the strchr case).
9191       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9192       break;
9193 
9194     case Builtin::BIwcschr:
9195     case Builtin::BI__builtin_wcschr:
9196       StopAtNull = true;
9197       LLVM_FALLTHROUGH;
9198     case Builtin::BIwmemchr:
9199     case Builtin::BI__builtin_wmemchr:
9200       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9201       DesiredVal = Desired.getZExtValue();
9202       break;
9203     }
9204 
9205     for (; MaxLength; --MaxLength) {
9206       APValue Char;
9207       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9208           !Char.isInt())
9209         return false;
9210       if (Char.getInt().getZExtValue() == DesiredVal)
9211         return true;
9212       if (StopAtNull && !Char.getInt())
9213         break;
9214       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9215         return false;
9216     }
9217     // Not found: return nullptr.
9218     return ZeroInitialization(E);
9219   }
9220 
9221   case Builtin::BImemcpy:
9222   case Builtin::BImemmove:
9223   case Builtin::BIwmemcpy:
9224   case Builtin::BIwmemmove:
9225     if (Info.getLangOpts().CPlusPlus11)
9226       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9227         << /*isConstexpr*/0 << /*isConstructor*/0
9228         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9229     else
9230       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9231     LLVM_FALLTHROUGH;
9232   case Builtin::BI__builtin_memcpy:
9233   case Builtin::BI__builtin_memmove:
9234   case Builtin::BI__builtin_wmemcpy:
9235   case Builtin::BI__builtin_wmemmove: {
9236     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9237                  BuiltinOp == Builtin::BIwmemmove ||
9238                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9239                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9240     bool Move = BuiltinOp == Builtin::BImemmove ||
9241                 BuiltinOp == Builtin::BIwmemmove ||
9242                 BuiltinOp == Builtin::BI__builtin_memmove ||
9243                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9244 
9245     // The result of mem* is the first argument.
9246     if (!Visit(E->getArg(0)))
9247       return false;
9248     LValue Dest = Result;
9249 
9250     LValue Src;
9251     if (!EvaluatePointer(E->getArg(1), Src, Info))
9252       return false;
9253 
9254     APSInt N;
9255     if (!EvaluateInteger(E->getArg(2), N, Info))
9256       return false;
9257     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9258 
9259     // If the size is zero, we treat this as always being a valid no-op.
9260     // (Even if one of the src and dest pointers is null.)
9261     if (!N)
9262       return true;
9263 
9264     // Otherwise, if either of the operands is null, we can't proceed. Don't
9265     // try to determine the type of the copied objects, because there aren't
9266     // any.
9267     if (!Src.Base || !Dest.Base) {
9268       APValue Val;
9269       (!Src.Base ? Src : Dest).moveInto(Val);
9270       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9271           << Move << WChar << !!Src.Base
9272           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9273       return false;
9274     }
9275     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9276       return false;
9277 
9278     // We require that Src and Dest are both pointers to arrays of
9279     // trivially-copyable type. (For the wide version, the designator will be
9280     // invalid if the designated object is not a wchar_t.)
9281     QualType T = Dest.Designator.getType(Info.Ctx);
9282     QualType SrcT = Src.Designator.getType(Info.Ctx);
9283     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9284       // FIXME: Consider using our bit_cast implementation to support this.
9285       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9286       return false;
9287     }
9288     if (T->isIncompleteType()) {
9289       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9290       return false;
9291     }
9292     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9293       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9294       return false;
9295     }
9296 
9297     // Figure out how many T's we're copying.
9298     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9299     if (!WChar) {
9300       uint64_t Remainder;
9301       llvm::APInt OrigN = N;
9302       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9303       if (Remainder) {
9304         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9305             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9306             << (unsigned)TSize;
9307         return false;
9308       }
9309     }
9310 
9311     // Check that the copying will remain within the arrays, just so that we
9312     // can give a more meaningful diagnostic. This implicitly also checks that
9313     // N fits into 64 bits.
9314     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9315     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9316     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9317       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9318           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9319           << toString(N, 10, /*Signed*/false);
9320       return false;
9321     }
9322     uint64_t NElems = N.getZExtValue();
9323     uint64_t NBytes = NElems * TSize;
9324 
9325     // Check for overlap.
9326     int Direction = 1;
9327     if (HasSameBase(Src, Dest)) {
9328       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9329       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9330       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9331         // Dest is inside the source region.
9332         if (!Move) {
9333           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9334           return false;
9335         }
9336         // For memmove and friends, copy backwards.
9337         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9338             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9339           return false;
9340         Direction = -1;
9341       } else if (!Move && SrcOffset >= DestOffset &&
9342                  SrcOffset - DestOffset < NBytes) {
9343         // Src is inside the destination region for memcpy: invalid.
9344         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9345         return false;
9346       }
9347     }
9348 
9349     while (true) {
9350       APValue Val;
9351       // FIXME: Set WantObjectRepresentation to true if we're copying a
9352       // char-like type?
9353       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9354           !handleAssignment(Info, E, Dest, T, Val))
9355         return false;
9356       // Do not iterate past the last element; if we're copying backwards, that
9357       // might take us off the start of the array.
9358       if (--NElems == 0)
9359         return true;
9360       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9361           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9362         return false;
9363     }
9364   }
9365 
9366   default:
9367     break;
9368   }
9369 
9370   return visitNonBuiltinCallExpr(E);
9371 }
9372 
9373 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9374                                      APValue &Result, const InitListExpr *ILE,
9375                                      QualType AllocType);
9376 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9377                                           APValue &Result,
9378                                           const CXXConstructExpr *CCE,
9379                                           QualType AllocType);
9380 
9381 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9382   if (!Info.getLangOpts().CPlusPlus20)
9383     Info.CCEDiag(E, diag::note_constexpr_new);
9384 
9385   // We cannot speculatively evaluate a delete expression.
9386   if (Info.SpeculativeEvaluationDepth)
9387     return false;
9388 
9389   FunctionDecl *OperatorNew = E->getOperatorNew();
9390 
9391   bool IsNothrow = false;
9392   bool IsPlacement = false;
9393   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9394       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9395     // FIXME Support array placement new.
9396     assert(E->getNumPlacementArgs() == 1);
9397     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9398       return false;
9399     if (Result.Designator.Invalid)
9400       return false;
9401     IsPlacement = true;
9402   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9403     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9404         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9405     return false;
9406   } else if (E->getNumPlacementArgs()) {
9407     // The only new-placement list we support is of the form (std::nothrow).
9408     //
9409     // FIXME: There is no restriction on this, but it's not clear that any
9410     // other form makes any sense. We get here for cases such as:
9411     //
9412     //   new (std::align_val_t{N}) X(int)
9413     //
9414     // (which should presumably be valid only if N is a multiple of
9415     // alignof(int), and in any case can't be deallocated unless N is
9416     // alignof(X) and X has new-extended alignment).
9417     if (E->getNumPlacementArgs() != 1 ||
9418         !E->getPlacementArg(0)->getType()->isNothrowT())
9419       return Error(E, diag::note_constexpr_new_placement);
9420 
9421     LValue Nothrow;
9422     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9423       return false;
9424     IsNothrow = true;
9425   }
9426 
9427   const Expr *Init = E->getInitializer();
9428   const InitListExpr *ResizedArrayILE = nullptr;
9429   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9430   bool ValueInit = false;
9431 
9432   QualType AllocType = E->getAllocatedType();
9433   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9434     const Expr *Stripped = *ArraySize;
9435     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9436          Stripped = ICE->getSubExpr())
9437       if (ICE->getCastKind() != CK_NoOp &&
9438           ICE->getCastKind() != CK_IntegralCast)
9439         break;
9440 
9441     llvm::APSInt ArrayBound;
9442     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9443       return false;
9444 
9445     // C++ [expr.new]p9:
9446     //   The expression is erroneous if:
9447     //   -- [...] its value before converting to size_t [or] applying the
9448     //      second standard conversion sequence is less than zero
9449     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9450       if (IsNothrow)
9451         return ZeroInitialization(E);
9452 
9453       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9454           << ArrayBound << (*ArraySize)->getSourceRange();
9455       return false;
9456     }
9457 
9458     //   -- its value is such that the size of the allocated object would
9459     //      exceed the implementation-defined limit
9460     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9461                                                 ArrayBound) >
9462         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9463       if (IsNothrow)
9464         return ZeroInitialization(E);
9465 
9466       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9467         << ArrayBound << (*ArraySize)->getSourceRange();
9468       return false;
9469     }
9470 
9471     //   -- the new-initializer is a braced-init-list and the number of
9472     //      array elements for which initializers are provided [...]
9473     //      exceeds the number of elements to initialize
9474     if (!Init) {
9475       // No initialization is performed.
9476     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9477                isa<ImplicitValueInitExpr>(Init)) {
9478       ValueInit = true;
9479     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9480       ResizedArrayCCE = CCE;
9481     } else {
9482       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9483       assert(CAT && "unexpected type for array initializer");
9484 
9485       unsigned Bits =
9486           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9487       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9488       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9489       if (InitBound.ugt(AllocBound)) {
9490         if (IsNothrow)
9491           return ZeroInitialization(E);
9492 
9493         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9494             << toString(AllocBound, 10, /*Signed=*/false)
9495             << toString(InitBound, 10, /*Signed=*/false)
9496             << (*ArraySize)->getSourceRange();
9497         return false;
9498       }
9499 
9500       // If the sizes differ, we must have an initializer list, and we need
9501       // special handling for this case when we initialize.
9502       if (InitBound != AllocBound)
9503         ResizedArrayILE = cast<InitListExpr>(Init);
9504     }
9505 
9506     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9507                                               ArrayType::Normal, 0);
9508   } else {
9509     assert(!AllocType->isArrayType() &&
9510            "array allocation with non-array new");
9511   }
9512 
9513   APValue *Val;
9514   if (IsPlacement) {
9515     AccessKinds AK = AK_Construct;
9516     struct FindObjectHandler {
9517       EvalInfo &Info;
9518       const Expr *E;
9519       QualType AllocType;
9520       const AccessKinds AccessKind;
9521       APValue *Value;
9522 
9523       typedef bool result_type;
9524       bool failed() { return false; }
9525       bool found(APValue &Subobj, QualType SubobjType) {
9526         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9527         // old name of the object to be used to name the new object.
9528         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9529           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9530             SubobjType << AllocType;
9531           return false;
9532         }
9533         Value = &Subobj;
9534         return true;
9535       }
9536       bool found(APSInt &Value, QualType SubobjType) {
9537         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9538         return false;
9539       }
9540       bool found(APFloat &Value, QualType SubobjType) {
9541         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9542         return false;
9543       }
9544     } Handler = {Info, E, AllocType, AK, nullptr};
9545 
9546     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9547     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9548       return false;
9549 
9550     Val = Handler.Value;
9551 
9552     // [basic.life]p1:
9553     //   The lifetime of an object o of type T ends when [...] the storage
9554     //   which the object occupies is [...] reused by an object that is not
9555     //   nested within o (6.6.2).
9556     *Val = APValue();
9557   } else {
9558     // Perform the allocation and obtain a pointer to the resulting object.
9559     Val = Info.createHeapAlloc(E, AllocType, Result);
9560     if (!Val)
9561       return false;
9562   }
9563 
9564   if (ValueInit) {
9565     ImplicitValueInitExpr VIE(AllocType);
9566     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9567       return false;
9568   } else if (ResizedArrayILE) {
9569     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9570                                   AllocType))
9571       return false;
9572   } else if (ResizedArrayCCE) {
9573     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9574                                        AllocType))
9575       return false;
9576   } else if (Init) {
9577     if (!EvaluateInPlace(*Val, Info, Result, Init))
9578       return false;
9579   } else if (!getDefaultInitValue(AllocType, *Val)) {
9580     return false;
9581   }
9582 
9583   // Array new returns a pointer to the first element, not a pointer to the
9584   // array.
9585   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9586     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9587 
9588   return true;
9589 }
9590 //===----------------------------------------------------------------------===//
9591 // Member Pointer Evaluation
9592 //===----------------------------------------------------------------------===//
9593 
9594 namespace {
9595 class MemberPointerExprEvaluator
9596   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9597   MemberPtr &Result;
9598 
9599   bool Success(const ValueDecl *D) {
9600     Result = MemberPtr(D);
9601     return true;
9602   }
9603 public:
9604 
9605   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9606     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9607 
9608   bool Success(const APValue &V, const Expr *E) {
9609     Result.setFrom(V);
9610     return true;
9611   }
9612   bool ZeroInitialization(const Expr *E) {
9613     return Success((const ValueDecl*)nullptr);
9614   }
9615 
9616   bool VisitCastExpr(const CastExpr *E);
9617   bool VisitUnaryAddrOf(const UnaryOperator *E);
9618 };
9619 } // end anonymous namespace
9620 
9621 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9622                                   EvalInfo &Info) {
9623   assert(!E->isValueDependent());
9624   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9625   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9626 }
9627 
9628 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9629   switch (E->getCastKind()) {
9630   default:
9631     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9632 
9633   case CK_NullToMemberPointer:
9634     VisitIgnoredValue(E->getSubExpr());
9635     return ZeroInitialization(E);
9636 
9637   case CK_BaseToDerivedMemberPointer: {
9638     if (!Visit(E->getSubExpr()))
9639       return false;
9640     if (E->path_empty())
9641       return true;
9642     // Base-to-derived member pointer casts store the path in derived-to-base
9643     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9644     // the wrong end of the derived->base arc, so stagger the path by one class.
9645     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9646     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9647          PathI != PathE; ++PathI) {
9648       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9649       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9650       if (!Result.castToDerived(Derived))
9651         return Error(E);
9652     }
9653     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9654     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9655       return Error(E);
9656     return true;
9657   }
9658 
9659   case CK_DerivedToBaseMemberPointer:
9660     if (!Visit(E->getSubExpr()))
9661       return false;
9662     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9663          PathE = E->path_end(); PathI != PathE; ++PathI) {
9664       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9665       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9666       if (!Result.castToBase(Base))
9667         return Error(E);
9668     }
9669     return true;
9670   }
9671 }
9672 
9673 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9674   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9675   // member can be formed.
9676   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9677 }
9678 
9679 //===----------------------------------------------------------------------===//
9680 // Record Evaluation
9681 //===----------------------------------------------------------------------===//
9682 
9683 namespace {
9684   class RecordExprEvaluator
9685   : public ExprEvaluatorBase<RecordExprEvaluator> {
9686     const LValue &This;
9687     APValue &Result;
9688   public:
9689 
9690     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9691       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9692 
9693     bool Success(const APValue &V, const Expr *E) {
9694       Result = V;
9695       return true;
9696     }
9697     bool ZeroInitialization(const Expr *E) {
9698       return ZeroInitialization(E, E->getType());
9699     }
9700     bool ZeroInitialization(const Expr *E, QualType T);
9701 
9702     bool VisitCallExpr(const CallExpr *E) {
9703       return handleCallExpr(E, Result, &This);
9704     }
9705     bool VisitCastExpr(const CastExpr *E);
9706     bool VisitInitListExpr(const InitListExpr *E);
9707     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9708       return VisitCXXConstructExpr(E, E->getType());
9709     }
9710     bool VisitLambdaExpr(const LambdaExpr *E);
9711     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9712     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9713     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9714     bool VisitBinCmp(const BinaryOperator *E);
9715   };
9716 }
9717 
9718 /// Perform zero-initialization on an object of non-union class type.
9719 /// C++11 [dcl.init]p5:
9720 ///  To zero-initialize an object or reference of type T means:
9721 ///    [...]
9722 ///    -- if T is a (possibly cv-qualified) non-union class type,
9723 ///       each non-static data member and each base-class subobject is
9724 ///       zero-initialized
9725 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9726                                           const RecordDecl *RD,
9727                                           const LValue &This, APValue &Result) {
9728   assert(!RD->isUnion() && "Expected non-union class type");
9729   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9730   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9731                    std::distance(RD->field_begin(), RD->field_end()));
9732 
9733   if (RD->isInvalidDecl()) return false;
9734   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9735 
9736   if (CD) {
9737     unsigned Index = 0;
9738     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9739            End = CD->bases_end(); I != End; ++I, ++Index) {
9740       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9741       LValue Subobject = This;
9742       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9743         return false;
9744       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9745                                          Result.getStructBase(Index)))
9746         return false;
9747     }
9748   }
9749 
9750   for (const auto *I : RD->fields()) {
9751     // -- if T is a reference type, no initialization is performed.
9752     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9753       continue;
9754 
9755     LValue Subobject = This;
9756     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9757       return false;
9758 
9759     ImplicitValueInitExpr VIE(I->getType());
9760     if (!EvaluateInPlace(
9761           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9762       return false;
9763   }
9764 
9765   return true;
9766 }
9767 
9768 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9769   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9770   if (RD->isInvalidDecl()) return false;
9771   if (RD->isUnion()) {
9772     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9773     // object's first non-static named data member is zero-initialized
9774     RecordDecl::field_iterator I = RD->field_begin();
9775     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9776       ++I;
9777     if (I == RD->field_end()) {
9778       Result = APValue((const FieldDecl*)nullptr);
9779       return true;
9780     }
9781 
9782     LValue Subobject = This;
9783     if (!HandleLValueMember(Info, E, Subobject, *I))
9784       return false;
9785     Result = APValue(*I);
9786     ImplicitValueInitExpr VIE(I->getType());
9787     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9788   }
9789 
9790   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9791     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9792     return false;
9793   }
9794 
9795   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9796 }
9797 
9798 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9799   switch (E->getCastKind()) {
9800   default:
9801     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9802 
9803   case CK_ConstructorConversion:
9804     return Visit(E->getSubExpr());
9805 
9806   case CK_DerivedToBase:
9807   case CK_UncheckedDerivedToBase: {
9808     APValue DerivedObject;
9809     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9810       return false;
9811     if (!DerivedObject.isStruct())
9812       return Error(E->getSubExpr());
9813 
9814     // Derived-to-base rvalue conversion: just slice off the derived part.
9815     APValue *Value = &DerivedObject;
9816     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9817     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9818          PathE = E->path_end(); PathI != PathE; ++PathI) {
9819       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9820       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9821       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9822       RD = Base;
9823     }
9824     Result = *Value;
9825     return true;
9826   }
9827   }
9828 }
9829 
9830 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9831   if (E->isTransparent())
9832     return Visit(E->getInit(0));
9833 
9834   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9835   if (RD->isInvalidDecl()) return false;
9836   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9837   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9838 
9839   EvalInfo::EvaluatingConstructorRAII EvalObj(
9840       Info,
9841       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9842       CXXRD && CXXRD->getNumBases());
9843 
9844   if (RD->isUnion()) {
9845     const FieldDecl *Field = E->getInitializedFieldInUnion();
9846     Result = APValue(Field);
9847     if (!Field)
9848       return true;
9849 
9850     // If the initializer list for a union does not contain any elements, the
9851     // first element of the union is value-initialized.
9852     // FIXME: The element should be initialized from an initializer list.
9853     //        Is this difference ever observable for initializer lists which
9854     //        we don't build?
9855     ImplicitValueInitExpr VIE(Field->getType());
9856     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9857 
9858     LValue Subobject = This;
9859     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9860       return false;
9861 
9862     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9863     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9864                                   isa<CXXDefaultInitExpr>(InitExpr));
9865 
9866     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9867       if (Field->isBitField())
9868         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9869                                      Field);
9870       return true;
9871     }
9872 
9873     return false;
9874   }
9875 
9876   if (!Result.hasValue())
9877     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9878                      std::distance(RD->field_begin(), RD->field_end()));
9879   unsigned ElementNo = 0;
9880   bool Success = true;
9881 
9882   // Initialize base classes.
9883   if (CXXRD && CXXRD->getNumBases()) {
9884     for (const auto &Base : CXXRD->bases()) {
9885       assert(ElementNo < E->getNumInits() && "missing init for base class");
9886       const Expr *Init = E->getInit(ElementNo);
9887 
9888       LValue Subobject = This;
9889       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9890         return false;
9891 
9892       APValue &FieldVal = Result.getStructBase(ElementNo);
9893       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9894         if (!Info.noteFailure())
9895           return false;
9896         Success = false;
9897       }
9898       ++ElementNo;
9899     }
9900 
9901     EvalObj.finishedConstructingBases();
9902   }
9903 
9904   // Initialize members.
9905   for (const auto *Field : RD->fields()) {
9906     // Anonymous bit-fields are not considered members of the class for
9907     // purposes of aggregate initialization.
9908     if (Field->isUnnamedBitfield())
9909       continue;
9910 
9911     LValue Subobject = This;
9912 
9913     bool HaveInit = ElementNo < E->getNumInits();
9914 
9915     // FIXME: Diagnostics here should point to the end of the initializer
9916     // list, not the start.
9917     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9918                             Subobject, Field, &Layout))
9919       return false;
9920 
9921     // Perform an implicit value-initialization for members beyond the end of
9922     // the initializer list.
9923     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9924     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9925 
9926     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9927     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9928                                   isa<CXXDefaultInitExpr>(Init));
9929 
9930     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9931     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9932         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9933                                                        FieldVal, Field))) {
9934       if (!Info.noteFailure())
9935         return false;
9936       Success = false;
9937     }
9938   }
9939 
9940   EvalObj.finishedConstructingFields();
9941 
9942   return Success;
9943 }
9944 
9945 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9946                                                 QualType T) {
9947   // Note that E's type is not necessarily the type of our class here; we might
9948   // be initializing an array element instead.
9949   const CXXConstructorDecl *FD = E->getConstructor();
9950   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9951 
9952   bool ZeroInit = E->requiresZeroInitialization();
9953   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9954     // If we've already performed zero-initialization, we're already done.
9955     if (Result.hasValue())
9956       return true;
9957 
9958     if (ZeroInit)
9959       return ZeroInitialization(E, T);
9960 
9961     return getDefaultInitValue(T, Result);
9962   }
9963 
9964   const FunctionDecl *Definition = nullptr;
9965   auto Body = FD->getBody(Definition);
9966 
9967   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9968     return false;
9969 
9970   // Avoid materializing a temporary for an elidable copy/move constructor.
9971   if (E->isElidable() && !ZeroInit) {
9972     // FIXME: This only handles the simplest case, where the source object
9973     //        is passed directly as the first argument to the constructor.
9974     //        This should also handle stepping though implicit casts and
9975     //        and conversion sequences which involve two steps, with a
9976     //        conversion operator followed by a converting constructor.
9977     const Expr *SrcObj = E->getArg(0);
9978     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9979     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9980     if (const MaterializeTemporaryExpr *ME =
9981             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9982       return Visit(ME->getSubExpr());
9983   }
9984 
9985   if (ZeroInit && !ZeroInitialization(E, T))
9986     return false;
9987 
9988   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9989   return HandleConstructorCall(E, This, Args,
9990                                cast<CXXConstructorDecl>(Definition), Info,
9991                                Result);
9992 }
9993 
9994 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9995     const CXXInheritedCtorInitExpr *E) {
9996   if (!Info.CurrentCall) {
9997     assert(Info.checkingPotentialConstantExpression());
9998     return false;
9999   }
10000 
10001   const CXXConstructorDecl *FD = E->getConstructor();
10002   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10003     return false;
10004 
10005   const FunctionDecl *Definition = nullptr;
10006   auto Body = FD->getBody(Definition);
10007 
10008   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10009     return false;
10010 
10011   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10012                                cast<CXXConstructorDecl>(Definition), Info,
10013                                Result);
10014 }
10015 
10016 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10017     const CXXStdInitializerListExpr *E) {
10018   const ConstantArrayType *ArrayType =
10019       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10020 
10021   LValue Array;
10022   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10023     return false;
10024 
10025   // Get a pointer to the first element of the array.
10026   Array.addArray(Info, E, ArrayType);
10027 
10028   auto InvalidType = [&] {
10029     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10030       << E->getType();
10031     return false;
10032   };
10033 
10034   // FIXME: Perform the checks on the field types in SemaInit.
10035   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10036   RecordDecl::field_iterator Field = Record->field_begin();
10037   if (Field == Record->field_end())
10038     return InvalidType();
10039 
10040   // Start pointer.
10041   if (!Field->getType()->isPointerType() ||
10042       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10043                             ArrayType->getElementType()))
10044     return InvalidType();
10045 
10046   // FIXME: What if the initializer_list type has base classes, etc?
10047   Result = APValue(APValue::UninitStruct(), 0, 2);
10048   Array.moveInto(Result.getStructField(0));
10049 
10050   if (++Field == Record->field_end())
10051     return InvalidType();
10052 
10053   if (Field->getType()->isPointerType() &&
10054       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10055                            ArrayType->getElementType())) {
10056     // End pointer.
10057     if (!HandleLValueArrayAdjustment(Info, E, Array,
10058                                      ArrayType->getElementType(),
10059                                      ArrayType->getSize().getZExtValue()))
10060       return false;
10061     Array.moveInto(Result.getStructField(1));
10062   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10063     // Length.
10064     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10065   else
10066     return InvalidType();
10067 
10068   if (++Field != Record->field_end())
10069     return InvalidType();
10070 
10071   return true;
10072 }
10073 
10074 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10075   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10076   if (ClosureClass->isInvalidDecl())
10077     return false;
10078 
10079   const size_t NumFields =
10080       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10081 
10082   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10083                                             E->capture_init_end()) &&
10084          "The number of lambda capture initializers should equal the number of "
10085          "fields within the closure type");
10086 
10087   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10088   // Iterate through all the lambda's closure object's fields and initialize
10089   // them.
10090   auto *CaptureInitIt = E->capture_init_begin();
10091   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10092   bool Success = true;
10093   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10094   for (const auto *Field : ClosureClass->fields()) {
10095     assert(CaptureInitIt != E->capture_init_end());
10096     // Get the initializer for this field
10097     Expr *const CurFieldInit = *CaptureInitIt++;
10098 
10099     // If there is no initializer, either this is a VLA or an error has
10100     // occurred.
10101     if (!CurFieldInit)
10102       return Error(E);
10103 
10104     LValue Subobject = This;
10105 
10106     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10107       return false;
10108 
10109     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10110     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10111       if (!Info.keepEvaluatingAfterFailure())
10112         return false;
10113       Success = false;
10114     }
10115     ++CaptureIt;
10116   }
10117   return Success;
10118 }
10119 
10120 static bool EvaluateRecord(const Expr *E, const LValue &This,
10121                            APValue &Result, EvalInfo &Info) {
10122   assert(!E->isValueDependent());
10123   assert(E->isPRValue() && E->getType()->isRecordType() &&
10124          "can't evaluate expression as a record rvalue");
10125   return RecordExprEvaluator(Info, This, Result).Visit(E);
10126 }
10127 
10128 //===----------------------------------------------------------------------===//
10129 // Temporary Evaluation
10130 //
10131 // Temporaries are represented in the AST as rvalues, but generally behave like
10132 // lvalues. The full-object of which the temporary is a subobject is implicitly
10133 // materialized so that a reference can bind to it.
10134 //===----------------------------------------------------------------------===//
10135 namespace {
10136 class TemporaryExprEvaluator
10137   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10138 public:
10139   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10140     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10141 
10142   /// Visit an expression which constructs the value of this temporary.
10143   bool VisitConstructExpr(const Expr *E) {
10144     APValue &Value = Info.CurrentCall->createTemporary(
10145         E, E->getType(), ScopeKind::FullExpression, Result);
10146     return EvaluateInPlace(Value, Info, Result, E);
10147   }
10148 
10149   bool VisitCastExpr(const CastExpr *E) {
10150     switch (E->getCastKind()) {
10151     default:
10152       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10153 
10154     case CK_ConstructorConversion:
10155       return VisitConstructExpr(E->getSubExpr());
10156     }
10157   }
10158   bool VisitInitListExpr(const InitListExpr *E) {
10159     return VisitConstructExpr(E);
10160   }
10161   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10162     return VisitConstructExpr(E);
10163   }
10164   bool VisitCallExpr(const CallExpr *E) {
10165     return VisitConstructExpr(E);
10166   }
10167   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10168     return VisitConstructExpr(E);
10169   }
10170   bool VisitLambdaExpr(const LambdaExpr *E) {
10171     return VisitConstructExpr(E);
10172   }
10173 };
10174 } // end anonymous namespace
10175 
10176 /// Evaluate an expression of record type as a temporary.
10177 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10178   assert(!E->isValueDependent());
10179   assert(E->isPRValue() && E->getType()->isRecordType());
10180   return TemporaryExprEvaluator(Info, Result).Visit(E);
10181 }
10182 
10183 //===----------------------------------------------------------------------===//
10184 // Vector Evaluation
10185 //===----------------------------------------------------------------------===//
10186 
10187 namespace {
10188   class VectorExprEvaluator
10189   : public ExprEvaluatorBase<VectorExprEvaluator> {
10190     APValue &Result;
10191   public:
10192 
10193     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10194       : ExprEvaluatorBaseTy(info), Result(Result) {}
10195 
10196     bool Success(ArrayRef<APValue> V, const Expr *E) {
10197       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10198       // FIXME: remove this APValue copy.
10199       Result = APValue(V.data(), V.size());
10200       return true;
10201     }
10202     bool Success(const APValue &V, const Expr *E) {
10203       assert(V.isVector());
10204       Result = V;
10205       return true;
10206     }
10207     bool ZeroInitialization(const Expr *E);
10208 
10209     bool VisitUnaryReal(const UnaryOperator *E)
10210       { return Visit(E->getSubExpr()); }
10211     bool VisitCastExpr(const CastExpr* E);
10212     bool VisitInitListExpr(const InitListExpr *E);
10213     bool VisitUnaryImag(const UnaryOperator *E);
10214     bool VisitBinaryOperator(const BinaryOperator *E);
10215     bool VisitUnaryOperator(const UnaryOperator *E);
10216     // FIXME: Missing: conditional operator (for GNU
10217     //                 conditional select), shufflevector, ExtVectorElementExpr
10218   };
10219 } // end anonymous namespace
10220 
10221 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10222   assert(E->isPRValue() && E->getType()->isVectorType() &&
10223          "not a vector prvalue");
10224   return VectorExprEvaluator(Info, Result).Visit(E);
10225 }
10226 
10227 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10228   const VectorType *VTy = E->getType()->castAs<VectorType>();
10229   unsigned NElts = VTy->getNumElements();
10230 
10231   const Expr *SE = E->getSubExpr();
10232   QualType SETy = SE->getType();
10233 
10234   switch (E->getCastKind()) {
10235   case CK_VectorSplat: {
10236     APValue Val = APValue();
10237     if (SETy->isIntegerType()) {
10238       APSInt IntResult;
10239       if (!EvaluateInteger(SE, IntResult, Info))
10240         return false;
10241       Val = APValue(std::move(IntResult));
10242     } else if (SETy->isRealFloatingType()) {
10243       APFloat FloatResult(0.0);
10244       if (!EvaluateFloat(SE, FloatResult, Info))
10245         return false;
10246       Val = APValue(std::move(FloatResult));
10247     } else {
10248       return Error(E);
10249     }
10250 
10251     // Splat and create vector APValue.
10252     SmallVector<APValue, 4> Elts(NElts, Val);
10253     return Success(Elts, E);
10254   }
10255   case CK_BitCast: {
10256     // Evaluate the operand into an APInt we can extract from.
10257     llvm::APInt SValInt;
10258     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10259       return false;
10260     // Extract the elements
10261     QualType EltTy = VTy->getElementType();
10262     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10263     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10264     SmallVector<APValue, 4> Elts;
10265     if (EltTy->isRealFloatingType()) {
10266       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10267       unsigned FloatEltSize = EltSize;
10268       if (&Sem == &APFloat::x87DoubleExtended())
10269         FloatEltSize = 80;
10270       for (unsigned i = 0; i < NElts; i++) {
10271         llvm::APInt Elt;
10272         if (BigEndian)
10273           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10274         else
10275           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10276         Elts.push_back(APValue(APFloat(Sem, Elt)));
10277       }
10278     } else if (EltTy->isIntegerType()) {
10279       for (unsigned i = 0; i < NElts; i++) {
10280         llvm::APInt Elt;
10281         if (BigEndian)
10282           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10283         else
10284           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10285         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10286       }
10287     } else {
10288       return Error(E);
10289     }
10290     return Success(Elts, E);
10291   }
10292   default:
10293     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10294   }
10295 }
10296 
10297 bool
10298 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10299   const VectorType *VT = E->getType()->castAs<VectorType>();
10300   unsigned NumInits = E->getNumInits();
10301   unsigned NumElements = VT->getNumElements();
10302 
10303   QualType EltTy = VT->getElementType();
10304   SmallVector<APValue, 4> Elements;
10305 
10306   // The number of initializers can be less than the number of
10307   // vector elements. For OpenCL, this can be due to nested vector
10308   // initialization. For GCC compatibility, missing trailing elements
10309   // should be initialized with zeroes.
10310   unsigned CountInits = 0, CountElts = 0;
10311   while (CountElts < NumElements) {
10312     // Handle nested vector initialization.
10313     if (CountInits < NumInits
10314         && E->getInit(CountInits)->getType()->isVectorType()) {
10315       APValue v;
10316       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10317         return Error(E);
10318       unsigned vlen = v.getVectorLength();
10319       for (unsigned j = 0; j < vlen; j++)
10320         Elements.push_back(v.getVectorElt(j));
10321       CountElts += vlen;
10322     } else if (EltTy->isIntegerType()) {
10323       llvm::APSInt sInt(32);
10324       if (CountInits < NumInits) {
10325         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10326           return false;
10327       } else // trailing integer zero.
10328         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10329       Elements.push_back(APValue(sInt));
10330       CountElts++;
10331     } else {
10332       llvm::APFloat f(0.0);
10333       if (CountInits < NumInits) {
10334         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10335           return false;
10336       } else // trailing float zero.
10337         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10338       Elements.push_back(APValue(f));
10339       CountElts++;
10340     }
10341     CountInits++;
10342   }
10343   return Success(Elements, E);
10344 }
10345 
10346 bool
10347 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10348   const auto *VT = E->getType()->castAs<VectorType>();
10349   QualType EltTy = VT->getElementType();
10350   APValue ZeroElement;
10351   if (EltTy->isIntegerType())
10352     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10353   else
10354     ZeroElement =
10355         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10356 
10357   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10358   return Success(Elements, E);
10359 }
10360 
10361 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10362   VisitIgnoredValue(E->getSubExpr());
10363   return ZeroInitialization(E);
10364 }
10365 
10366 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10367   BinaryOperatorKind Op = E->getOpcode();
10368   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10369          "Operation not supported on vector types");
10370 
10371   if (Op == BO_Comma)
10372     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10373 
10374   Expr *LHS = E->getLHS();
10375   Expr *RHS = E->getRHS();
10376 
10377   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10378          "Must both be vector types");
10379   // Checking JUST the types are the same would be fine, except shifts don't
10380   // need to have their types be the same (since you always shift by an int).
10381   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10382              E->getType()->castAs<VectorType>()->getNumElements() &&
10383          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10384              E->getType()->castAs<VectorType>()->getNumElements() &&
10385          "All operands must be the same size.");
10386 
10387   APValue LHSValue;
10388   APValue RHSValue;
10389   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10390   if (!LHSOK && !Info.noteFailure())
10391     return false;
10392   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10393     return false;
10394 
10395   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10396     return false;
10397 
10398   return Success(LHSValue, E);
10399 }
10400 
10401 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10402                                                          QualType ResultTy,
10403                                                          UnaryOperatorKind Op,
10404                                                          APValue Elt) {
10405   switch (Op) {
10406   case UO_Plus:
10407     // Nothing to do here.
10408     return Elt;
10409   case UO_Minus:
10410     if (Elt.getKind() == APValue::Int) {
10411       Elt.getInt().negate();
10412     } else {
10413       assert(Elt.getKind() == APValue::Float &&
10414              "Vector can only be int or float type");
10415       Elt.getFloat().changeSign();
10416     }
10417     return Elt;
10418   case UO_Not:
10419     // This is only valid for integral types anyway, so we don't have to handle
10420     // float here.
10421     assert(Elt.getKind() == APValue::Int &&
10422            "Vector operator ~ can only be int");
10423     Elt.getInt().flipAllBits();
10424     return Elt;
10425   case UO_LNot: {
10426     if (Elt.getKind() == APValue::Int) {
10427       Elt.getInt() = !Elt.getInt();
10428       // operator ! on vectors returns -1 for 'truth', so negate it.
10429       Elt.getInt().negate();
10430       return Elt;
10431     }
10432     assert(Elt.getKind() == APValue::Float &&
10433            "Vector can only be int or float type");
10434     // Float types result in an int of the same size, but -1 for true, or 0 for
10435     // false.
10436     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10437                      ResultTy->isUnsignedIntegerType()};
10438     if (Elt.getFloat().isZero())
10439       EltResult.setAllBits();
10440     else
10441       EltResult.clearAllBits();
10442 
10443     return APValue{EltResult};
10444   }
10445   default:
10446     // FIXME: Implement the rest of the unary operators.
10447     return llvm::None;
10448   }
10449 }
10450 
10451 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10452   Expr *SubExpr = E->getSubExpr();
10453   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10454   // This result element type differs in the case of negating a floating point
10455   // vector, since the result type is the a vector of the equivilant sized
10456   // integer.
10457   const QualType ResultEltTy = VD->getElementType();
10458   UnaryOperatorKind Op = E->getOpcode();
10459 
10460   APValue SubExprValue;
10461   if (!Evaluate(SubExprValue, Info, SubExpr))
10462     return false;
10463 
10464   // FIXME: This vector evaluator someday needs to be changed to be LValue
10465   // aware/keep LValue information around, rather than dealing with just vector
10466   // types directly. Until then, we cannot handle cases where the operand to
10467   // these unary operators is an LValue. The only case I've been able to see
10468   // cause this is operator++ assigning to a member expression (only valid in
10469   // altivec compilations) in C mode, so this shouldn't limit us too much.
10470   if (SubExprValue.isLValue())
10471     return false;
10472 
10473   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10474          "Vector length doesn't match type?");
10475 
10476   SmallVector<APValue, 4> ResultElements;
10477   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10478     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10479         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10480     if (!Elt)
10481       return false;
10482     ResultElements.push_back(*Elt);
10483   }
10484   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10485 }
10486 
10487 //===----------------------------------------------------------------------===//
10488 // Array Evaluation
10489 //===----------------------------------------------------------------------===//
10490 
10491 namespace {
10492   class ArrayExprEvaluator
10493   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10494     const LValue &This;
10495     APValue &Result;
10496   public:
10497 
10498     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10499       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10500 
10501     bool Success(const APValue &V, const Expr *E) {
10502       assert(V.isArray() && "expected array");
10503       Result = V;
10504       return true;
10505     }
10506 
10507     bool ZeroInitialization(const Expr *E) {
10508       const ConstantArrayType *CAT =
10509           Info.Ctx.getAsConstantArrayType(E->getType());
10510       if (!CAT) {
10511         if (E->getType()->isIncompleteArrayType()) {
10512           // We can be asked to zero-initialize a flexible array member; this
10513           // is represented as an ImplicitValueInitExpr of incomplete array
10514           // type. In this case, the array has zero elements.
10515           Result = APValue(APValue::UninitArray(), 0, 0);
10516           return true;
10517         }
10518         // FIXME: We could handle VLAs here.
10519         return Error(E);
10520       }
10521 
10522       Result = APValue(APValue::UninitArray(), 0,
10523                        CAT->getSize().getZExtValue());
10524       if (!Result.hasArrayFiller())
10525         return true;
10526 
10527       // Zero-initialize all elements.
10528       LValue Subobject = This;
10529       Subobject.addArray(Info, E, CAT);
10530       ImplicitValueInitExpr VIE(CAT->getElementType());
10531       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10532     }
10533 
10534     bool VisitCallExpr(const CallExpr *E) {
10535       return handleCallExpr(E, Result, &This);
10536     }
10537     bool VisitInitListExpr(const InitListExpr *E,
10538                            QualType AllocType = QualType());
10539     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10540     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10541     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10542                                const LValue &Subobject,
10543                                APValue *Value, QualType Type);
10544     bool VisitStringLiteral(const StringLiteral *E,
10545                             QualType AllocType = QualType()) {
10546       expandStringLiteral(Info, E, Result, AllocType);
10547       return true;
10548     }
10549   };
10550 } // end anonymous namespace
10551 
10552 static bool EvaluateArray(const Expr *E, const LValue &This,
10553                           APValue &Result, EvalInfo &Info) {
10554   assert(!E->isValueDependent());
10555   assert(E->isPRValue() && E->getType()->isArrayType() &&
10556          "not an array prvalue");
10557   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10558 }
10559 
10560 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10561                                      APValue &Result, const InitListExpr *ILE,
10562                                      QualType AllocType) {
10563   assert(!ILE->isValueDependent());
10564   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10565          "not an array prvalue");
10566   return ArrayExprEvaluator(Info, This, Result)
10567       .VisitInitListExpr(ILE, AllocType);
10568 }
10569 
10570 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10571                                           APValue &Result,
10572                                           const CXXConstructExpr *CCE,
10573                                           QualType AllocType) {
10574   assert(!CCE->isValueDependent());
10575   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10576          "not an array prvalue");
10577   return ArrayExprEvaluator(Info, This, Result)
10578       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10579 }
10580 
10581 // Return true iff the given array filler may depend on the element index.
10582 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10583   // For now, just allow non-class value-initialization and initialization
10584   // lists comprised of them.
10585   if (isa<ImplicitValueInitExpr>(FillerExpr))
10586     return false;
10587   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10588     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10589       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10590         return true;
10591     }
10592     return false;
10593   }
10594   return true;
10595 }
10596 
10597 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10598                                            QualType AllocType) {
10599   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10600       AllocType.isNull() ? E->getType() : AllocType);
10601   if (!CAT)
10602     return Error(E);
10603 
10604   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10605   // an appropriately-typed string literal enclosed in braces.
10606   if (E->isStringLiteralInit()) {
10607     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10608     // FIXME: Support ObjCEncodeExpr here once we support it in
10609     // ArrayExprEvaluator generally.
10610     if (!SL)
10611       return Error(E);
10612     return VisitStringLiteral(SL, AllocType);
10613   }
10614   // Any other transparent list init will need proper handling of the
10615   // AllocType; we can't just recurse to the inner initializer.
10616   assert(!E->isTransparent() &&
10617          "transparent array list initialization is not string literal init?");
10618 
10619   bool Success = true;
10620 
10621   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10622          "zero-initialized array shouldn't have any initialized elts");
10623   APValue Filler;
10624   if (Result.isArray() && Result.hasArrayFiller())
10625     Filler = Result.getArrayFiller();
10626 
10627   unsigned NumEltsToInit = E->getNumInits();
10628   unsigned NumElts = CAT->getSize().getZExtValue();
10629   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10630 
10631   // If the initializer might depend on the array index, run it for each
10632   // array element.
10633   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10634     NumEltsToInit = NumElts;
10635 
10636   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10637                           << NumEltsToInit << ".\n");
10638 
10639   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10640 
10641   // If the array was previously zero-initialized, preserve the
10642   // zero-initialized values.
10643   if (Filler.hasValue()) {
10644     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10645       Result.getArrayInitializedElt(I) = Filler;
10646     if (Result.hasArrayFiller())
10647       Result.getArrayFiller() = Filler;
10648   }
10649 
10650   LValue Subobject = This;
10651   Subobject.addArray(Info, E, CAT);
10652   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10653     const Expr *Init =
10654         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10655     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10656                          Info, Subobject, Init) ||
10657         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10658                                      CAT->getElementType(), 1)) {
10659       if (!Info.noteFailure())
10660         return false;
10661       Success = false;
10662     }
10663   }
10664 
10665   if (!Result.hasArrayFiller())
10666     return Success;
10667 
10668   // If we get here, we have a trivial filler, which we can just evaluate
10669   // once and splat over the rest of the array elements.
10670   assert(FillerExpr && "no array filler for incomplete init list");
10671   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10672                          FillerExpr) && Success;
10673 }
10674 
10675 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10676   LValue CommonLV;
10677   if (E->getCommonExpr() &&
10678       !Evaluate(Info.CurrentCall->createTemporary(
10679                     E->getCommonExpr(),
10680                     getStorageType(Info.Ctx, E->getCommonExpr()),
10681                     ScopeKind::FullExpression, CommonLV),
10682                 Info, E->getCommonExpr()->getSourceExpr()))
10683     return false;
10684 
10685   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10686 
10687   uint64_t Elements = CAT->getSize().getZExtValue();
10688   Result = APValue(APValue::UninitArray(), Elements, Elements);
10689 
10690   LValue Subobject = This;
10691   Subobject.addArray(Info, E, CAT);
10692 
10693   bool Success = true;
10694   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10695     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10696                          Info, Subobject, E->getSubExpr()) ||
10697         !HandleLValueArrayAdjustment(Info, E, Subobject,
10698                                      CAT->getElementType(), 1)) {
10699       if (!Info.noteFailure())
10700         return false;
10701       Success = false;
10702     }
10703   }
10704 
10705   return Success;
10706 }
10707 
10708 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10709   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10710 }
10711 
10712 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10713                                                const LValue &Subobject,
10714                                                APValue *Value,
10715                                                QualType Type) {
10716   bool HadZeroInit = Value->hasValue();
10717 
10718   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10719     unsigned FinalSize = CAT->getSize().getZExtValue();
10720 
10721     // Preserve the array filler if we had prior zero-initialization.
10722     APValue Filler =
10723       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10724                                              : APValue();
10725 
10726     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10727     if (FinalSize == 0)
10728       return true;
10729 
10730     LValue ArrayElt = Subobject;
10731     ArrayElt.addArray(Info, E, CAT);
10732     // We do the whole initialization in two passes, first for just one element,
10733     // then for the whole array. It's possible we may find out we can't do const
10734     // init in the first pass, in which case we avoid allocating a potentially
10735     // large array. We don't do more passes because expanding array requires
10736     // copying the data, which is wasteful.
10737     for (const unsigned N : {1u, FinalSize}) {
10738       unsigned OldElts = Value->getArrayInitializedElts();
10739       if (OldElts == N)
10740         break;
10741 
10742       // Expand the array to appropriate size.
10743       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10744       for (unsigned I = 0; I < OldElts; ++I)
10745         NewValue.getArrayInitializedElt(I).swap(
10746             Value->getArrayInitializedElt(I));
10747       Value->swap(NewValue);
10748 
10749       if (HadZeroInit)
10750         for (unsigned I = OldElts; I < N; ++I)
10751           Value->getArrayInitializedElt(I) = Filler;
10752 
10753       // Initialize the elements.
10754       for (unsigned I = OldElts; I < N; ++I) {
10755         if (!VisitCXXConstructExpr(E, ArrayElt,
10756                                    &Value->getArrayInitializedElt(I),
10757                                    CAT->getElementType()) ||
10758             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10759                                          CAT->getElementType(), 1))
10760           return false;
10761         // When checking for const initilization any diagnostic is considered
10762         // an error.
10763         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10764             !Info.keepEvaluatingAfterFailure())
10765           return false;
10766       }
10767     }
10768 
10769     return true;
10770   }
10771 
10772   if (!Type->isRecordType())
10773     return Error(E);
10774 
10775   return RecordExprEvaluator(Info, Subobject, *Value)
10776              .VisitCXXConstructExpr(E, Type);
10777 }
10778 
10779 //===----------------------------------------------------------------------===//
10780 // Integer Evaluation
10781 //
10782 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10783 // types and back in constant folding. Integer values are thus represented
10784 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10785 //===----------------------------------------------------------------------===//
10786 
10787 namespace {
10788 class IntExprEvaluator
10789         : public ExprEvaluatorBase<IntExprEvaluator> {
10790   APValue &Result;
10791 public:
10792   IntExprEvaluator(EvalInfo &info, APValue &result)
10793       : ExprEvaluatorBaseTy(info), Result(result) {}
10794 
10795   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10796     assert(E->getType()->isIntegralOrEnumerationType() &&
10797            "Invalid evaluation result.");
10798     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10799            "Invalid evaluation result.");
10800     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10801            "Invalid evaluation result.");
10802     Result = APValue(SI);
10803     return true;
10804   }
10805   bool Success(const llvm::APSInt &SI, const Expr *E) {
10806     return Success(SI, E, Result);
10807   }
10808 
10809   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10810     assert(E->getType()->isIntegralOrEnumerationType() &&
10811            "Invalid evaluation result.");
10812     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10813            "Invalid evaluation result.");
10814     Result = APValue(APSInt(I));
10815     Result.getInt().setIsUnsigned(
10816                             E->getType()->isUnsignedIntegerOrEnumerationType());
10817     return true;
10818   }
10819   bool Success(const llvm::APInt &I, const Expr *E) {
10820     return Success(I, E, Result);
10821   }
10822 
10823   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10824     assert(E->getType()->isIntegralOrEnumerationType() &&
10825            "Invalid evaluation result.");
10826     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10827     return true;
10828   }
10829   bool Success(uint64_t Value, const Expr *E) {
10830     return Success(Value, E, Result);
10831   }
10832 
10833   bool Success(CharUnits Size, const Expr *E) {
10834     return Success(Size.getQuantity(), E);
10835   }
10836 
10837   bool Success(const APValue &V, const Expr *E) {
10838     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10839       Result = V;
10840       return true;
10841     }
10842     return Success(V.getInt(), E);
10843   }
10844 
10845   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10846 
10847   //===--------------------------------------------------------------------===//
10848   //                            Visitor Methods
10849   //===--------------------------------------------------------------------===//
10850 
10851   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10852     return Success(E->getValue(), E);
10853   }
10854   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10855     return Success(E->getValue(), E);
10856   }
10857 
10858   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10859   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10860     if (CheckReferencedDecl(E, E->getDecl()))
10861       return true;
10862 
10863     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10864   }
10865   bool VisitMemberExpr(const MemberExpr *E) {
10866     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10867       VisitIgnoredBaseExpression(E->getBase());
10868       return true;
10869     }
10870 
10871     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10872   }
10873 
10874   bool VisitCallExpr(const CallExpr *E);
10875   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10876   bool VisitBinaryOperator(const BinaryOperator *E);
10877   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10878   bool VisitUnaryOperator(const UnaryOperator *E);
10879 
10880   bool VisitCastExpr(const CastExpr* E);
10881   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10882 
10883   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10884     return Success(E->getValue(), E);
10885   }
10886 
10887   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10888     return Success(E->getValue(), E);
10889   }
10890 
10891   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10892     if (Info.ArrayInitIndex == uint64_t(-1)) {
10893       // We were asked to evaluate this subexpression independent of the
10894       // enclosing ArrayInitLoopExpr. We can't do that.
10895       Info.FFDiag(E);
10896       return false;
10897     }
10898     return Success(Info.ArrayInitIndex, E);
10899   }
10900 
10901   // Note, GNU defines __null as an integer, not a pointer.
10902   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10903     return ZeroInitialization(E);
10904   }
10905 
10906   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10907     return Success(E->getValue(), E);
10908   }
10909 
10910   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10911     return Success(E->getValue(), E);
10912   }
10913 
10914   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10915     return Success(E->getValue(), E);
10916   }
10917 
10918   bool VisitUnaryReal(const UnaryOperator *E);
10919   bool VisitUnaryImag(const UnaryOperator *E);
10920 
10921   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10922   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10923   bool VisitSourceLocExpr(const SourceLocExpr *E);
10924   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10925   bool VisitRequiresExpr(const RequiresExpr *E);
10926   // FIXME: Missing: array subscript of vector, member of vector
10927 };
10928 
10929 class FixedPointExprEvaluator
10930     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10931   APValue &Result;
10932 
10933  public:
10934   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10935       : ExprEvaluatorBaseTy(info), Result(result) {}
10936 
10937   bool Success(const llvm::APInt &I, const Expr *E) {
10938     return Success(
10939         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10940   }
10941 
10942   bool Success(uint64_t Value, const Expr *E) {
10943     return Success(
10944         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10945   }
10946 
10947   bool Success(const APValue &V, const Expr *E) {
10948     return Success(V.getFixedPoint(), E);
10949   }
10950 
10951   bool Success(const APFixedPoint &V, const Expr *E) {
10952     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10953     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10954            "Invalid evaluation result.");
10955     Result = APValue(V);
10956     return true;
10957   }
10958 
10959   //===--------------------------------------------------------------------===//
10960   //                            Visitor Methods
10961   //===--------------------------------------------------------------------===//
10962 
10963   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10964     return Success(E->getValue(), E);
10965   }
10966 
10967   bool VisitCastExpr(const CastExpr *E);
10968   bool VisitUnaryOperator(const UnaryOperator *E);
10969   bool VisitBinaryOperator(const BinaryOperator *E);
10970 };
10971 } // end anonymous namespace
10972 
10973 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10974 /// produce either the integer value or a pointer.
10975 ///
10976 /// GCC has a heinous extension which folds casts between pointer types and
10977 /// pointer-sized integral types. We support this by allowing the evaluation of
10978 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10979 /// Some simple arithmetic on such values is supported (they are treated much
10980 /// like char*).
10981 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10982                                     EvalInfo &Info) {
10983   assert(!E->isValueDependent());
10984   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10985   return IntExprEvaluator(Info, Result).Visit(E);
10986 }
10987 
10988 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10989   assert(!E->isValueDependent());
10990   APValue Val;
10991   if (!EvaluateIntegerOrLValue(E, Val, Info))
10992     return false;
10993   if (!Val.isInt()) {
10994     // FIXME: It would be better to produce the diagnostic for casting
10995     //        a pointer to an integer.
10996     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10997     return false;
10998   }
10999   Result = Val.getInt();
11000   return true;
11001 }
11002 
11003 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11004   APValue Evaluated = E->EvaluateInContext(
11005       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11006   return Success(Evaluated, E);
11007 }
11008 
11009 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11010                                EvalInfo &Info) {
11011   assert(!E->isValueDependent());
11012   if (E->getType()->isFixedPointType()) {
11013     APValue Val;
11014     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11015       return false;
11016     if (!Val.isFixedPoint())
11017       return false;
11018 
11019     Result = Val.getFixedPoint();
11020     return true;
11021   }
11022   return false;
11023 }
11024 
11025 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11026                                         EvalInfo &Info) {
11027   assert(!E->isValueDependent());
11028   if (E->getType()->isIntegerType()) {
11029     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11030     APSInt Val;
11031     if (!EvaluateInteger(E, Val, Info))
11032       return false;
11033     Result = APFixedPoint(Val, FXSema);
11034     return true;
11035   } else if (E->getType()->isFixedPointType()) {
11036     return EvaluateFixedPoint(E, Result, Info);
11037   }
11038   return false;
11039 }
11040 
11041 /// Check whether the given declaration can be directly converted to an integral
11042 /// rvalue. If not, no diagnostic is produced; there are other things we can
11043 /// try.
11044 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11045   // Enums are integer constant exprs.
11046   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11047     // Check for signedness/width mismatches between E type and ECD value.
11048     bool SameSign = (ECD->getInitVal().isSigned()
11049                      == E->getType()->isSignedIntegerOrEnumerationType());
11050     bool SameWidth = (ECD->getInitVal().getBitWidth()
11051                       == Info.Ctx.getIntWidth(E->getType()));
11052     if (SameSign && SameWidth)
11053       return Success(ECD->getInitVal(), E);
11054     else {
11055       // Get rid of mismatch (otherwise Success assertions will fail)
11056       // by computing a new value matching the type of E.
11057       llvm::APSInt Val = ECD->getInitVal();
11058       if (!SameSign)
11059         Val.setIsSigned(!ECD->getInitVal().isSigned());
11060       if (!SameWidth)
11061         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11062       return Success(Val, E);
11063     }
11064   }
11065   return false;
11066 }
11067 
11068 /// Values returned by __builtin_classify_type, chosen to match the values
11069 /// produced by GCC's builtin.
11070 enum class GCCTypeClass {
11071   None = -1,
11072   Void = 0,
11073   Integer = 1,
11074   // GCC reserves 2 for character types, but instead classifies them as
11075   // integers.
11076   Enum = 3,
11077   Bool = 4,
11078   Pointer = 5,
11079   // GCC reserves 6 for references, but appears to never use it (because
11080   // expressions never have reference type, presumably).
11081   PointerToDataMember = 7,
11082   RealFloat = 8,
11083   Complex = 9,
11084   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11085   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11086   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11087   // uses 12 for that purpose, same as for a class or struct. Maybe it
11088   // internally implements a pointer to member as a struct?  Who knows.
11089   PointerToMemberFunction = 12, // Not a bug, see above.
11090   ClassOrStruct = 12,
11091   Union = 13,
11092   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11093   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11094   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11095   // literals.
11096 };
11097 
11098 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11099 /// as GCC.
11100 static GCCTypeClass
11101 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11102   assert(!T->isDependentType() && "unexpected dependent type");
11103 
11104   QualType CanTy = T.getCanonicalType();
11105   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11106 
11107   switch (CanTy->getTypeClass()) {
11108 #define TYPE(ID, BASE)
11109 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11110 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11111 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11112 #include "clang/AST/TypeNodes.inc"
11113   case Type::Auto:
11114   case Type::DeducedTemplateSpecialization:
11115       llvm_unreachable("unexpected non-canonical or dependent type");
11116 
11117   case Type::Builtin:
11118     switch (BT->getKind()) {
11119 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11120 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11121     case BuiltinType::ID: return GCCTypeClass::Integer;
11122 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11123     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11124 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11125     case BuiltinType::ID: break;
11126 #include "clang/AST/BuiltinTypes.def"
11127     case BuiltinType::Void:
11128       return GCCTypeClass::Void;
11129 
11130     case BuiltinType::Bool:
11131       return GCCTypeClass::Bool;
11132 
11133     case BuiltinType::Char_U:
11134     case BuiltinType::UChar:
11135     case BuiltinType::WChar_U:
11136     case BuiltinType::Char8:
11137     case BuiltinType::Char16:
11138     case BuiltinType::Char32:
11139     case BuiltinType::UShort:
11140     case BuiltinType::UInt:
11141     case BuiltinType::ULong:
11142     case BuiltinType::ULongLong:
11143     case BuiltinType::UInt128:
11144       return GCCTypeClass::Integer;
11145 
11146     case BuiltinType::UShortAccum:
11147     case BuiltinType::UAccum:
11148     case BuiltinType::ULongAccum:
11149     case BuiltinType::UShortFract:
11150     case BuiltinType::UFract:
11151     case BuiltinType::ULongFract:
11152     case BuiltinType::SatUShortAccum:
11153     case BuiltinType::SatUAccum:
11154     case BuiltinType::SatULongAccum:
11155     case BuiltinType::SatUShortFract:
11156     case BuiltinType::SatUFract:
11157     case BuiltinType::SatULongFract:
11158       return GCCTypeClass::None;
11159 
11160     case BuiltinType::NullPtr:
11161 
11162     case BuiltinType::ObjCId:
11163     case BuiltinType::ObjCClass:
11164     case BuiltinType::ObjCSel:
11165 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11166     case BuiltinType::Id:
11167 #include "clang/Basic/OpenCLImageTypes.def"
11168 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11169     case BuiltinType::Id:
11170 #include "clang/Basic/OpenCLExtensionTypes.def"
11171     case BuiltinType::OCLSampler:
11172     case BuiltinType::OCLEvent:
11173     case BuiltinType::OCLClkEvent:
11174     case BuiltinType::OCLQueue:
11175     case BuiltinType::OCLReserveID:
11176 #define SVE_TYPE(Name, Id, SingletonId) \
11177     case BuiltinType::Id:
11178 #include "clang/Basic/AArch64SVEACLETypes.def"
11179 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11180     case BuiltinType::Id:
11181 #include "clang/Basic/PPCTypes.def"
11182 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11183 #include "clang/Basic/RISCVVTypes.def"
11184       return GCCTypeClass::None;
11185 
11186     case BuiltinType::Dependent:
11187       llvm_unreachable("unexpected dependent type");
11188     };
11189     llvm_unreachable("unexpected placeholder type");
11190 
11191   case Type::Enum:
11192     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11193 
11194   case Type::Pointer:
11195   case Type::ConstantArray:
11196   case Type::VariableArray:
11197   case Type::IncompleteArray:
11198   case Type::FunctionNoProto:
11199   case Type::FunctionProto:
11200     return GCCTypeClass::Pointer;
11201 
11202   case Type::MemberPointer:
11203     return CanTy->isMemberDataPointerType()
11204                ? GCCTypeClass::PointerToDataMember
11205                : GCCTypeClass::PointerToMemberFunction;
11206 
11207   case Type::Complex:
11208     return GCCTypeClass::Complex;
11209 
11210   case Type::Record:
11211     return CanTy->isUnionType() ? GCCTypeClass::Union
11212                                 : GCCTypeClass::ClassOrStruct;
11213 
11214   case Type::Atomic:
11215     // GCC classifies _Atomic T the same as T.
11216     return EvaluateBuiltinClassifyType(
11217         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11218 
11219   case Type::BlockPointer:
11220   case Type::Vector:
11221   case Type::ExtVector:
11222   case Type::ConstantMatrix:
11223   case Type::ObjCObject:
11224   case Type::ObjCInterface:
11225   case Type::ObjCObjectPointer:
11226   case Type::Pipe:
11227   case Type::BitInt:
11228     // GCC classifies vectors as None. We follow its lead and classify all
11229     // other types that don't fit into the regular classification the same way.
11230     return GCCTypeClass::None;
11231 
11232   case Type::LValueReference:
11233   case Type::RValueReference:
11234     llvm_unreachable("invalid type for expression");
11235   }
11236 
11237   llvm_unreachable("unexpected type class");
11238 }
11239 
11240 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11241 /// as GCC.
11242 static GCCTypeClass
11243 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11244   // If no argument was supplied, default to None. This isn't
11245   // ideal, however it is what gcc does.
11246   if (E->getNumArgs() == 0)
11247     return GCCTypeClass::None;
11248 
11249   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11250   // being an ICE, but still folds it to a constant using the type of the first
11251   // argument.
11252   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11253 }
11254 
11255 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11256 /// __builtin_constant_p when applied to the given pointer.
11257 ///
11258 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11259 /// or it points to the first character of a string literal.
11260 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11261   APValue::LValueBase Base = LV.getLValueBase();
11262   if (Base.isNull()) {
11263     // A null base is acceptable.
11264     return true;
11265   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11266     if (!isa<StringLiteral>(E))
11267       return false;
11268     return LV.getLValueOffset().isZero();
11269   } else if (Base.is<TypeInfoLValue>()) {
11270     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11271     // evaluate to true.
11272     return true;
11273   } else {
11274     // Any other base is not constant enough for GCC.
11275     return false;
11276   }
11277 }
11278 
11279 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11280 /// GCC as we can manage.
11281 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11282   // This evaluation is not permitted to have side-effects, so evaluate it in
11283   // a speculative evaluation context.
11284   SpeculativeEvaluationRAII SpeculativeEval(Info);
11285 
11286   // Constant-folding is always enabled for the operand of __builtin_constant_p
11287   // (even when the enclosing evaluation context otherwise requires a strict
11288   // language-specific constant expression).
11289   FoldConstant Fold(Info, true);
11290 
11291   QualType ArgType = Arg->getType();
11292 
11293   // __builtin_constant_p always has one operand. The rules which gcc follows
11294   // are not precisely documented, but are as follows:
11295   //
11296   //  - If the operand is of integral, floating, complex or enumeration type,
11297   //    and can be folded to a known value of that type, it returns 1.
11298   //  - If the operand can be folded to a pointer to the first character
11299   //    of a string literal (or such a pointer cast to an integral type)
11300   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11301   //
11302   // Otherwise, it returns 0.
11303   //
11304   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11305   // its support for this did not work prior to GCC 9 and is not yet well
11306   // understood.
11307   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11308       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11309       ArgType->isNullPtrType()) {
11310     APValue V;
11311     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11312       Fold.keepDiagnostics();
11313       return false;
11314     }
11315 
11316     // For a pointer (possibly cast to integer), there are special rules.
11317     if (V.getKind() == APValue::LValue)
11318       return EvaluateBuiltinConstantPForLValue(V);
11319 
11320     // Otherwise, any constant value is good enough.
11321     return V.hasValue();
11322   }
11323 
11324   // Anything else isn't considered to be sufficiently constant.
11325   return false;
11326 }
11327 
11328 /// Retrieves the "underlying object type" of the given expression,
11329 /// as used by __builtin_object_size.
11330 static QualType getObjectType(APValue::LValueBase B) {
11331   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11332     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11333       return VD->getType();
11334   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11335     if (isa<CompoundLiteralExpr>(E))
11336       return E->getType();
11337   } else if (B.is<TypeInfoLValue>()) {
11338     return B.getTypeInfoType();
11339   } else if (B.is<DynamicAllocLValue>()) {
11340     return B.getDynamicAllocType();
11341   }
11342 
11343   return QualType();
11344 }
11345 
11346 /// A more selective version of E->IgnoreParenCasts for
11347 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11348 /// to change the type of E.
11349 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11350 ///
11351 /// Always returns an RValue with a pointer representation.
11352 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11353   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11354 
11355   auto *NoParens = E->IgnoreParens();
11356   auto *Cast = dyn_cast<CastExpr>(NoParens);
11357   if (Cast == nullptr)
11358     return NoParens;
11359 
11360   // We only conservatively allow a few kinds of casts, because this code is
11361   // inherently a simple solution that seeks to support the common case.
11362   auto CastKind = Cast->getCastKind();
11363   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11364       CastKind != CK_AddressSpaceConversion)
11365     return NoParens;
11366 
11367   auto *SubExpr = Cast->getSubExpr();
11368   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11369     return NoParens;
11370   return ignorePointerCastsAndParens(SubExpr);
11371 }
11372 
11373 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11374 /// record layout. e.g.
11375 ///   struct { struct { int a, b; } fst, snd; } obj;
11376 ///   obj.fst   // no
11377 ///   obj.snd   // yes
11378 ///   obj.fst.a // no
11379 ///   obj.fst.b // no
11380 ///   obj.snd.a // no
11381 ///   obj.snd.b // yes
11382 ///
11383 /// Please note: this function is specialized for how __builtin_object_size
11384 /// views "objects".
11385 ///
11386 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11387 /// correct result, it will always return true.
11388 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11389   assert(!LVal.Designator.Invalid);
11390 
11391   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11392     const RecordDecl *Parent = FD->getParent();
11393     Invalid = Parent->isInvalidDecl();
11394     if (Invalid || Parent->isUnion())
11395       return true;
11396     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11397     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11398   };
11399 
11400   auto &Base = LVal.getLValueBase();
11401   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11402     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11403       bool Invalid;
11404       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11405         return Invalid;
11406     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11407       for (auto *FD : IFD->chain()) {
11408         bool Invalid;
11409         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11410           return Invalid;
11411       }
11412     }
11413   }
11414 
11415   unsigned I = 0;
11416   QualType BaseType = getType(Base);
11417   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11418     // If we don't know the array bound, conservatively assume we're looking at
11419     // the final array element.
11420     ++I;
11421     if (BaseType->isIncompleteArrayType())
11422       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11423     else
11424       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11425   }
11426 
11427   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11428     const auto &Entry = LVal.Designator.Entries[I];
11429     if (BaseType->isArrayType()) {
11430       // Because __builtin_object_size treats arrays as objects, we can ignore
11431       // the index iff this is the last array in the Designator.
11432       if (I + 1 == E)
11433         return true;
11434       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11435       uint64_t Index = Entry.getAsArrayIndex();
11436       if (Index + 1 != CAT->getSize())
11437         return false;
11438       BaseType = CAT->getElementType();
11439     } else if (BaseType->isAnyComplexType()) {
11440       const auto *CT = BaseType->castAs<ComplexType>();
11441       uint64_t Index = Entry.getAsArrayIndex();
11442       if (Index != 1)
11443         return false;
11444       BaseType = CT->getElementType();
11445     } else if (auto *FD = getAsField(Entry)) {
11446       bool Invalid;
11447       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11448         return Invalid;
11449       BaseType = FD->getType();
11450     } else {
11451       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11452       return false;
11453     }
11454   }
11455   return true;
11456 }
11457 
11458 /// Tests to see if the LValue has a user-specified designator (that isn't
11459 /// necessarily valid). Note that this always returns 'true' if the LValue has
11460 /// an unsized array as its first designator entry, because there's currently no
11461 /// way to tell if the user typed *foo or foo[0].
11462 static bool refersToCompleteObject(const LValue &LVal) {
11463   if (LVal.Designator.Invalid)
11464     return false;
11465 
11466   if (!LVal.Designator.Entries.empty())
11467     return LVal.Designator.isMostDerivedAnUnsizedArray();
11468 
11469   if (!LVal.InvalidBase)
11470     return true;
11471 
11472   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11473   // the LValueBase.
11474   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11475   return !E || !isa<MemberExpr>(E);
11476 }
11477 
11478 /// Attempts to detect a user writing into a piece of memory that's impossible
11479 /// to figure out the size of by just using types.
11480 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11481   const SubobjectDesignator &Designator = LVal.Designator;
11482   // Notes:
11483   // - Users can only write off of the end when we have an invalid base. Invalid
11484   //   bases imply we don't know where the memory came from.
11485   // - We used to be a bit more aggressive here; we'd only be conservative if
11486   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11487   //   broke some common standard library extensions (PR30346), but was
11488   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11489   //   with some sort of list. OTOH, it seems that GCC is always
11490   //   conservative with the last element in structs (if it's an array), so our
11491   //   current behavior is more compatible than an explicit list approach would
11492   //   be.
11493   return LVal.InvalidBase &&
11494          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11495          Designator.MostDerivedIsArrayElement &&
11496          isDesignatorAtObjectEnd(Ctx, LVal);
11497 }
11498 
11499 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11500 /// Fails if the conversion would cause loss of precision.
11501 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11502                                             CharUnits &Result) {
11503   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11504   if (Int.ugt(CharUnitsMax))
11505     return false;
11506   Result = CharUnits::fromQuantity(Int.getZExtValue());
11507   return true;
11508 }
11509 
11510 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11511 /// determine how many bytes exist from the beginning of the object to either
11512 /// the end of the current subobject, or the end of the object itself, depending
11513 /// on what the LValue looks like + the value of Type.
11514 ///
11515 /// If this returns false, the value of Result is undefined.
11516 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11517                                unsigned Type, const LValue &LVal,
11518                                CharUnits &EndOffset) {
11519   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11520 
11521   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11522     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11523       return false;
11524     return HandleSizeof(Info, ExprLoc, Ty, Result);
11525   };
11526 
11527   // We want to evaluate the size of the entire object. This is a valid fallback
11528   // for when Type=1 and the designator is invalid, because we're asked for an
11529   // upper-bound.
11530   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11531     // Type=3 wants a lower bound, so we can't fall back to this.
11532     if (Type == 3 && !DetermineForCompleteObject)
11533       return false;
11534 
11535     llvm::APInt APEndOffset;
11536     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11537         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11538       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11539 
11540     if (LVal.InvalidBase)
11541       return false;
11542 
11543     QualType BaseTy = getObjectType(LVal.getLValueBase());
11544     return CheckedHandleSizeof(BaseTy, EndOffset);
11545   }
11546 
11547   // We want to evaluate the size of a subobject.
11548   const SubobjectDesignator &Designator = LVal.Designator;
11549 
11550   // The following is a moderately common idiom in C:
11551   //
11552   // struct Foo { int a; char c[1]; };
11553   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11554   // strcpy(&F->c[0], Bar);
11555   //
11556   // In order to not break too much legacy code, we need to support it.
11557   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11558     // If we can resolve this to an alloc_size call, we can hand that back,
11559     // because we know for certain how many bytes there are to write to.
11560     llvm::APInt APEndOffset;
11561     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11562         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11563       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11564 
11565     // If we cannot determine the size of the initial allocation, then we can't
11566     // given an accurate upper-bound. However, we are still able to give
11567     // conservative lower-bounds for Type=3.
11568     if (Type == 1)
11569       return false;
11570   }
11571 
11572   CharUnits BytesPerElem;
11573   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11574     return false;
11575 
11576   // According to the GCC documentation, we want the size of the subobject
11577   // denoted by the pointer. But that's not quite right -- what we actually
11578   // want is the size of the immediately-enclosing array, if there is one.
11579   int64_t ElemsRemaining;
11580   if (Designator.MostDerivedIsArrayElement &&
11581       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11582     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11583     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11584     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11585   } else {
11586     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11587   }
11588 
11589   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11590   return true;
11591 }
11592 
11593 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11594 /// returns true and stores the result in @p Size.
11595 ///
11596 /// If @p WasError is non-null, this will report whether the failure to evaluate
11597 /// is to be treated as an Error in IntExprEvaluator.
11598 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11599                                          EvalInfo &Info, uint64_t &Size) {
11600   // Determine the denoted object.
11601   LValue LVal;
11602   {
11603     // The operand of __builtin_object_size is never evaluated for side-effects.
11604     // If there are any, but we can determine the pointed-to object anyway, then
11605     // ignore the side-effects.
11606     SpeculativeEvaluationRAII SpeculativeEval(Info);
11607     IgnoreSideEffectsRAII Fold(Info);
11608 
11609     if (E->isGLValue()) {
11610       // It's possible for us to be given GLValues if we're called via
11611       // Expr::tryEvaluateObjectSize.
11612       APValue RVal;
11613       if (!EvaluateAsRValue(Info, E, RVal))
11614         return false;
11615       LVal.setFrom(Info.Ctx, RVal);
11616     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11617                                 /*InvalidBaseOK=*/true))
11618       return false;
11619   }
11620 
11621   // If we point to before the start of the object, there are no accessible
11622   // bytes.
11623   if (LVal.getLValueOffset().isNegative()) {
11624     Size = 0;
11625     return true;
11626   }
11627 
11628   CharUnits EndOffset;
11629   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11630     return false;
11631 
11632   // If we've fallen outside of the end offset, just pretend there's nothing to
11633   // write to/read from.
11634   if (EndOffset <= LVal.getLValueOffset())
11635     Size = 0;
11636   else
11637     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11638   return true;
11639 }
11640 
11641 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11642   if (unsigned BuiltinOp = E->getBuiltinCallee())
11643     return VisitBuiltinCallExpr(E, BuiltinOp);
11644 
11645   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11646 }
11647 
11648 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11649                                      APValue &Val, APSInt &Alignment) {
11650   QualType SrcTy = E->getArg(0)->getType();
11651   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11652     return false;
11653   // Even though we are evaluating integer expressions we could get a pointer
11654   // argument for the __builtin_is_aligned() case.
11655   if (SrcTy->isPointerType()) {
11656     LValue Ptr;
11657     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11658       return false;
11659     Ptr.moveInto(Val);
11660   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11661     Info.FFDiag(E->getArg(0));
11662     return false;
11663   } else {
11664     APSInt SrcInt;
11665     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11666       return false;
11667     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11668            "Bit widths must be the same");
11669     Val = APValue(SrcInt);
11670   }
11671   assert(Val.hasValue());
11672   return true;
11673 }
11674 
11675 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11676                                             unsigned BuiltinOp) {
11677   switch (BuiltinOp) {
11678   default:
11679     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11680 
11681   case Builtin::BI__builtin_dynamic_object_size:
11682   case Builtin::BI__builtin_object_size: {
11683     // The type was checked when we built the expression.
11684     unsigned Type =
11685         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11686     assert(Type <= 3 && "unexpected type");
11687 
11688     uint64_t Size;
11689     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11690       return Success(Size, E);
11691 
11692     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11693       return Success((Type & 2) ? 0 : -1, E);
11694 
11695     // Expression had no side effects, but we couldn't statically determine the
11696     // size of the referenced object.
11697     switch (Info.EvalMode) {
11698     case EvalInfo::EM_ConstantExpression:
11699     case EvalInfo::EM_ConstantFold:
11700     case EvalInfo::EM_IgnoreSideEffects:
11701       // Leave it to IR generation.
11702       return Error(E);
11703     case EvalInfo::EM_ConstantExpressionUnevaluated:
11704       // Reduce it to a constant now.
11705       return Success((Type & 2) ? 0 : -1, E);
11706     }
11707 
11708     llvm_unreachable("unexpected EvalMode");
11709   }
11710 
11711   case Builtin::BI__builtin_os_log_format_buffer_size: {
11712     analyze_os_log::OSLogBufferLayout Layout;
11713     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11714     return Success(Layout.size().getQuantity(), E);
11715   }
11716 
11717   case Builtin::BI__builtin_is_aligned: {
11718     APValue Src;
11719     APSInt Alignment;
11720     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11721       return false;
11722     if (Src.isLValue()) {
11723       // If we evaluated a pointer, check the minimum known alignment.
11724       LValue Ptr;
11725       Ptr.setFrom(Info.Ctx, Src);
11726       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11727       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11728       // We can return true if the known alignment at the computed offset is
11729       // greater than the requested alignment.
11730       assert(PtrAlign.isPowerOfTwo());
11731       assert(Alignment.isPowerOf2());
11732       if (PtrAlign.getQuantity() >= Alignment)
11733         return Success(1, E);
11734       // If the alignment is not known to be sufficient, some cases could still
11735       // be aligned at run time. However, if the requested alignment is less or
11736       // equal to the base alignment and the offset is not aligned, we know that
11737       // the run-time value can never be aligned.
11738       if (BaseAlignment.getQuantity() >= Alignment &&
11739           PtrAlign.getQuantity() < Alignment)
11740         return Success(0, E);
11741       // Otherwise we can't infer whether the value is sufficiently aligned.
11742       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11743       //  in cases where we can't fully evaluate the pointer.
11744       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11745           << Alignment;
11746       return false;
11747     }
11748     assert(Src.isInt());
11749     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11750   }
11751   case Builtin::BI__builtin_align_up: {
11752     APValue Src;
11753     APSInt Alignment;
11754     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11755       return false;
11756     if (!Src.isInt())
11757       return Error(E);
11758     APSInt AlignedVal =
11759         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11760                Src.getInt().isUnsigned());
11761     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11762     return Success(AlignedVal, E);
11763   }
11764   case Builtin::BI__builtin_align_down: {
11765     APValue Src;
11766     APSInt Alignment;
11767     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11768       return false;
11769     if (!Src.isInt())
11770       return Error(E);
11771     APSInt AlignedVal =
11772         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11773     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11774     return Success(AlignedVal, E);
11775   }
11776 
11777   case Builtin::BI__builtin_bitreverse8:
11778   case Builtin::BI__builtin_bitreverse16:
11779   case Builtin::BI__builtin_bitreverse32:
11780   case Builtin::BI__builtin_bitreverse64: {
11781     APSInt Val;
11782     if (!EvaluateInteger(E->getArg(0), Val, Info))
11783       return false;
11784 
11785     return Success(Val.reverseBits(), E);
11786   }
11787 
11788   case Builtin::BI__builtin_bswap16:
11789   case Builtin::BI__builtin_bswap32:
11790   case Builtin::BI__builtin_bswap64: {
11791     APSInt Val;
11792     if (!EvaluateInteger(E->getArg(0), Val, Info))
11793       return false;
11794 
11795     return Success(Val.byteSwap(), E);
11796   }
11797 
11798   case Builtin::BI__builtin_classify_type:
11799     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11800 
11801   case Builtin::BI__builtin_clrsb:
11802   case Builtin::BI__builtin_clrsbl:
11803   case Builtin::BI__builtin_clrsbll: {
11804     APSInt Val;
11805     if (!EvaluateInteger(E->getArg(0), Val, Info))
11806       return false;
11807 
11808     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11809   }
11810 
11811   case Builtin::BI__builtin_clz:
11812   case Builtin::BI__builtin_clzl:
11813   case Builtin::BI__builtin_clzll:
11814   case Builtin::BI__builtin_clzs: {
11815     APSInt Val;
11816     if (!EvaluateInteger(E->getArg(0), Val, Info))
11817       return false;
11818     if (!Val)
11819       return Error(E);
11820 
11821     return Success(Val.countLeadingZeros(), E);
11822   }
11823 
11824   case Builtin::BI__builtin_constant_p: {
11825     const Expr *Arg = E->getArg(0);
11826     if (EvaluateBuiltinConstantP(Info, Arg))
11827       return Success(true, E);
11828     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11829       // Outside a constant context, eagerly evaluate to false in the presence
11830       // of side-effects in order to avoid -Wunsequenced false-positives in
11831       // a branch on __builtin_constant_p(expr).
11832       return Success(false, E);
11833     }
11834     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11835     return false;
11836   }
11837 
11838   case Builtin::BI__builtin_is_constant_evaluated: {
11839     const auto *Callee = Info.CurrentCall->getCallee();
11840     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11841         (Info.CallStackDepth == 1 ||
11842          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11843           Callee->getIdentifier() &&
11844           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11845       // FIXME: Find a better way to avoid duplicated diagnostics.
11846       if (Info.EvalStatus.Diag)
11847         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11848                                                : Info.CurrentCall->CallLoc,
11849                     diag::warn_is_constant_evaluated_always_true_constexpr)
11850             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11851                                          : "std::is_constant_evaluated");
11852     }
11853 
11854     return Success(Info.InConstantContext, E);
11855   }
11856 
11857   case Builtin::BI__builtin_ctz:
11858   case Builtin::BI__builtin_ctzl:
11859   case Builtin::BI__builtin_ctzll:
11860   case Builtin::BI__builtin_ctzs: {
11861     APSInt Val;
11862     if (!EvaluateInteger(E->getArg(0), Val, Info))
11863       return false;
11864     if (!Val)
11865       return Error(E);
11866 
11867     return Success(Val.countTrailingZeros(), E);
11868   }
11869 
11870   case Builtin::BI__builtin_eh_return_data_regno: {
11871     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11872     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11873     return Success(Operand, E);
11874   }
11875 
11876   case Builtin::BI__builtin_expect:
11877   case Builtin::BI__builtin_expect_with_probability:
11878     return Visit(E->getArg(0));
11879 
11880   case Builtin::BI__builtin_ffs:
11881   case Builtin::BI__builtin_ffsl:
11882   case Builtin::BI__builtin_ffsll: {
11883     APSInt Val;
11884     if (!EvaluateInteger(E->getArg(0), Val, Info))
11885       return false;
11886 
11887     unsigned N = Val.countTrailingZeros();
11888     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11889   }
11890 
11891   case Builtin::BI__builtin_fpclassify: {
11892     APFloat Val(0.0);
11893     if (!EvaluateFloat(E->getArg(5), Val, Info))
11894       return false;
11895     unsigned Arg;
11896     switch (Val.getCategory()) {
11897     case APFloat::fcNaN: Arg = 0; break;
11898     case APFloat::fcInfinity: Arg = 1; break;
11899     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11900     case APFloat::fcZero: Arg = 4; break;
11901     }
11902     return Visit(E->getArg(Arg));
11903   }
11904 
11905   case Builtin::BI__builtin_isinf_sign: {
11906     APFloat Val(0.0);
11907     return EvaluateFloat(E->getArg(0), Val, Info) &&
11908            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11909   }
11910 
11911   case Builtin::BI__builtin_isinf: {
11912     APFloat Val(0.0);
11913     return EvaluateFloat(E->getArg(0), Val, Info) &&
11914            Success(Val.isInfinity() ? 1 : 0, E);
11915   }
11916 
11917   case Builtin::BI__builtin_isfinite: {
11918     APFloat Val(0.0);
11919     return EvaluateFloat(E->getArg(0), Val, Info) &&
11920            Success(Val.isFinite() ? 1 : 0, E);
11921   }
11922 
11923   case Builtin::BI__builtin_isnan: {
11924     APFloat Val(0.0);
11925     return EvaluateFloat(E->getArg(0), Val, Info) &&
11926            Success(Val.isNaN() ? 1 : 0, E);
11927   }
11928 
11929   case Builtin::BI__builtin_isnormal: {
11930     APFloat Val(0.0);
11931     return EvaluateFloat(E->getArg(0), Val, Info) &&
11932            Success(Val.isNormal() ? 1 : 0, E);
11933   }
11934 
11935   case Builtin::BI__builtin_parity:
11936   case Builtin::BI__builtin_parityl:
11937   case Builtin::BI__builtin_parityll: {
11938     APSInt Val;
11939     if (!EvaluateInteger(E->getArg(0), Val, Info))
11940       return false;
11941 
11942     return Success(Val.countPopulation() % 2, E);
11943   }
11944 
11945   case Builtin::BI__builtin_popcount:
11946   case Builtin::BI__builtin_popcountl:
11947   case Builtin::BI__builtin_popcountll: {
11948     APSInt Val;
11949     if (!EvaluateInteger(E->getArg(0), Val, Info))
11950       return false;
11951 
11952     return Success(Val.countPopulation(), E);
11953   }
11954 
11955   case Builtin::BI__builtin_rotateleft8:
11956   case Builtin::BI__builtin_rotateleft16:
11957   case Builtin::BI__builtin_rotateleft32:
11958   case Builtin::BI__builtin_rotateleft64:
11959   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11960   case Builtin::BI_rotl16:
11961   case Builtin::BI_rotl:
11962   case Builtin::BI_lrotl:
11963   case Builtin::BI_rotl64: {
11964     APSInt Val, Amt;
11965     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11966         !EvaluateInteger(E->getArg(1), Amt, Info))
11967       return false;
11968 
11969     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11970   }
11971 
11972   case Builtin::BI__builtin_rotateright8:
11973   case Builtin::BI__builtin_rotateright16:
11974   case Builtin::BI__builtin_rotateright32:
11975   case Builtin::BI__builtin_rotateright64:
11976   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11977   case Builtin::BI_rotr16:
11978   case Builtin::BI_rotr:
11979   case Builtin::BI_lrotr:
11980   case Builtin::BI_rotr64: {
11981     APSInt Val, Amt;
11982     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11983         !EvaluateInteger(E->getArg(1), Amt, Info))
11984       return false;
11985 
11986     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11987   }
11988 
11989   case Builtin::BIstrlen:
11990   case Builtin::BIwcslen:
11991     // A call to strlen is not a constant expression.
11992     if (Info.getLangOpts().CPlusPlus11)
11993       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11994         << /*isConstexpr*/0 << /*isConstructor*/0
11995         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11996     else
11997       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11998     LLVM_FALLTHROUGH;
11999   case Builtin::BI__builtin_strlen:
12000   case Builtin::BI__builtin_wcslen: {
12001     // As an extension, we support __builtin_strlen() as a constant expression,
12002     // and support folding strlen() to a constant.
12003     uint64_t StrLen;
12004     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12005       return Success(StrLen, E);
12006     return false;
12007   }
12008 
12009   case Builtin::BIstrcmp:
12010   case Builtin::BIwcscmp:
12011   case Builtin::BIstrncmp:
12012   case Builtin::BIwcsncmp:
12013   case Builtin::BImemcmp:
12014   case Builtin::BIbcmp:
12015   case Builtin::BIwmemcmp:
12016     // A call to strlen is not a constant expression.
12017     if (Info.getLangOpts().CPlusPlus11)
12018       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12019         << /*isConstexpr*/0 << /*isConstructor*/0
12020         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12021     else
12022       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12023     LLVM_FALLTHROUGH;
12024   case Builtin::BI__builtin_strcmp:
12025   case Builtin::BI__builtin_wcscmp:
12026   case Builtin::BI__builtin_strncmp:
12027   case Builtin::BI__builtin_wcsncmp:
12028   case Builtin::BI__builtin_memcmp:
12029   case Builtin::BI__builtin_bcmp:
12030   case Builtin::BI__builtin_wmemcmp: {
12031     LValue String1, String2;
12032     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12033         !EvaluatePointer(E->getArg(1), String2, Info))
12034       return false;
12035 
12036     uint64_t MaxLength = uint64_t(-1);
12037     if (BuiltinOp != Builtin::BIstrcmp &&
12038         BuiltinOp != Builtin::BIwcscmp &&
12039         BuiltinOp != Builtin::BI__builtin_strcmp &&
12040         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12041       APSInt N;
12042       if (!EvaluateInteger(E->getArg(2), N, Info))
12043         return false;
12044       MaxLength = N.getExtValue();
12045     }
12046 
12047     // Empty substrings compare equal by definition.
12048     if (MaxLength == 0u)
12049       return Success(0, E);
12050 
12051     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12052         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12053         String1.Designator.Invalid || String2.Designator.Invalid)
12054       return false;
12055 
12056     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12057     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12058 
12059     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12060                      BuiltinOp == Builtin::BIbcmp ||
12061                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12062                      BuiltinOp == Builtin::BI__builtin_bcmp;
12063 
12064     assert(IsRawByte ||
12065            (Info.Ctx.hasSameUnqualifiedType(
12066                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12067             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12068 
12069     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12070     // 'char8_t', but no other types.
12071     if (IsRawByte &&
12072         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12073       // FIXME: Consider using our bit_cast implementation to support this.
12074       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12075           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12076           << CharTy1 << CharTy2;
12077       return false;
12078     }
12079 
12080     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12081       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12082              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12083              Char1.isInt() && Char2.isInt();
12084     };
12085     const auto &AdvanceElems = [&] {
12086       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12087              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12088     };
12089 
12090     bool StopAtNull =
12091         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12092          BuiltinOp != Builtin::BIwmemcmp &&
12093          BuiltinOp != Builtin::BI__builtin_memcmp &&
12094          BuiltinOp != Builtin::BI__builtin_bcmp &&
12095          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12096     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12097                   BuiltinOp == Builtin::BIwcsncmp ||
12098                   BuiltinOp == Builtin::BIwmemcmp ||
12099                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12100                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12101                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12102 
12103     for (; MaxLength; --MaxLength) {
12104       APValue Char1, Char2;
12105       if (!ReadCurElems(Char1, Char2))
12106         return false;
12107       if (Char1.getInt().ne(Char2.getInt())) {
12108         if (IsWide) // wmemcmp compares with wchar_t signedness.
12109           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12110         // memcmp always compares unsigned chars.
12111         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12112       }
12113       if (StopAtNull && !Char1.getInt())
12114         return Success(0, E);
12115       assert(!(StopAtNull && !Char2.getInt()));
12116       if (!AdvanceElems())
12117         return false;
12118     }
12119     // We hit the strncmp / memcmp limit.
12120     return Success(0, E);
12121   }
12122 
12123   case Builtin::BI__atomic_always_lock_free:
12124   case Builtin::BI__atomic_is_lock_free:
12125   case Builtin::BI__c11_atomic_is_lock_free: {
12126     APSInt SizeVal;
12127     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12128       return false;
12129 
12130     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12131     // of two less than or equal to the maximum inline atomic width, we know it
12132     // is lock-free.  If the size isn't a power of two, or greater than the
12133     // maximum alignment where we promote atomics, we know it is not lock-free
12134     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12135     // the answer can only be determined at runtime; for example, 16-byte
12136     // atomics have lock-free implementations on some, but not all,
12137     // x86-64 processors.
12138 
12139     // Check power-of-two.
12140     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12141     if (Size.isPowerOfTwo()) {
12142       // Check against inlining width.
12143       unsigned InlineWidthBits =
12144           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12145       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12146         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12147             Size == CharUnits::One() ||
12148             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12149                                                 Expr::NPC_NeverValueDependent))
12150           // OK, we will inline appropriately-aligned operations of this size,
12151           // and _Atomic(T) is appropriately-aligned.
12152           return Success(1, E);
12153 
12154         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12155           castAs<PointerType>()->getPointeeType();
12156         if (!PointeeType->isIncompleteType() &&
12157             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12158           // OK, we will inline operations on this object.
12159           return Success(1, E);
12160         }
12161       }
12162     }
12163 
12164     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12165         Success(0, E) : Error(E);
12166   }
12167   case Builtin::BI__builtin_add_overflow:
12168   case Builtin::BI__builtin_sub_overflow:
12169   case Builtin::BI__builtin_mul_overflow:
12170   case Builtin::BI__builtin_sadd_overflow:
12171   case Builtin::BI__builtin_uadd_overflow:
12172   case Builtin::BI__builtin_uaddl_overflow:
12173   case Builtin::BI__builtin_uaddll_overflow:
12174   case Builtin::BI__builtin_usub_overflow:
12175   case Builtin::BI__builtin_usubl_overflow:
12176   case Builtin::BI__builtin_usubll_overflow:
12177   case Builtin::BI__builtin_umul_overflow:
12178   case Builtin::BI__builtin_umull_overflow:
12179   case Builtin::BI__builtin_umulll_overflow:
12180   case Builtin::BI__builtin_saddl_overflow:
12181   case Builtin::BI__builtin_saddll_overflow:
12182   case Builtin::BI__builtin_ssub_overflow:
12183   case Builtin::BI__builtin_ssubl_overflow:
12184   case Builtin::BI__builtin_ssubll_overflow:
12185   case Builtin::BI__builtin_smul_overflow:
12186   case Builtin::BI__builtin_smull_overflow:
12187   case Builtin::BI__builtin_smulll_overflow: {
12188     LValue ResultLValue;
12189     APSInt LHS, RHS;
12190 
12191     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12192     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12193         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12194         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12195       return false;
12196 
12197     APSInt Result;
12198     bool DidOverflow = false;
12199 
12200     // If the types don't have to match, enlarge all 3 to the largest of them.
12201     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12202         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12203         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12204       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12205                       ResultType->isSignedIntegerOrEnumerationType();
12206       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12207                       ResultType->isSignedIntegerOrEnumerationType();
12208       uint64_t LHSSize = LHS.getBitWidth();
12209       uint64_t RHSSize = RHS.getBitWidth();
12210       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12211       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12212 
12213       // Add an additional bit if the signedness isn't uniformly agreed to. We
12214       // could do this ONLY if there is a signed and an unsigned that both have
12215       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12216       // caught in the shrink-to-result later anyway.
12217       if (IsSigned && !AllSigned)
12218         ++MaxBits;
12219 
12220       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12221       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12222       Result = APSInt(MaxBits, !IsSigned);
12223     }
12224 
12225     // Find largest int.
12226     switch (BuiltinOp) {
12227     default:
12228       llvm_unreachable("Invalid value for BuiltinOp");
12229     case Builtin::BI__builtin_add_overflow:
12230     case Builtin::BI__builtin_sadd_overflow:
12231     case Builtin::BI__builtin_saddl_overflow:
12232     case Builtin::BI__builtin_saddll_overflow:
12233     case Builtin::BI__builtin_uadd_overflow:
12234     case Builtin::BI__builtin_uaddl_overflow:
12235     case Builtin::BI__builtin_uaddll_overflow:
12236       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12237                               : LHS.uadd_ov(RHS, DidOverflow);
12238       break;
12239     case Builtin::BI__builtin_sub_overflow:
12240     case Builtin::BI__builtin_ssub_overflow:
12241     case Builtin::BI__builtin_ssubl_overflow:
12242     case Builtin::BI__builtin_ssubll_overflow:
12243     case Builtin::BI__builtin_usub_overflow:
12244     case Builtin::BI__builtin_usubl_overflow:
12245     case Builtin::BI__builtin_usubll_overflow:
12246       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12247                               : LHS.usub_ov(RHS, DidOverflow);
12248       break;
12249     case Builtin::BI__builtin_mul_overflow:
12250     case Builtin::BI__builtin_smul_overflow:
12251     case Builtin::BI__builtin_smull_overflow:
12252     case Builtin::BI__builtin_smulll_overflow:
12253     case Builtin::BI__builtin_umul_overflow:
12254     case Builtin::BI__builtin_umull_overflow:
12255     case Builtin::BI__builtin_umulll_overflow:
12256       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12257                               : LHS.umul_ov(RHS, DidOverflow);
12258       break;
12259     }
12260 
12261     // In the case where multiple sizes are allowed, truncate and see if
12262     // the values are the same.
12263     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12264         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12265         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12266       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12267       // since it will give us the behavior of a TruncOrSelf in the case where
12268       // its parameter <= its size.  We previously set Result to be at least the
12269       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12270       // will work exactly like TruncOrSelf.
12271       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12272       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12273 
12274       if (!APSInt::isSameValue(Temp, Result))
12275         DidOverflow = true;
12276       Result = Temp;
12277     }
12278 
12279     APValue APV{Result};
12280     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12281       return false;
12282     return Success(DidOverflow, E);
12283   }
12284   }
12285 }
12286 
12287 /// Determine whether this is a pointer past the end of the complete
12288 /// object referred to by the lvalue.
12289 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12290                                             const LValue &LV) {
12291   // A null pointer can be viewed as being "past the end" but we don't
12292   // choose to look at it that way here.
12293   if (!LV.getLValueBase())
12294     return false;
12295 
12296   // If the designator is valid and refers to a subobject, we're not pointing
12297   // past the end.
12298   if (!LV.getLValueDesignator().Invalid &&
12299       !LV.getLValueDesignator().isOnePastTheEnd())
12300     return false;
12301 
12302   // A pointer to an incomplete type might be past-the-end if the type's size is
12303   // zero.  We cannot tell because the type is incomplete.
12304   QualType Ty = getType(LV.getLValueBase());
12305   if (Ty->isIncompleteType())
12306     return true;
12307 
12308   // We're a past-the-end pointer if we point to the byte after the object,
12309   // no matter what our type or path is.
12310   auto Size = Ctx.getTypeSizeInChars(Ty);
12311   return LV.getLValueOffset() == Size;
12312 }
12313 
12314 namespace {
12315 
12316 /// Data recursive integer evaluator of certain binary operators.
12317 ///
12318 /// We use a data recursive algorithm for binary operators so that we are able
12319 /// to handle extreme cases of chained binary operators without causing stack
12320 /// overflow.
12321 class DataRecursiveIntBinOpEvaluator {
12322   struct EvalResult {
12323     APValue Val;
12324     bool Failed;
12325 
12326     EvalResult() : Failed(false) { }
12327 
12328     void swap(EvalResult &RHS) {
12329       Val.swap(RHS.Val);
12330       Failed = RHS.Failed;
12331       RHS.Failed = false;
12332     }
12333   };
12334 
12335   struct Job {
12336     const Expr *E;
12337     EvalResult LHSResult; // meaningful only for binary operator expression.
12338     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12339 
12340     Job() = default;
12341     Job(Job &&) = default;
12342 
12343     void startSpeculativeEval(EvalInfo &Info) {
12344       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12345     }
12346 
12347   private:
12348     SpeculativeEvaluationRAII SpecEvalRAII;
12349   };
12350 
12351   SmallVector<Job, 16> Queue;
12352 
12353   IntExprEvaluator &IntEval;
12354   EvalInfo &Info;
12355   APValue &FinalResult;
12356 
12357 public:
12358   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12359     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12360 
12361   /// True if \param E is a binary operator that we are going to handle
12362   /// data recursively.
12363   /// We handle binary operators that are comma, logical, or that have operands
12364   /// with integral or enumeration type.
12365   static bool shouldEnqueue(const BinaryOperator *E) {
12366     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12367            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12368             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12369             E->getRHS()->getType()->isIntegralOrEnumerationType());
12370   }
12371 
12372   bool Traverse(const BinaryOperator *E) {
12373     enqueue(E);
12374     EvalResult PrevResult;
12375     while (!Queue.empty())
12376       process(PrevResult);
12377 
12378     if (PrevResult.Failed) return false;
12379 
12380     FinalResult.swap(PrevResult.Val);
12381     return true;
12382   }
12383 
12384 private:
12385   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12386     return IntEval.Success(Value, E, Result);
12387   }
12388   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12389     return IntEval.Success(Value, E, Result);
12390   }
12391   bool Error(const Expr *E) {
12392     return IntEval.Error(E);
12393   }
12394   bool Error(const Expr *E, diag::kind D) {
12395     return IntEval.Error(E, D);
12396   }
12397 
12398   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12399     return Info.CCEDiag(E, D);
12400   }
12401 
12402   // Returns true if visiting the RHS is necessary, false otherwise.
12403   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12404                          bool &SuppressRHSDiags);
12405 
12406   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12407                   const BinaryOperator *E, APValue &Result);
12408 
12409   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12410     Result.Failed = !Evaluate(Result.Val, Info, E);
12411     if (Result.Failed)
12412       Result.Val = APValue();
12413   }
12414 
12415   void process(EvalResult &Result);
12416 
12417   void enqueue(const Expr *E) {
12418     E = E->IgnoreParens();
12419     Queue.resize(Queue.size()+1);
12420     Queue.back().E = E;
12421     Queue.back().Kind = Job::AnyExprKind;
12422   }
12423 };
12424 
12425 }
12426 
12427 bool DataRecursiveIntBinOpEvaluator::
12428        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12429                          bool &SuppressRHSDiags) {
12430   if (E->getOpcode() == BO_Comma) {
12431     // Ignore LHS but note if we could not evaluate it.
12432     if (LHSResult.Failed)
12433       return Info.noteSideEffect();
12434     return true;
12435   }
12436 
12437   if (E->isLogicalOp()) {
12438     bool LHSAsBool;
12439     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12440       // We were able to evaluate the LHS, see if we can get away with not
12441       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12442       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12443         Success(LHSAsBool, E, LHSResult.Val);
12444         return false; // Ignore RHS
12445       }
12446     } else {
12447       LHSResult.Failed = true;
12448 
12449       // Since we weren't able to evaluate the left hand side, it
12450       // might have had side effects.
12451       if (!Info.noteSideEffect())
12452         return false;
12453 
12454       // We can't evaluate the LHS; however, sometimes the result
12455       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12456       // Don't ignore RHS and suppress diagnostics from this arm.
12457       SuppressRHSDiags = true;
12458     }
12459 
12460     return true;
12461   }
12462 
12463   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12464          E->getRHS()->getType()->isIntegralOrEnumerationType());
12465 
12466   if (LHSResult.Failed && !Info.noteFailure())
12467     return false; // Ignore RHS;
12468 
12469   return true;
12470 }
12471 
12472 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12473                                     bool IsSub) {
12474   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12475   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12476   // offsets.
12477   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12478   CharUnits &Offset = LVal.getLValueOffset();
12479   uint64_t Offset64 = Offset.getQuantity();
12480   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12481   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12482                                          : Offset64 + Index64);
12483 }
12484 
12485 bool DataRecursiveIntBinOpEvaluator::
12486        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12487                   const BinaryOperator *E, APValue &Result) {
12488   if (E->getOpcode() == BO_Comma) {
12489     if (RHSResult.Failed)
12490       return false;
12491     Result = RHSResult.Val;
12492     return true;
12493   }
12494 
12495   if (E->isLogicalOp()) {
12496     bool lhsResult, rhsResult;
12497     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12498     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12499 
12500     if (LHSIsOK) {
12501       if (RHSIsOK) {
12502         if (E->getOpcode() == BO_LOr)
12503           return Success(lhsResult || rhsResult, E, Result);
12504         else
12505           return Success(lhsResult && rhsResult, E, Result);
12506       }
12507     } else {
12508       if (RHSIsOK) {
12509         // We can't evaluate the LHS; however, sometimes the result
12510         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12511         if (rhsResult == (E->getOpcode() == BO_LOr))
12512           return Success(rhsResult, E, Result);
12513       }
12514     }
12515 
12516     return false;
12517   }
12518 
12519   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12520          E->getRHS()->getType()->isIntegralOrEnumerationType());
12521 
12522   if (LHSResult.Failed || RHSResult.Failed)
12523     return false;
12524 
12525   const APValue &LHSVal = LHSResult.Val;
12526   const APValue &RHSVal = RHSResult.Val;
12527 
12528   // Handle cases like (unsigned long)&a + 4.
12529   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12530     Result = LHSVal;
12531     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12532     return true;
12533   }
12534 
12535   // Handle cases like 4 + (unsigned long)&a
12536   if (E->getOpcode() == BO_Add &&
12537       RHSVal.isLValue() && LHSVal.isInt()) {
12538     Result = RHSVal;
12539     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12540     return true;
12541   }
12542 
12543   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12544     // Handle (intptr_t)&&A - (intptr_t)&&B.
12545     if (!LHSVal.getLValueOffset().isZero() ||
12546         !RHSVal.getLValueOffset().isZero())
12547       return false;
12548     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12549     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12550     if (!LHSExpr || !RHSExpr)
12551       return false;
12552     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12553     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12554     if (!LHSAddrExpr || !RHSAddrExpr)
12555       return false;
12556     // Make sure both labels come from the same function.
12557     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12558         RHSAddrExpr->getLabel()->getDeclContext())
12559       return false;
12560     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12561     return true;
12562   }
12563 
12564   // All the remaining cases expect both operands to be an integer
12565   if (!LHSVal.isInt() || !RHSVal.isInt())
12566     return Error(E);
12567 
12568   // Set up the width and signedness manually, in case it can't be deduced
12569   // from the operation we're performing.
12570   // FIXME: Don't do this in the cases where we can deduce it.
12571   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12572                E->getType()->isUnsignedIntegerOrEnumerationType());
12573   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12574                          RHSVal.getInt(), Value))
12575     return false;
12576   return Success(Value, E, Result);
12577 }
12578 
12579 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12580   Job &job = Queue.back();
12581 
12582   switch (job.Kind) {
12583     case Job::AnyExprKind: {
12584       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12585         if (shouldEnqueue(Bop)) {
12586           job.Kind = Job::BinOpKind;
12587           enqueue(Bop->getLHS());
12588           return;
12589         }
12590       }
12591 
12592       EvaluateExpr(job.E, Result);
12593       Queue.pop_back();
12594       return;
12595     }
12596 
12597     case Job::BinOpKind: {
12598       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12599       bool SuppressRHSDiags = false;
12600       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12601         Queue.pop_back();
12602         return;
12603       }
12604       if (SuppressRHSDiags)
12605         job.startSpeculativeEval(Info);
12606       job.LHSResult.swap(Result);
12607       job.Kind = Job::BinOpVisitedLHSKind;
12608       enqueue(Bop->getRHS());
12609       return;
12610     }
12611 
12612     case Job::BinOpVisitedLHSKind: {
12613       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12614       EvalResult RHS;
12615       RHS.swap(Result);
12616       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12617       Queue.pop_back();
12618       return;
12619     }
12620   }
12621 
12622   llvm_unreachable("Invalid Job::Kind!");
12623 }
12624 
12625 namespace {
12626 enum class CmpResult {
12627   Unequal,
12628   Less,
12629   Equal,
12630   Greater,
12631   Unordered,
12632 };
12633 }
12634 
12635 template <class SuccessCB, class AfterCB>
12636 static bool
12637 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12638                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12639   assert(!E->isValueDependent());
12640   assert(E->isComparisonOp() && "expected comparison operator");
12641   assert((E->getOpcode() == BO_Cmp ||
12642           E->getType()->isIntegralOrEnumerationType()) &&
12643          "unsupported binary expression evaluation");
12644   auto Error = [&](const Expr *E) {
12645     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12646     return false;
12647   };
12648 
12649   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12650   bool IsEquality = E->isEqualityOp();
12651 
12652   QualType LHSTy = E->getLHS()->getType();
12653   QualType RHSTy = E->getRHS()->getType();
12654 
12655   if (LHSTy->isIntegralOrEnumerationType() &&
12656       RHSTy->isIntegralOrEnumerationType()) {
12657     APSInt LHS, RHS;
12658     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12659     if (!LHSOK && !Info.noteFailure())
12660       return false;
12661     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12662       return false;
12663     if (LHS < RHS)
12664       return Success(CmpResult::Less, E);
12665     if (LHS > RHS)
12666       return Success(CmpResult::Greater, E);
12667     return Success(CmpResult::Equal, E);
12668   }
12669 
12670   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12671     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12672     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12673 
12674     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12675     if (!LHSOK && !Info.noteFailure())
12676       return false;
12677     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12678       return false;
12679     if (LHSFX < RHSFX)
12680       return Success(CmpResult::Less, E);
12681     if (LHSFX > RHSFX)
12682       return Success(CmpResult::Greater, E);
12683     return Success(CmpResult::Equal, E);
12684   }
12685 
12686   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12687     ComplexValue LHS, RHS;
12688     bool LHSOK;
12689     if (E->isAssignmentOp()) {
12690       LValue LV;
12691       EvaluateLValue(E->getLHS(), LV, Info);
12692       LHSOK = false;
12693     } else if (LHSTy->isRealFloatingType()) {
12694       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12695       if (LHSOK) {
12696         LHS.makeComplexFloat();
12697         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12698       }
12699     } else {
12700       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12701     }
12702     if (!LHSOK && !Info.noteFailure())
12703       return false;
12704 
12705     if (E->getRHS()->getType()->isRealFloatingType()) {
12706       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12707         return false;
12708       RHS.makeComplexFloat();
12709       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12710     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12711       return false;
12712 
12713     if (LHS.isComplexFloat()) {
12714       APFloat::cmpResult CR_r =
12715         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12716       APFloat::cmpResult CR_i =
12717         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12718       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12719       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12720     } else {
12721       assert(IsEquality && "invalid complex comparison");
12722       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12723                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12724       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12725     }
12726   }
12727 
12728   if (LHSTy->isRealFloatingType() &&
12729       RHSTy->isRealFloatingType()) {
12730     APFloat RHS(0.0), LHS(0.0);
12731 
12732     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12733     if (!LHSOK && !Info.noteFailure())
12734       return false;
12735 
12736     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12737       return false;
12738 
12739     assert(E->isComparisonOp() && "Invalid binary operator!");
12740     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12741     if (!Info.InConstantContext &&
12742         APFloatCmpResult == APFloat::cmpUnordered &&
12743         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12744       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12745       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12746       return false;
12747     }
12748     auto GetCmpRes = [&]() {
12749       switch (APFloatCmpResult) {
12750       case APFloat::cmpEqual:
12751         return CmpResult::Equal;
12752       case APFloat::cmpLessThan:
12753         return CmpResult::Less;
12754       case APFloat::cmpGreaterThan:
12755         return CmpResult::Greater;
12756       case APFloat::cmpUnordered:
12757         return CmpResult::Unordered;
12758       }
12759       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12760     };
12761     return Success(GetCmpRes(), E);
12762   }
12763 
12764   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12765     LValue LHSValue, RHSValue;
12766 
12767     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12768     if (!LHSOK && !Info.noteFailure())
12769       return false;
12770 
12771     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12772       return false;
12773 
12774     // Reject differing bases from the normal codepath; we special-case
12775     // comparisons to null.
12776     if (!HasSameBase(LHSValue, RHSValue)) {
12777       // Inequalities and subtractions between unrelated pointers have
12778       // unspecified or undefined behavior.
12779       if (!IsEquality) {
12780         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12781         return false;
12782       }
12783       // A constant address may compare equal to the address of a symbol.
12784       // The one exception is that address of an object cannot compare equal
12785       // to a null pointer constant.
12786       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12787           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12788         return Error(E);
12789       // It's implementation-defined whether distinct literals will have
12790       // distinct addresses. In clang, the result of such a comparison is
12791       // unspecified, so it is not a constant expression. However, we do know
12792       // that the address of a literal will be non-null.
12793       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12794           LHSValue.Base && RHSValue.Base)
12795         return Error(E);
12796       // We can't tell whether weak symbols will end up pointing to the same
12797       // object.
12798       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12799         return Error(E);
12800       // We can't compare the address of the start of one object with the
12801       // past-the-end address of another object, per C++ DR1652.
12802       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12803            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12804           (RHSValue.Base && RHSValue.Offset.isZero() &&
12805            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12806         return Error(E);
12807       // We can't tell whether an object is at the same address as another
12808       // zero sized object.
12809       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12810           (LHSValue.Base && isZeroSized(RHSValue)))
12811         return Error(E);
12812       return Success(CmpResult::Unequal, E);
12813     }
12814 
12815     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12816     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12817 
12818     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12819     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12820 
12821     // C++11 [expr.rel]p3:
12822     //   Pointers to void (after pointer conversions) can be compared, with a
12823     //   result defined as follows: If both pointers represent the same
12824     //   address or are both the null pointer value, the result is true if the
12825     //   operator is <= or >= and false otherwise; otherwise the result is
12826     //   unspecified.
12827     // We interpret this as applying to pointers to *cv* void.
12828     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12829       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12830 
12831     // C++11 [expr.rel]p2:
12832     // - If two pointers point to non-static data members of the same object,
12833     //   or to subobjects or array elements fo such members, recursively, the
12834     //   pointer to the later declared member compares greater provided the
12835     //   two members have the same access control and provided their class is
12836     //   not a union.
12837     //   [...]
12838     // - Otherwise pointer comparisons are unspecified.
12839     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12840       bool WasArrayIndex;
12841       unsigned Mismatch = FindDesignatorMismatch(
12842           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12843       // At the point where the designators diverge, the comparison has a
12844       // specified value if:
12845       //  - we are comparing array indices
12846       //  - we are comparing fields of a union, or fields with the same access
12847       // Otherwise, the result is unspecified and thus the comparison is not a
12848       // constant expression.
12849       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12850           Mismatch < RHSDesignator.Entries.size()) {
12851         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12852         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12853         if (!LF && !RF)
12854           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12855         else if (!LF)
12856           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12857               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12858               << RF->getParent() << RF;
12859         else if (!RF)
12860           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12861               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12862               << LF->getParent() << LF;
12863         else if (!LF->getParent()->isUnion() &&
12864                  LF->getAccess() != RF->getAccess())
12865           Info.CCEDiag(E,
12866                        diag::note_constexpr_pointer_comparison_differing_access)
12867               << LF << LF->getAccess() << RF << RF->getAccess()
12868               << LF->getParent();
12869       }
12870     }
12871 
12872     // The comparison here must be unsigned, and performed with the same
12873     // width as the pointer.
12874     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12875     uint64_t CompareLHS = LHSOffset.getQuantity();
12876     uint64_t CompareRHS = RHSOffset.getQuantity();
12877     assert(PtrSize <= 64 && "Unexpected pointer width");
12878     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12879     CompareLHS &= Mask;
12880     CompareRHS &= Mask;
12881 
12882     // If there is a base and this is a relational operator, we can only
12883     // compare pointers within the object in question; otherwise, the result
12884     // depends on where the object is located in memory.
12885     if (!LHSValue.Base.isNull() && IsRelational) {
12886       QualType BaseTy = getType(LHSValue.Base);
12887       if (BaseTy->isIncompleteType())
12888         return Error(E);
12889       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12890       uint64_t OffsetLimit = Size.getQuantity();
12891       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12892         return Error(E);
12893     }
12894 
12895     if (CompareLHS < CompareRHS)
12896       return Success(CmpResult::Less, E);
12897     if (CompareLHS > CompareRHS)
12898       return Success(CmpResult::Greater, E);
12899     return Success(CmpResult::Equal, E);
12900   }
12901 
12902   if (LHSTy->isMemberPointerType()) {
12903     assert(IsEquality && "unexpected member pointer operation");
12904     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12905 
12906     MemberPtr LHSValue, RHSValue;
12907 
12908     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12909     if (!LHSOK && !Info.noteFailure())
12910       return false;
12911 
12912     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12913       return false;
12914 
12915     // C++11 [expr.eq]p2:
12916     //   If both operands are null, they compare equal. Otherwise if only one is
12917     //   null, they compare unequal.
12918     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12919       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12920       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12921     }
12922 
12923     //   Otherwise if either is a pointer to a virtual member function, the
12924     //   result is unspecified.
12925     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12926       if (MD->isVirtual())
12927         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12928     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12929       if (MD->isVirtual())
12930         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12931 
12932     //   Otherwise they compare equal if and only if they would refer to the
12933     //   same member of the same most derived object or the same subobject if
12934     //   they were dereferenced with a hypothetical object of the associated
12935     //   class type.
12936     bool Equal = LHSValue == RHSValue;
12937     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12938   }
12939 
12940   if (LHSTy->isNullPtrType()) {
12941     assert(E->isComparisonOp() && "unexpected nullptr operation");
12942     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12943     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12944     // are compared, the result is true of the operator is <=, >= or ==, and
12945     // false otherwise.
12946     return Success(CmpResult::Equal, E);
12947   }
12948 
12949   return DoAfter();
12950 }
12951 
12952 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12953   if (!CheckLiteralType(Info, E))
12954     return false;
12955 
12956   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12957     ComparisonCategoryResult CCR;
12958     switch (CR) {
12959     case CmpResult::Unequal:
12960       llvm_unreachable("should never produce Unequal for three-way comparison");
12961     case CmpResult::Less:
12962       CCR = ComparisonCategoryResult::Less;
12963       break;
12964     case CmpResult::Equal:
12965       CCR = ComparisonCategoryResult::Equal;
12966       break;
12967     case CmpResult::Greater:
12968       CCR = ComparisonCategoryResult::Greater;
12969       break;
12970     case CmpResult::Unordered:
12971       CCR = ComparisonCategoryResult::Unordered;
12972       break;
12973     }
12974     // Evaluation succeeded. Lookup the information for the comparison category
12975     // type and fetch the VarDecl for the result.
12976     const ComparisonCategoryInfo &CmpInfo =
12977         Info.Ctx.CompCategories.getInfoForType(E->getType());
12978     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12979     // Check and evaluate the result as a constant expression.
12980     LValue LV;
12981     LV.set(VD);
12982     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12983       return false;
12984     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12985                                    ConstantExprKind::Normal);
12986   };
12987   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12988     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12989   });
12990 }
12991 
12992 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12993   // We don't support assignment in C. C++ assignments don't get here because
12994   // assignment is an lvalue in C++.
12995   if (E->isAssignmentOp()) {
12996     Error(E);
12997     if (!Info.noteFailure())
12998       return false;
12999   }
13000 
13001   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13002     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13003 
13004   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13005           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13006          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13007 
13008   if (E->isComparisonOp()) {
13009     // Evaluate builtin binary comparisons by evaluating them as three-way
13010     // comparisons and then translating the result.
13011     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13012       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13013              "should only produce Unequal for equality comparisons");
13014       bool IsEqual   = CR == CmpResult::Equal,
13015            IsLess    = CR == CmpResult::Less,
13016            IsGreater = CR == CmpResult::Greater;
13017       auto Op = E->getOpcode();
13018       switch (Op) {
13019       default:
13020         llvm_unreachable("unsupported binary operator");
13021       case BO_EQ:
13022       case BO_NE:
13023         return Success(IsEqual == (Op == BO_EQ), E);
13024       case BO_LT:
13025         return Success(IsLess, E);
13026       case BO_GT:
13027         return Success(IsGreater, E);
13028       case BO_LE:
13029         return Success(IsEqual || IsLess, E);
13030       case BO_GE:
13031         return Success(IsEqual || IsGreater, E);
13032       }
13033     };
13034     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13035       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13036     });
13037   }
13038 
13039   QualType LHSTy = E->getLHS()->getType();
13040   QualType RHSTy = E->getRHS()->getType();
13041 
13042   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13043       E->getOpcode() == BO_Sub) {
13044     LValue LHSValue, RHSValue;
13045 
13046     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13047     if (!LHSOK && !Info.noteFailure())
13048       return false;
13049 
13050     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13051       return false;
13052 
13053     // Reject differing bases from the normal codepath; we special-case
13054     // comparisons to null.
13055     if (!HasSameBase(LHSValue, RHSValue)) {
13056       // Handle &&A - &&B.
13057       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13058         return Error(E);
13059       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13060       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13061       if (!LHSExpr || !RHSExpr)
13062         return Error(E);
13063       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13064       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13065       if (!LHSAddrExpr || !RHSAddrExpr)
13066         return Error(E);
13067       // Make sure both labels come from the same function.
13068       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13069           RHSAddrExpr->getLabel()->getDeclContext())
13070         return Error(E);
13071       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13072     }
13073     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13074     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13075 
13076     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13077     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13078 
13079     // C++11 [expr.add]p6:
13080     //   Unless both pointers point to elements of the same array object, or
13081     //   one past the last element of the array object, the behavior is
13082     //   undefined.
13083     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13084         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13085                                 RHSDesignator))
13086       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13087 
13088     QualType Type = E->getLHS()->getType();
13089     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13090 
13091     CharUnits ElementSize;
13092     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13093       return false;
13094 
13095     // As an extension, a type may have zero size (empty struct or union in
13096     // C, array of zero length). Pointer subtraction in such cases has
13097     // undefined behavior, so is not constant.
13098     if (ElementSize.isZero()) {
13099       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13100           << ElementType;
13101       return false;
13102     }
13103 
13104     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13105     // and produce incorrect results when it overflows. Such behavior
13106     // appears to be non-conforming, but is common, so perhaps we should
13107     // assume the standard intended for such cases to be undefined behavior
13108     // and check for them.
13109 
13110     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13111     // overflow in the final conversion to ptrdiff_t.
13112     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13113     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13114     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13115                     false);
13116     APSInt TrueResult = (LHS - RHS) / ElemSize;
13117     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13118 
13119     if (Result.extend(65) != TrueResult &&
13120         !HandleOverflow(Info, E, TrueResult, E->getType()))
13121       return false;
13122     return Success(Result, E);
13123   }
13124 
13125   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13126 }
13127 
13128 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13129 /// a result as the expression's type.
13130 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13131                                     const UnaryExprOrTypeTraitExpr *E) {
13132   switch(E->getKind()) {
13133   case UETT_PreferredAlignOf:
13134   case UETT_AlignOf: {
13135     if (E->isArgumentType())
13136       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13137                      E);
13138     else
13139       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13140                      E);
13141   }
13142 
13143   case UETT_VecStep: {
13144     QualType Ty = E->getTypeOfArgument();
13145 
13146     if (Ty->isVectorType()) {
13147       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13148 
13149       // The vec_step built-in functions that take a 3-component
13150       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13151       if (n == 3)
13152         n = 4;
13153 
13154       return Success(n, E);
13155     } else
13156       return Success(1, E);
13157   }
13158 
13159   case UETT_SizeOf: {
13160     QualType SrcTy = E->getTypeOfArgument();
13161     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13162     //   the result is the size of the referenced type."
13163     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13164       SrcTy = Ref->getPointeeType();
13165 
13166     CharUnits Sizeof;
13167     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13168       return false;
13169     return Success(Sizeof, E);
13170   }
13171   case UETT_OpenMPRequiredSimdAlign:
13172     assert(E->isArgumentType());
13173     return Success(
13174         Info.Ctx.toCharUnitsFromBits(
13175                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13176             .getQuantity(),
13177         E);
13178   }
13179 
13180   llvm_unreachable("unknown expr/type trait");
13181 }
13182 
13183 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13184   CharUnits Result;
13185   unsigned n = OOE->getNumComponents();
13186   if (n == 0)
13187     return Error(OOE);
13188   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13189   for (unsigned i = 0; i != n; ++i) {
13190     OffsetOfNode ON = OOE->getComponent(i);
13191     switch (ON.getKind()) {
13192     case OffsetOfNode::Array: {
13193       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13194       APSInt IdxResult;
13195       if (!EvaluateInteger(Idx, IdxResult, Info))
13196         return false;
13197       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13198       if (!AT)
13199         return Error(OOE);
13200       CurrentType = AT->getElementType();
13201       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13202       Result += IdxResult.getSExtValue() * ElementSize;
13203       break;
13204     }
13205 
13206     case OffsetOfNode::Field: {
13207       FieldDecl *MemberDecl = ON.getField();
13208       const RecordType *RT = CurrentType->getAs<RecordType>();
13209       if (!RT)
13210         return Error(OOE);
13211       RecordDecl *RD = RT->getDecl();
13212       if (RD->isInvalidDecl()) return false;
13213       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13214       unsigned i = MemberDecl->getFieldIndex();
13215       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13216       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13217       CurrentType = MemberDecl->getType().getNonReferenceType();
13218       break;
13219     }
13220 
13221     case OffsetOfNode::Identifier:
13222       llvm_unreachable("dependent __builtin_offsetof");
13223 
13224     case OffsetOfNode::Base: {
13225       CXXBaseSpecifier *BaseSpec = ON.getBase();
13226       if (BaseSpec->isVirtual())
13227         return Error(OOE);
13228 
13229       // Find the layout of the class whose base we are looking into.
13230       const RecordType *RT = CurrentType->getAs<RecordType>();
13231       if (!RT)
13232         return Error(OOE);
13233       RecordDecl *RD = RT->getDecl();
13234       if (RD->isInvalidDecl()) return false;
13235       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13236 
13237       // Find the base class itself.
13238       CurrentType = BaseSpec->getType();
13239       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13240       if (!BaseRT)
13241         return Error(OOE);
13242 
13243       // Add the offset to the base.
13244       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13245       break;
13246     }
13247     }
13248   }
13249   return Success(Result, OOE);
13250 }
13251 
13252 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13253   switch (E->getOpcode()) {
13254   default:
13255     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13256     // See C99 6.6p3.
13257     return Error(E);
13258   case UO_Extension:
13259     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13260     // If so, we could clear the diagnostic ID.
13261     return Visit(E->getSubExpr());
13262   case UO_Plus:
13263     // The result is just the value.
13264     return Visit(E->getSubExpr());
13265   case UO_Minus: {
13266     if (!Visit(E->getSubExpr()))
13267       return false;
13268     if (!Result.isInt()) return Error(E);
13269     const APSInt &Value = Result.getInt();
13270     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13271         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13272                         E->getType()))
13273       return false;
13274     return Success(-Value, E);
13275   }
13276   case UO_Not: {
13277     if (!Visit(E->getSubExpr()))
13278       return false;
13279     if (!Result.isInt()) return Error(E);
13280     return Success(~Result.getInt(), E);
13281   }
13282   case UO_LNot: {
13283     bool bres;
13284     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13285       return false;
13286     return Success(!bres, E);
13287   }
13288   }
13289 }
13290 
13291 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13292 /// result type is integer.
13293 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13294   const Expr *SubExpr = E->getSubExpr();
13295   QualType DestType = E->getType();
13296   QualType SrcType = SubExpr->getType();
13297 
13298   switch (E->getCastKind()) {
13299   case CK_BaseToDerived:
13300   case CK_DerivedToBase:
13301   case CK_UncheckedDerivedToBase:
13302   case CK_Dynamic:
13303   case CK_ToUnion:
13304   case CK_ArrayToPointerDecay:
13305   case CK_FunctionToPointerDecay:
13306   case CK_NullToPointer:
13307   case CK_NullToMemberPointer:
13308   case CK_BaseToDerivedMemberPointer:
13309   case CK_DerivedToBaseMemberPointer:
13310   case CK_ReinterpretMemberPointer:
13311   case CK_ConstructorConversion:
13312   case CK_IntegralToPointer:
13313   case CK_ToVoid:
13314   case CK_VectorSplat:
13315   case CK_IntegralToFloating:
13316   case CK_FloatingCast:
13317   case CK_CPointerToObjCPointerCast:
13318   case CK_BlockPointerToObjCPointerCast:
13319   case CK_AnyPointerToBlockPointerCast:
13320   case CK_ObjCObjectLValueCast:
13321   case CK_FloatingRealToComplex:
13322   case CK_FloatingComplexToReal:
13323   case CK_FloatingComplexCast:
13324   case CK_FloatingComplexToIntegralComplex:
13325   case CK_IntegralRealToComplex:
13326   case CK_IntegralComplexCast:
13327   case CK_IntegralComplexToFloatingComplex:
13328   case CK_BuiltinFnToFnPtr:
13329   case CK_ZeroToOCLOpaqueType:
13330   case CK_NonAtomicToAtomic:
13331   case CK_AddressSpaceConversion:
13332   case CK_IntToOCLSampler:
13333   case CK_FloatingToFixedPoint:
13334   case CK_FixedPointToFloating:
13335   case CK_FixedPointCast:
13336   case CK_IntegralToFixedPoint:
13337   case CK_MatrixCast:
13338     llvm_unreachable("invalid cast kind for integral value");
13339 
13340   case CK_BitCast:
13341   case CK_Dependent:
13342   case CK_LValueBitCast:
13343   case CK_ARCProduceObject:
13344   case CK_ARCConsumeObject:
13345   case CK_ARCReclaimReturnedObject:
13346   case CK_ARCExtendBlockObject:
13347   case CK_CopyAndAutoreleaseBlockObject:
13348     return Error(E);
13349 
13350   case CK_UserDefinedConversion:
13351   case CK_LValueToRValue:
13352   case CK_AtomicToNonAtomic:
13353   case CK_NoOp:
13354   case CK_LValueToRValueBitCast:
13355     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13356 
13357   case CK_MemberPointerToBoolean:
13358   case CK_PointerToBoolean:
13359   case CK_IntegralToBoolean:
13360   case CK_FloatingToBoolean:
13361   case CK_BooleanToSignedIntegral:
13362   case CK_FloatingComplexToBoolean:
13363   case CK_IntegralComplexToBoolean: {
13364     bool BoolResult;
13365     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13366       return false;
13367     uint64_t IntResult = BoolResult;
13368     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13369       IntResult = (uint64_t)-1;
13370     return Success(IntResult, E);
13371   }
13372 
13373   case CK_FixedPointToIntegral: {
13374     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13375     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13376       return false;
13377     bool Overflowed;
13378     llvm::APSInt Result = Src.convertToInt(
13379         Info.Ctx.getIntWidth(DestType),
13380         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13381     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13382       return false;
13383     return Success(Result, E);
13384   }
13385 
13386   case CK_FixedPointToBoolean: {
13387     // Unsigned padding does not affect this.
13388     APValue Val;
13389     if (!Evaluate(Val, Info, SubExpr))
13390       return false;
13391     return Success(Val.getFixedPoint().getBoolValue(), E);
13392   }
13393 
13394   case CK_IntegralCast: {
13395     if (!Visit(SubExpr))
13396       return false;
13397 
13398     if (!Result.isInt()) {
13399       // Allow casts of address-of-label differences if they are no-ops
13400       // or narrowing.  (The narrowing case isn't actually guaranteed to
13401       // be constant-evaluatable except in some narrow cases which are hard
13402       // to detect here.  We let it through on the assumption the user knows
13403       // what they are doing.)
13404       if (Result.isAddrLabelDiff())
13405         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13406       // Only allow casts of lvalues if they are lossless.
13407       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13408     }
13409 
13410     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13411                                       Result.getInt()), E);
13412   }
13413 
13414   case CK_PointerToIntegral: {
13415     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13416 
13417     LValue LV;
13418     if (!EvaluatePointer(SubExpr, LV, Info))
13419       return false;
13420 
13421     if (LV.getLValueBase()) {
13422       // Only allow based lvalue casts if they are lossless.
13423       // FIXME: Allow a larger integer size than the pointer size, and allow
13424       // narrowing back down to pointer width in subsequent integral casts.
13425       // FIXME: Check integer type's active bits, not its type size.
13426       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13427         return Error(E);
13428 
13429       LV.Designator.setInvalid();
13430       LV.moveInto(Result);
13431       return true;
13432     }
13433 
13434     APSInt AsInt;
13435     APValue V;
13436     LV.moveInto(V);
13437     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13438       llvm_unreachable("Can't cast this!");
13439 
13440     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13441   }
13442 
13443   case CK_IntegralComplexToReal: {
13444     ComplexValue C;
13445     if (!EvaluateComplex(SubExpr, C, Info))
13446       return false;
13447     return Success(C.getComplexIntReal(), E);
13448   }
13449 
13450   case CK_FloatingToIntegral: {
13451     APFloat F(0.0);
13452     if (!EvaluateFloat(SubExpr, F, Info))
13453       return false;
13454 
13455     APSInt Value;
13456     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13457       return false;
13458     return Success(Value, E);
13459   }
13460   }
13461 
13462   llvm_unreachable("unknown cast resulting in integral value");
13463 }
13464 
13465 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13466   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13467     ComplexValue LV;
13468     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13469       return false;
13470     if (!LV.isComplexInt())
13471       return Error(E);
13472     return Success(LV.getComplexIntReal(), E);
13473   }
13474 
13475   return Visit(E->getSubExpr());
13476 }
13477 
13478 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13479   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13480     ComplexValue LV;
13481     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13482       return false;
13483     if (!LV.isComplexInt())
13484       return Error(E);
13485     return Success(LV.getComplexIntImag(), E);
13486   }
13487 
13488   VisitIgnoredValue(E->getSubExpr());
13489   return Success(0, E);
13490 }
13491 
13492 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13493   return Success(E->getPackLength(), E);
13494 }
13495 
13496 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13497   return Success(E->getValue(), E);
13498 }
13499 
13500 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13501        const ConceptSpecializationExpr *E) {
13502   return Success(E->isSatisfied(), E);
13503 }
13504 
13505 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13506   return Success(E->isSatisfied(), E);
13507 }
13508 
13509 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13510   switch (E->getOpcode()) {
13511     default:
13512       // Invalid unary operators
13513       return Error(E);
13514     case UO_Plus:
13515       // The result is just the value.
13516       return Visit(E->getSubExpr());
13517     case UO_Minus: {
13518       if (!Visit(E->getSubExpr())) return false;
13519       if (!Result.isFixedPoint())
13520         return Error(E);
13521       bool Overflowed;
13522       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13523       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13524         return false;
13525       return Success(Negated, E);
13526     }
13527     case UO_LNot: {
13528       bool bres;
13529       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13530         return false;
13531       return Success(!bres, E);
13532     }
13533   }
13534 }
13535 
13536 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13537   const Expr *SubExpr = E->getSubExpr();
13538   QualType DestType = E->getType();
13539   assert(DestType->isFixedPointType() &&
13540          "Expected destination type to be a fixed point type");
13541   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13542 
13543   switch (E->getCastKind()) {
13544   case CK_FixedPointCast: {
13545     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13546     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13547       return false;
13548     bool Overflowed;
13549     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13550     if (Overflowed) {
13551       if (Info.checkingForUndefinedBehavior())
13552         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13553                                          diag::warn_fixedpoint_constant_overflow)
13554           << Result.toString() << E->getType();
13555       if (!HandleOverflow(Info, E, Result, E->getType()))
13556         return false;
13557     }
13558     return Success(Result, E);
13559   }
13560   case CK_IntegralToFixedPoint: {
13561     APSInt Src;
13562     if (!EvaluateInteger(SubExpr, Src, Info))
13563       return false;
13564 
13565     bool Overflowed;
13566     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13567         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13568 
13569     if (Overflowed) {
13570       if (Info.checkingForUndefinedBehavior())
13571         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13572                                          diag::warn_fixedpoint_constant_overflow)
13573           << IntResult.toString() << E->getType();
13574       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13575         return false;
13576     }
13577 
13578     return Success(IntResult, E);
13579   }
13580   case CK_FloatingToFixedPoint: {
13581     APFloat Src(0.0);
13582     if (!EvaluateFloat(SubExpr, Src, Info))
13583       return false;
13584 
13585     bool Overflowed;
13586     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13587         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13588 
13589     if (Overflowed) {
13590       if (Info.checkingForUndefinedBehavior())
13591         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13592                                          diag::warn_fixedpoint_constant_overflow)
13593           << Result.toString() << E->getType();
13594       if (!HandleOverflow(Info, E, Result, E->getType()))
13595         return false;
13596     }
13597 
13598     return Success(Result, E);
13599   }
13600   case CK_NoOp:
13601   case CK_LValueToRValue:
13602     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13603   default:
13604     return Error(E);
13605   }
13606 }
13607 
13608 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13609   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13610     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13611 
13612   const Expr *LHS = E->getLHS();
13613   const Expr *RHS = E->getRHS();
13614   FixedPointSemantics ResultFXSema =
13615       Info.Ctx.getFixedPointSemantics(E->getType());
13616 
13617   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13618   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13619     return false;
13620   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13621   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13622     return false;
13623 
13624   bool OpOverflow = false, ConversionOverflow = false;
13625   APFixedPoint Result(LHSFX.getSemantics());
13626   switch (E->getOpcode()) {
13627   case BO_Add: {
13628     Result = LHSFX.add(RHSFX, &OpOverflow)
13629                   .convert(ResultFXSema, &ConversionOverflow);
13630     break;
13631   }
13632   case BO_Sub: {
13633     Result = LHSFX.sub(RHSFX, &OpOverflow)
13634                   .convert(ResultFXSema, &ConversionOverflow);
13635     break;
13636   }
13637   case BO_Mul: {
13638     Result = LHSFX.mul(RHSFX, &OpOverflow)
13639                   .convert(ResultFXSema, &ConversionOverflow);
13640     break;
13641   }
13642   case BO_Div: {
13643     if (RHSFX.getValue() == 0) {
13644       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13645       return false;
13646     }
13647     Result = LHSFX.div(RHSFX, &OpOverflow)
13648                   .convert(ResultFXSema, &ConversionOverflow);
13649     break;
13650   }
13651   case BO_Shl:
13652   case BO_Shr: {
13653     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13654     llvm::APSInt RHSVal = RHSFX.getValue();
13655 
13656     unsigned ShiftBW =
13657         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13658     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13659     // Embedded-C 4.1.6.2.2:
13660     //   The right operand must be nonnegative and less than the total number
13661     //   of (nonpadding) bits of the fixed-point operand ...
13662     if (RHSVal.isNegative())
13663       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13664     else if (Amt != RHSVal)
13665       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13666           << RHSVal << E->getType() << ShiftBW;
13667 
13668     if (E->getOpcode() == BO_Shl)
13669       Result = LHSFX.shl(Amt, &OpOverflow);
13670     else
13671       Result = LHSFX.shr(Amt, &OpOverflow);
13672     break;
13673   }
13674   default:
13675     return false;
13676   }
13677   if (OpOverflow || ConversionOverflow) {
13678     if (Info.checkingForUndefinedBehavior())
13679       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13680                                        diag::warn_fixedpoint_constant_overflow)
13681         << Result.toString() << E->getType();
13682     if (!HandleOverflow(Info, E, Result, E->getType()))
13683       return false;
13684   }
13685   return Success(Result, E);
13686 }
13687 
13688 //===----------------------------------------------------------------------===//
13689 // Float Evaluation
13690 //===----------------------------------------------------------------------===//
13691 
13692 namespace {
13693 class FloatExprEvaluator
13694   : public ExprEvaluatorBase<FloatExprEvaluator> {
13695   APFloat &Result;
13696 public:
13697   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13698     : ExprEvaluatorBaseTy(info), Result(result) {}
13699 
13700   bool Success(const APValue &V, const Expr *e) {
13701     Result = V.getFloat();
13702     return true;
13703   }
13704 
13705   bool ZeroInitialization(const Expr *E) {
13706     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13707     return true;
13708   }
13709 
13710   bool VisitCallExpr(const CallExpr *E);
13711 
13712   bool VisitUnaryOperator(const UnaryOperator *E);
13713   bool VisitBinaryOperator(const BinaryOperator *E);
13714   bool VisitFloatingLiteral(const FloatingLiteral *E);
13715   bool VisitCastExpr(const CastExpr *E);
13716 
13717   bool VisitUnaryReal(const UnaryOperator *E);
13718   bool VisitUnaryImag(const UnaryOperator *E);
13719 
13720   // FIXME: Missing: array subscript of vector, member of vector
13721 };
13722 } // end anonymous namespace
13723 
13724 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13725   assert(!E->isValueDependent());
13726   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13727   return FloatExprEvaluator(Info, Result).Visit(E);
13728 }
13729 
13730 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13731                                   QualType ResultTy,
13732                                   const Expr *Arg,
13733                                   bool SNaN,
13734                                   llvm::APFloat &Result) {
13735   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13736   if (!S) return false;
13737 
13738   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13739 
13740   llvm::APInt fill;
13741 
13742   // Treat empty strings as if they were zero.
13743   if (S->getString().empty())
13744     fill = llvm::APInt(32, 0);
13745   else if (S->getString().getAsInteger(0, fill))
13746     return false;
13747 
13748   if (Context.getTargetInfo().isNan2008()) {
13749     if (SNaN)
13750       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13751     else
13752       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13753   } else {
13754     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13755     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13756     // a different encoding to what became a standard in 2008, and for pre-
13757     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13758     // sNaN. This is now known as "legacy NaN" encoding.
13759     if (SNaN)
13760       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13761     else
13762       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13763   }
13764 
13765   return true;
13766 }
13767 
13768 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13769   switch (E->getBuiltinCallee()) {
13770   default:
13771     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13772 
13773   case Builtin::BI__builtin_huge_val:
13774   case Builtin::BI__builtin_huge_valf:
13775   case Builtin::BI__builtin_huge_vall:
13776   case Builtin::BI__builtin_huge_valf128:
13777   case Builtin::BI__builtin_inf:
13778   case Builtin::BI__builtin_inff:
13779   case Builtin::BI__builtin_infl:
13780   case Builtin::BI__builtin_inff128: {
13781     const llvm::fltSemantics &Sem =
13782       Info.Ctx.getFloatTypeSemantics(E->getType());
13783     Result = llvm::APFloat::getInf(Sem);
13784     return true;
13785   }
13786 
13787   case Builtin::BI__builtin_nans:
13788   case Builtin::BI__builtin_nansf:
13789   case Builtin::BI__builtin_nansl:
13790   case Builtin::BI__builtin_nansf128:
13791     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13792                                true, Result))
13793       return Error(E);
13794     return true;
13795 
13796   case Builtin::BI__builtin_nan:
13797   case Builtin::BI__builtin_nanf:
13798   case Builtin::BI__builtin_nanl:
13799   case Builtin::BI__builtin_nanf128:
13800     // If this is __builtin_nan() turn this into a nan, otherwise we
13801     // can't constant fold it.
13802     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13803                                false, Result))
13804       return Error(E);
13805     return true;
13806 
13807   case Builtin::BI__builtin_fabs:
13808   case Builtin::BI__builtin_fabsf:
13809   case Builtin::BI__builtin_fabsl:
13810   case Builtin::BI__builtin_fabsf128:
13811     // The C standard says "fabs raises no floating-point exceptions,
13812     // even if x is a signaling NaN. The returned value is independent of
13813     // the current rounding direction mode."  Therefore constant folding can
13814     // proceed without regard to the floating point settings.
13815     // Reference, WG14 N2478 F.10.4.3
13816     if (!EvaluateFloat(E->getArg(0), Result, Info))
13817       return false;
13818 
13819     if (Result.isNegative())
13820       Result.changeSign();
13821     return true;
13822 
13823   case Builtin::BI__arithmetic_fence:
13824     return EvaluateFloat(E->getArg(0), Result, Info);
13825 
13826   // FIXME: Builtin::BI__builtin_powi
13827   // FIXME: Builtin::BI__builtin_powif
13828   // FIXME: Builtin::BI__builtin_powil
13829 
13830   case Builtin::BI__builtin_copysign:
13831   case Builtin::BI__builtin_copysignf:
13832   case Builtin::BI__builtin_copysignl:
13833   case Builtin::BI__builtin_copysignf128: {
13834     APFloat RHS(0.);
13835     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13836         !EvaluateFloat(E->getArg(1), RHS, Info))
13837       return false;
13838     Result.copySign(RHS);
13839     return true;
13840   }
13841   }
13842 }
13843 
13844 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13845   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13846     ComplexValue CV;
13847     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13848       return false;
13849     Result = CV.FloatReal;
13850     return true;
13851   }
13852 
13853   return Visit(E->getSubExpr());
13854 }
13855 
13856 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13857   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13858     ComplexValue CV;
13859     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13860       return false;
13861     Result = CV.FloatImag;
13862     return true;
13863   }
13864 
13865   VisitIgnoredValue(E->getSubExpr());
13866   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13867   Result = llvm::APFloat::getZero(Sem);
13868   return true;
13869 }
13870 
13871 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13872   switch (E->getOpcode()) {
13873   default: return Error(E);
13874   case UO_Plus:
13875     return EvaluateFloat(E->getSubExpr(), Result, Info);
13876   case UO_Minus:
13877     // In C standard, WG14 N2478 F.3 p4
13878     // "the unary - raises no floating point exceptions,
13879     // even if the operand is signalling."
13880     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13881       return false;
13882     Result.changeSign();
13883     return true;
13884   }
13885 }
13886 
13887 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13888   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13889     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13890 
13891   APFloat RHS(0.0);
13892   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13893   if (!LHSOK && !Info.noteFailure())
13894     return false;
13895   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13896          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13897 }
13898 
13899 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13900   Result = E->getValue();
13901   return true;
13902 }
13903 
13904 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13905   const Expr* SubExpr = E->getSubExpr();
13906 
13907   switch (E->getCastKind()) {
13908   default:
13909     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13910 
13911   case CK_IntegralToFloating: {
13912     APSInt IntResult;
13913     const FPOptions FPO = E->getFPFeaturesInEffect(
13914                                   Info.Ctx.getLangOpts());
13915     return EvaluateInteger(SubExpr, IntResult, Info) &&
13916            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13917                                 IntResult, E->getType(), Result);
13918   }
13919 
13920   case CK_FixedPointToFloating: {
13921     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13922     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13923       return false;
13924     Result =
13925         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13926     return true;
13927   }
13928 
13929   case CK_FloatingCast: {
13930     if (!Visit(SubExpr))
13931       return false;
13932     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13933                                   Result);
13934   }
13935 
13936   case CK_FloatingComplexToReal: {
13937     ComplexValue V;
13938     if (!EvaluateComplex(SubExpr, V, Info))
13939       return false;
13940     Result = V.getComplexFloatReal();
13941     return true;
13942   }
13943   }
13944 }
13945 
13946 //===----------------------------------------------------------------------===//
13947 // Complex Evaluation (for float and integer)
13948 //===----------------------------------------------------------------------===//
13949 
13950 namespace {
13951 class ComplexExprEvaluator
13952   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13953   ComplexValue &Result;
13954 
13955 public:
13956   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13957     : ExprEvaluatorBaseTy(info), Result(Result) {}
13958 
13959   bool Success(const APValue &V, const Expr *e) {
13960     Result.setFrom(V);
13961     return true;
13962   }
13963 
13964   bool ZeroInitialization(const Expr *E);
13965 
13966   //===--------------------------------------------------------------------===//
13967   //                            Visitor Methods
13968   //===--------------------------------------------------------------------===//
13969 
13970   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13971   bool VisitCastExpr(const CastExpr *E);
13972   bool VisitBinaryOperator(const BinaryOperator *E);
13973   bool VisitUnaryOperator(const UnaryOperator *E);
13974   bool VisitInitListExpr(const InitListExpr *E);
13975   bool VisitCallExpr(const CallExpr *E);
13976 };
13977 } // end anonymous namespace
13978 
13979 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13980                             EvalInfo &Info) {
13981   assert(!E->isValueDependent());
13982   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13983   return ComplexExprEvaluator(Info, Result).Visit(E);
13984 }
13985 
13986 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13987   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13988   if (ElemTy->isRealFloatingType()) {
13989     Result.makeComplexFloat();
13990     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13991     Result.FloatReal = Zero;
13992     Result.FloatImag = Zero;
13993   } else {
13994     Result.makeComplexInt();
13995     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13996     Result.IntReal = Zero;
13997     Result.IntImag = Zero;
13998   }
13999   return true;
14000 }
14001 
14002 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14003   const Expr* SubExpr = E->getSubExpr();
14004 
14005   if (SubExpr->getType()->isRealFloatingType()) {
14006     Result.makeComplexFloat();
14007     APFloat &Imag = Result.FloatImag;
14008     if (!EvaluateFloat(SubExpr, Imag, Info))
14009       return false;
14010 
14011     Result.FloatReal = APFloat(Imag.getSemantics());
14012     return true;
14013   } else {
14014     assert(SubExpr->getType()->isIntegerType() &&
14015            "Unexpected imaginary literal.");
14016 
14017     Result.makeComplexInt();
14018     APSInt &Imag = Result.IntImag;
14019     if (!EvaluateInteger(SubExpr, Imag, Info))
14020       return false;
14021 
14022     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14023     return true;
14024   }
14025 }
14026 
14027 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14028 
14029   switch (E->getCastKind()) {
14030   case CK_BitCast:
14031   case CK_BaseToDerived:
14032   case CK_DerivedToBase:
14033   case CK_UncheckedDerivedToBase:
14034   case CK_Dynamic:
14035   case CK_ToUnion:
14036   case CK_ArrayToPointerDecay:
14037   case CK_FunctionToPointerDecay:
14038   case CK_NullToPointer:
14039   case CK_NullToMemberPointer:
14040   case CK_BaseToDerivedMemberPointer:
14041   case CK_DerivedToBaseMemberPointer:
14042   case CK_MemberPointerToBoolean:
14043   case CK_ReinterpretMemberPointer:
14044   case CK_ConstructorConversion:
14045   case CK_IntegralToPointer:
14046   case CK_PointerToIntegral:
14047   case CK_PointerToBoolean:
14048   case CK_ToVoid:
14049   case CK_VectorSplat:
14050   case CK_IntegralCast:
14051   case CK_BooleanToSignedIntegral:
14052   case CK_IntegralToBoolean:
14053   case CK_IntegralToFloating:
14054   case CK_FloatingToIntegral:
14055   case CK_FloatingToBoolean:
14056   case CK_FloatingCast:
14057   case CK_CPointerToObjCPointerCast:
14058   case CK_BlockPointerToObjCPointerCast:
14059   case CK_AnyPointerToBlockPointerCast:
14060   case CK_ObjCObjectLValueCast:
14061   case CK_FloatingComplexToReal:
14062   case CK_FloatingComplexToBoolean:
14063   case CK_IntegralComplexToReal:
14064   case CK_IntegralComplexToBoolean:
14065   case CK_ARCProduceObject:
14066   case CK_ARCConsumeObject:
14067   case CK_ARCReclaimReturnedObject:
14068   case CK_ARCExtendBlockObject:
14069   case CK_CopyAndAutoreleaseBlockObject:
14070   case CK_BuiltinFnToFnPtr:
14071   case CK_ZeroToOCLOpaqueType:
14072   case CK_NonAtomicToAtomic:
14073   case CK_AddressSpaceConversion:
14074   case CK_IntToOCLSampler:
14075   case CK_FloatingToFixedPoint:
14076   case CK_FixedPointToFloating:
14077   case CK_FixedPointCast:
14078   case CK_FixedPointToBoolean:
14079   case CK_FixedPointToIntegral:
14080   case CK_IntegralToFixedPoint:
14081   case CK_MatrixCast:
14082     llvm_unreachable("invalid cast kind for complex value");
14083 
14084   case CK_LValueToRValue:
14085   case CK_AtomicToNonAtomic:
14086   case CK_NoOp:
14087   case CK_LValueToRValueBitCast:
14088     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14089 
14090   case CK_Dependent:
14091   case CK_LValueBitCast:
14092   case CK_UserDefinedConversion:
14093     return Error(E);
14094 
14095   case CK_FloatingRealToComplex: {
14096     APFloat &Real = Result.FloatReal;
14097     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14098       return false;
14099 
14100     Result.makeComplexFloat();
14101     Result.FloatImag = APFloat(Real.getSemantics());
14102     return true;
14103   }
14104 
14105   case CK_FloatingComplexCast: {
14106     if (!Visit(E->getSubExpr()))
14107       return false;
14108 
14109     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14110     QualType From
14111       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14112 
14113     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14114            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14115   }
14116 
14117   case CK_FloatingComplexToIntegralComplex: {
14118     if (!Visit(E->getSubExpr()))
14119       return false;
14120 
14121     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14122     QualType From
14123       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14124     Result.makeComplexInt();
14125     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14126                                 To, Result.IntReal) &&
14127            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14128                                 To, Result.IntImag);
14129   }
14130 
14131   case CK_IntegralRealToComplex: {
14132     APSInt &Real = Result.IntReal;
14133     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14134       return false;
14135 
14136     Result.makeComplexInt();
14137     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14138     return true;
14139   }
14140 
14141   case CK_IntegralComplexCast: {
14142     if (!Visit(E->getSubExpr()))
14143       return false;
14144 
14145     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14146     QualType From
14147       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14148 
14149     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14150     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14151     return true;
14152   }
14153 
14154   case CK_IntegralComplexToFloatingComplex: {
14155     if (!Visit(E->getSubExpr()))
14156       return false;
14157 
14158     const FPOptions FPO = E->getFPFeaturesInEffect(
14159                                   Info.Ctx.getLangOpts());
14160     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14161     QualType From
14162       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14163     Result.makeComplexFloat();
14164     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14165                                 To, Result.FloatReal) &&
14166            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14167                                 To, Result.FloatImag);
14168   }
14169   }
14170 
14171   llvm_unreachable("unknown cast resulting in complex value");
14172 }
14173 
14174 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14175   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14176     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14177 
14178   // Track whether the LHS or RHS is real at the type system level. When this is
14179   // the case we can simplify our evaluation strategy.
14180   bool LHSReal = false, RHSReal = false;
14181 
14182   bool LHSOK;
14183   if (E->getLHS()->getType()->isRealFloatingType()) {
14184     LHSReal = true;
14185     APFloat &Real = Result.FloatReal;
14186     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14187     if (LHSOK) {
14188       Result.makeComplexFloat();
14189       Result.FloatImag = APFloat(Real.getSemantics());
14190     }
14191   } else {
14192     LHSOK = Visit(E->getLHS());
14193   }
14194   if (!LHSOK && !Info.noteFailure())
14195     return false;
14196 
14197   ComplexValue RHS;
14198   if (E->getRHS()->getType()->isRealFloatingType()) {
14199     RHSReal = true;
14200     APFloat &Real = RHS.FloatReal;
14201     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14202       return false;
14203     RHS.makeComplexFloat();
14204     RHS.FloatImag = APFloat(Real.getSemantics());
14205   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14206     return false;
14207 
14208   assert(!(LHSReal && RHSReal) &&
14209          "Cannot have both operands of a complex operation be real.");
14210   switch (E->getOpcode()) {
14211   default: return Error(E);
14212   case BO_Add:
14213     if (Result.isComplexFloat()) {
14214       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14215                                        APFloat::rmNearestTiesToEven);
14216       if (LHSReal)
14217         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14218       else if (!RHSReal)
14219         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14220                                          APFloat::rmNearestTiesToEven);
14221     } else {
14222       Result.getComplexIntReal() += RHS.getComplexIntReal();
14223       Result.getComplexIntImag() += RHS.getComplexIntImag();
14224     }
14225     break;
14226   case BO_Sub:
14227     if (Result.isComplexFloat()) {
14228       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14229                                             APFloat::rmNearestTiesToEven);
14230       if (LHSReal) {
14231         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14232         Result.getComplexFloatImag().changeSign();
14233       } else if (!RHSReal) {
14234         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14235                                               APFloat::rmNearestTiesToEven);
14236       }
14237     } else {
14238       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14239       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14240     }
14241     break;
14242   case BO_Mul:
14243     if (Result.isComplexFloat()) {
14244       // This is an implementation of complex multiplication according to the
14245       // constraints laid out in C11 Annex G. The implementation uses the
14246       // following naming scheme:
14247       //   (a + ib) * (c + id)
14248       ComplexValue LHS = Result;
14249       APFloat &A = LHS.getComplexFloatReal();
14250       APFloat &B = LHS.getComplexFloatImag();
14251       APFloat &C = RHS.getComplexFloatReal();
14252       APFloat &D = RHS.getComplexFloatImag();
14253       APFloat &ResR = Result.getComplexFloatReal();
14254       APFloat &ResI = Result.getComplexFloatImag();
14255       if (LHSReal) {
14256         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14257         ResR = A * C;
14258         ResI = A * D;
14259       } else if (RHSReal) {
14260         ResR = C * A;
14261         ResI = C * B;
14262       } else {
14263         // In the fully general case, we need to handle NaNs and infinities
14264         // robustly.
14265         APFloat AC = A * C;
14266         APFloat BD = B * D;
14267         APFloat AD = A * D;
14268         APFloat BC = B * C;
14269         ResR = AC - BD;
14270         ResI = AD + BC;
14271         if (ResR.isNaN() && ResI.isNaN()) {
14272           bool Recalc = false;
14273           if (A.isInfinity() || B.isInfinity()) {
14274             A = APFloat::copySign(
14275                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14276             B = APFloat::copySign(
14277                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14278             if (C.isNaN())
14279               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14280             if (D.isNaN())
14281               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14282             Recalc = true;
14283           }
14284           if (C.isInfinity() || D.isInfinity()) {
14285             C = APFloat::copySign(
14286                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14287             D = APFloat::copySign(
14288                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14289             if (A.isNaN())
14290               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14291             if (B.isNaN())
14292               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14293             Recalc = true;
14294           }
14295           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14296                           AD.isInfinity() || BC.isInfinity())) {
14297             if (A.isNaN())
14298               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14299             if (B.isNaN())
14300               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14301             if (C.isNaN())
14302               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14303             if (D.isNaN())
14304               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14305             Recalc = true;
14306           }
14307           if (Recalc) {
14308             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14309             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14310           }
14311         }
14312       }
14313     } else {
14314       ComplexValue LHS = Result;
14315       Result.getComplexIntReal() =
14316         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14317          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14318       Result.getComplexIntImag() =
14319         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14320          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14321     }
14322     break;
14323   case BO_Div:
14324     if (Result.isComplexFloat()) {
14325       // This is an implementation of complex division according to the
14326       // constraints laid out in C11 Annex G. The implementation uses the
14327       // following naming scheme:
14328       //   (a + ib) / (c + id)
14329       ComplexValue LHS = Result;
14330       APFloat &A = LHS.getComplexFloatReal();
14331       APFloat &B = LHS.getComplexFloatImag();
14332       APFloat &C = RHS.getComplexFloatReal();
14333       APFloat &D = RHS.getComplexFloatImag();
14334       APFloat &ResR = Result.getComplexFloatReal();
14335       APFloat &ResI = Result.getComplexFloatImag();
14336       if (RHSReal) {
14337         ResR = A / C;
14338         ResI = B / C;
14339       } else {
14340         if (LHSReal) {
14341           // No real optimizations we can do here, stub out with zero.
14342           B = APFloat::getZero(A.getSemantics());
14343         }
14344         int DenomLogB = 0;
14345         APFloat MaxCD = maxnum(abs(C), abs(D));
14346         if (MaxCD.isFinite()) {
14347           DenomLogB = ilogb(MaxCD);
14348           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14349           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14350         }
14351         APFloat Denom = C * C + D * D;
14352         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14353                       APFloat::rmNearestTiesToEven);
14354         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14355                       APFloat::rmNearestTiesToEven);
14356         if (ResR.isNaN() && ResI.isNaN()) {
14357           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14358             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14359             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14360           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14361                      D.isFinite()) {
14362             A = APFloat::copySign(
14363                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14364             B = APFloat::copySign(
14365                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14366             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14367             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14368           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14369             C = APFloat::copySign(
14370                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14371             D = APFloat::copySign(
14372                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14373             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14374             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14375           }
14376         }
14377       }
14378     } else {
14379       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14380         return Error(E, diag::note_expr_divide_by_zero);
14381 
14382       ComplexValue LHS = Result;
14383       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14384         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14385       Result.getComplexIntReal() =
14386         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14387          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14388       Result.getComplexIntImag() =
14389         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14390          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14391     }
14392     break;
14393   }
14394 
14395   return true;
14396 }
14397 
14398 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14399   // Get the operand value into 'Result'.
14400   if (!Visit(E->getSubExpr()))
14401     return false;
14402 
14403   switch (E->getOpcode()) {
14404   default:
14405     return Error(E);
14406   case UO_Extension:
14407     return true;
14408   case UO_Plus:
14409     // The result is always just the subexpr.
14410     return true;
14411   case UO_Minus:
14412     if (Result.isComplexFloat()) {
14413       Result.getComplexFloatReal().changeSign();
14414       Result.getComplexFloatImag().changeSign();
14415     }
14416     else {
14417       Result.getComplexIntReal() = -Result.getComplexIntReal();
14418       Result.getComplexIntImag() = -Result.getComplexIntImag();
14419     }
14420     return true;
14421   case UO_Not:
14422     if (Result.isComplexFloat())
14423       Result.getComplexFloatImag().changeSign();
14424     else
14425       Result.getComplexIntImag() = -Result.getComplexIntImag();
14426     return true;
14427   }
14428 }
14429 
14430 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14431   if (E->getNumInits() == 2) {
14432     if (E->getType()->isComplexType()) {
14433       Result.makeComplexFloat();
14434       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14435         return false;
14436       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14437         return false;
14438     } else {
14439       Result.makeComplexInt();
14440       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14441         return false;
14442       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14443         return false;
14444     }
14445     return true;
14446   }
14447   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14448 }
14449 
14450 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14451   switch (E->getBuiltinCallee()) {
14452   case Builtin::BI__builtin_complex:
14453     Result.makeComplexFloat();
14454     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14455       return false;
14456     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14457       return false;
14458     return true;
14459 
14460   default:
14461     break;
14462   }
14463 
14464   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14465 }
14466 
14467 //===----------------------------------------------------------------------===//
14468 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14469 // implicit conversion.
14470 //===----------------------------------------------------------------------===//
14471 
14472 namespace {
14473 class AtomicExprEvaluator :
14474     public ExprEvaluatorBase<AtomicExprEvaluator> {
14475   const LValue *This;
14476   APValue &Result;
14477 public:
14478   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14479       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14480 
14481   bool Success(const APValue &V, const Expr *E) {
14482     Result = V;
14483     return true;
14484   }
14485 
14486   bool ZeroInitialization(const Expr *E) {
14487     ImplicitValueInitExpr VIE(
14488         E->getType()->castAs<AtomicType>()->getValueType());
14489     // For atomic-qualified class (and array) types in C++, initialize the
14490     // _Atomic-wrapped subobject directly, in-place.
14491     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14492                 : Evaluate(Result, Info, &VIE);
14493   }
14494 
14495   bool VisitCastExpr(const CastExpr *E) {
14496     switch (E->getCastKind()) {
14497     default:
14498       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14499     case CK_NonAtomicToAtomic:
14500       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14501                   : Evaluate(Result, Info, E->getSubExpr());
14502     }
14503   }
14504 };
14505 } // end anonymous namespace
14506 
14507 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14508                            EvalInfo &Info) {
14509   assert(!E->isValueDependent());
14510   assert(E->isPRValue() && E->getType()->isAtomicType());
14511   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14512 }
14513 
14514 //===----------------------------------------------------------------------===//
14515 // Void expression evaluation, primarily for a cast to void on the LHS of a
14516 // comma operator
14517 //===----------------------------------------------------------------------===//
14518 
14519 namespace {
14520 class VoidExprEvaluator
14521   : public ExprEvaluatorBase<VoidExprEvaluator> {
14522 public:
14523   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14524 
14525   bool Success(const APValue &V, const Expr *e) { return true; }
14526 
14527   bool ZeroInitialization(const Expr *E) { return true; }
14528 
14529   bool VisitCastExpr(const CastExpr *E) {
14530     switch (E->getCastKind()) {
14531     default:
14532       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14533     case CK_ToVoid:
14534       VisitIgnoredValue(E->getSubExpr());
14535       return true;
14536     }
14537   }
14538 
14539   bool VisitCallExpr(const CallExpr *E) {
14540     switch (E->getBuiltinCallee()) {
14541     case Builtin::BI__assume:
14542     case Builtin::BI__builtin_assume:
14543       // The argument is not evaluated!
14544       return true;
14545 
14546     case Builtin::BI__builtin_operator_delete:
14547       return HandleOperatorDeleteCall(Info, E);
14548 
14549     default:
14550       break;
14551     }
14552 
14553     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14554   }
14555 
14556   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14557 };
14558 } // end anonymous namespace
14559 
14560 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14561   // We cannot speculatively evaluate a delete expression.
14562   if (Info.SpeculativeEvaluationDepth)
14563     return false;
14564 
14565   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14566   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14567     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14568         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14569     return false;
14570   }
14571 
14572   const Expr *Arg = E->getArgument();
14573 
14574   LValue Pointer;
14575   if (!EvaluatePointer(Arg, Pointer, Info))
14576     return false;
14577   if (Pointer.Designator.Invalid)
14578     return false;
14579 
14580   // Deleting a null pointer has no effect.
14581   if (Pointer.isNullPointer()) {
14582     // This is the only case where we need to produce an extension warning:
14583     // the only other way we can succeed is if we find a dynamic allocation,
14584     // and we will have warned when we allocated it in that case.
14585     if (!Info.getLangOpts().CPlusPlus20)
14586       Info.CCEDiag(E, diag::note_constexpr_new);
14587     return true;
14588   }
14589 
14590   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14591       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14592   if (!Alloc)
14593     return false;
14594   QualType AllocType = Pointer.Base.getDynamicAllocType();
14595 
14596   // For the non-array case, the designator must be empty if the static type
14597   // does not have a virtual destructor.
14598   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14599       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14600     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14601         << Arg->getType()->getPointeeType() << AllocType;
14602     return false;
14603   }
14604 
14605   // For a class type with a virtual destructor, the selected operator delete
14606   // is the one looked up when building the destructor.
14607   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14608     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14609     if (VirtualDelete &&
14610         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14611       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14612           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14613       return false;
14614     }
14615   }
14616 
14617   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14618                          (*Alloc)->Value, AllocType))
14619     return false;
14620 
14621   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14622     // The element was already erased. This means the destructor call also
14623     // deleted the object.
14624     // FIXME: This probably results in undefined behavior before we get this
14625     // far, and should be diagnosed elsewhere first.
14626     Info.FFDiag(E, diag::note_constexpr_double_delete);
14627     return false;
14628   }
14629 
14630   return true;
14631 }
14632 
14633 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14634   assert(!E->isValueDependent());
14635   assert(E->isPRValue() && E->getType()->isVoidType());
14636   return VoidExprEvaluator(Info).Visit(E);
14637 }
14638 
14639 //===----------------------------------------------------------------------===//
14640 // Top level Expr::EvaluateAsRValue method.
14641 //===----------------------------------------------------------------------===//
14642 
14643 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14644   assert(!E->isValueDependent());
14645   // In C, function designators are not lvalues, but we evaluate them as if they
14646   // are.
14647   QualType T = E->getType();
14648   if (E->isGLValue() || T->isFunctionType()) {
14649     LValue LV;
14650     if (!EvaluateLValue(E, LV, Info))
14651       return false;
14652     LV.moveInto(Result);
14653   } else if (T->isVectorType()) {
14654     if (!EvaluateVector(E, Result, Info))
14655       return false;
14656   } else if (T->isIntegralOrEnumerationType()) {
14657     if (!IntExprEvaluator(Info, Result).Visit(E))
14658       return false;
14659   } else if (T->hasPointerRepresentation()) {
14660     LValue LV;
14661     if (!EvaluatePointer(E, LV, Info))
14662       return false;
14663     LV.moveInto(Result);
14664   } else if (T->isRealFloatingType()) {
14665     llvm::APFloat F(0.0);
14666     if (!EvaluateFloat(E, F, Info))
14667       return false;
14668     Result = APValue(F);
14669   } else if (T->isAnyComplexType()) {
14670     ComplexValue C;
14671     if (!EvaluateComplex(E, C, Info))
14672       return false;
14673     C.moveInto(Result);
14674   } else if (T->isFixedPointType()) {
14675     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14676   } else if (T->isMemberPointerType()) {
14677     MemberPtr P;
14678     if (!EvaluateMemberPointer(E, P, Info))
14679       return false;
14680     P.moveInto(Result);
14681     return true;
14682   } else if (T->isArrayType()) {
14683     LValue LV;
14684     APValue &Value =
14685         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14686     if (!EvaluateArray(E, LV, Value, Info))
14687       return false;
14688     Result = Value;
14689   } else if (T->isRecordType()) {
14690     LValue LV;
14691     APValue &Value =
14692         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14693     if (!EvaluateRecord(E, LV, Value, Info))
14694       return false;
14695     Result = Value;
14696   } else if (T->isVoidType()) {
14697     if (!Info.getLangOpts().CPlusPlus11)
14698       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14699         << E->getType();
14700     if (!EvaluateVoid(E, Info))
14701       return false;
14702   } else if (T->isAtomicType()) {
14703     QualType Unqual = T.getAtomicUnqualifiedType();
14704     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14705       LValue LV;
14706       APValue &Value = Info.CurrentCall->createTemporary(
14707           E, Unqual, ScopeKind::FullExpression, LV);
14708       if (!EvaluateAtomic(E, &LV, Value, Info))
14709         return false;
14710     } else {
14711       if (!EvaluateAtomic(E, nullptr, Result, Info))
14712         return false;
14713     }
14714   } else if (Info.getLangOpts().CPlusPlus11) {
14715     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14716     return false;
14717   } else {
14718     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14719     return false;
14720   }
14721 
14722   return true;
14723 }
14724 
14725 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14726 /// cases, the in-place evaluation is essential, since later initializers for
14727 /// an object can indirectly refer to subobjects which were initialized earlier.
14728 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14729                             const Expr *E, bool AllowNonLiteralTypes) {
14730   assert(!E->isValueDependent());
14731 
14732   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14733     return false;
14734 
14735   if (E->isPRValue()) {
14736     // Evaluate arrays and record types in-place, so that later initializers can
14737     // refer to earlier-initialized members of the object.
14738     QualType T = E->getType();
14739     if (T->isArrayType())
14740       return EvaluateArray(E, This, Result, Info);
14741     else if (T->isRecordType())
14742       return EvaluateRecord(E, This, Result, Info);
14743     else if (T->isAtomicType()) {
14744       QualType Unqual = T.getAtomicUnqualifiedType();
14745       if (Unqual->isArrayType() || Unqual->isRecordType())
14746         return EvaluateAtomic(E, &This, Result, Info);
14747     }
14748   }
14749 
14750   // For any other type, in-place evaluation is unimportant.
14751   return Evaluate(Result, Info, E);
14752 }
14753 
14754 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14755 /// lvalue-to-rvalue cast if it is an lvalue.
14756 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14757   assert(!E->isValueDependent());
14758   if (Info.EnableNewConstInterp) {
14759     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14760       return false;
14761   } else {
14762     if (E->getType().isNull())
14763       return false;
14764 
14765     if (!CheckLiteralType(Info, E))
14766       return false;
14767 
14768     if (!::Evaluate(Result, Info, E))
14769       return false;
14770 
14771     if (E->isGLValue()) {
14772       LValue LV;
14773       LV.setFrom(Info.Ctx, Result);
14774       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14775         return false;
14776     }
14777   }
14778 
14779   // Check this core constant expression is a constant expression.
14780   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14781                                  ConstantExprKind::Normal) &&
14782          CheckMemoryLeaks(Info);
14783 }
14784 
14785 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14786                                  const ASTContext &Ctx, bool &IsConst) {
14787   // Fast-path evaluations of integer literals, since we sometimes see files
14788   // containing vast quantities of these.
14789   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14790     Result.Val = APValue(APSInt(L->getValue(),
14791                                 L->getType()->isUnsignedIntegerType()));
14792     IsConst = true;
14793     return true;
14794   }
14795 
14796   // This case should be rare, but we need to check it before we check on
14797   // the type below.
14798   if (Exp->getType().isNull()) {
14799     IsConst = false;
14800     return true;
14801   }
14802 
14803   // FIXME: Evaluating values of large array and record types can cause
14804   // performance problems. Only do so in C++11 for now.
14805   if (Exp->isPRValue() &&
14806       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14807       !Ctx.getLangOpts().CPlusPlus11) {
14808     IsConst = false;
14809     return true;
14810   }
14811   return false;
14812 }
14813 
14814 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14815                                       Expr::SideEffectsKind SEK) {
14816   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14817          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14818 }
14819 
14820 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14821                              const ASTContext &Ctx, EvalInfo &Info) {
14822   assert(!E->isValueDependent());
14823   bool IsConst;
14824   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14825     return IsConst;
14826 
14827   return EvaluateAsRValue(Info, E, Result.Val);
14828 }
14829 
14830 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14831                           const ASTContext &Ctx,
14832                           Expr::SideEffectsKind AllowSideEffects,
14833                           EvalInfo &Info) {
14834   assert(!E->isValueDependent());
14835   if (!E->getType()->isIntegralOrEnumerationType())
14836     return false;
14837 
14838   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14839       !ExprResult.Val.isInt() ||
14840       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14841     return false;
14842 
14843   return true;
14844 }
14845 
14846 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14847                                  const ASTContext &Ctx,
14848                                  Expr::SideEffectsKind AllowSideEffects,
14849                                  EvalInfo &Info) {
14850   assert(!E->isValueDependent());
14851   if (!E->getType()->isFixedPointType())
14852     return false;
14853 
14854   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14855     return false;
14856 
14857   if (!ExprResult.Val.isFixedPoint() ||
14858       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14859     return false;
14860 
14861   return true;
14862 }
14863 
14864 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14865 /// any crazy technique (that has nothing to do with language standards) that
14866 /// we want to.  If this function returns true, it returns the folded constant
14867 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14868 /// will be applied to the result.
14869 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14870                             bool InConstantContext) const {
14871   assert(!isValueDependent() &&
14872          "Expression evaluator can't be called on a dependent expression.");
14873   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14874   Info.InConstantContext = InConstantContext;
14875   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14876 }
14877 
14878 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14879                                       bool InConstantContext) const {
14880   assert(!isValueDependent() &&
14881          "Expression evaluator can't be called on a dependent expression.");
14882   EvalResult Scratch;
14883   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14884          HandleConversionToBool(Scratch.Val, Result);
14885 }
14886 
14887 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14888                          SideEffectsKind AllowSideEffects,
14889                          bool InConstantContext) const {
14890   assert(!isValueDependent() &&
14891          "Expression evaluator can't be called on a dependent expression.");
14892   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14893   Info.InConstantContext = InConstantContext;
14894   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14895 }
14896 
14897 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14898                                 SideEffectsKind AllowSideEffects,
14899                                 bool InConstantContext) const {
14900   assert(!isValueDependent() &&
14901          "Expression evaluator can't be called on a dependent expression.");
14902   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14903   Info.InConstantContext = InConstantContext;
14904   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14905 }
14906 
14907 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14908                            SideEffectsKind AllowSideEffects,
14909                            bool InConstantContext) const {
14910   assert(!isValueDependent() &&
14911          "Expression evaluator can't be called on a dependent expression.");
14912 
14913   if (!getType()->isRealFloatingType())
14914     return false;
14915 
14916   EvalResult ExprResult;
14917   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14918       !ExprResult.Val.isFloat() ||
14919       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14920     return false;
14921 
14922   Result = ExprResult.Val.getFloat();
14923   return true;
14924 }
14925 
14926 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14927                             bool InConstantContext) const {
14928   assert(!isValueDependent() &&
14929          "Expression evaluator can't be called on a dependent expression.");
14930 
14931   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14932   Info.InConstantContext = InConstantContext;
14933   LValue LV;
14934   CheckedTemporaries CheckedTemps;
14935   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14936       Result.HasSideEffects ||
14937       !CheckLValueConstantExpression(Info, getExprLoc(),
14938                                      Ctx.getLValueReferenceType(getType()), LV,
14939                                      ConstantExprKind::Normal, CheckedTemps))
14940     return false;
14941 
14942   LV.moveInto(Result.Val);
14943   return true;
14944 }
14945 
14946 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14947                                 APValue DestroyedValue, QualType Type,
14948                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14949                                 bool IsConstantDestruction) {
14950   EvalInfo Info(Ctx, EStatus,
14951                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14952                                       : EvalInfo::EM_ConstantFold);
14953   Info.setEvaluatingDecl(Base, DestroyedValue,
14954                          EvalInfo::EvaluatingDeclKind::Dtor);
14955   Info.InConstantContext = IsConstantDestruction;
14956 
14957   LValue LVal;
14958   LVal.set(Base);
14959 
14960   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14961       EStatus.HasSideEffects)
14962     return false;
14963 
14964   if (!Info.discardCleanups())
14965     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14966 
14967   return true;
14968 }
14969 
14970 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14971                                   ConstantExprKind Kind) const {
14972   assert(!isValueDependent() &&
14973          "Expression evaluator can't be called on a dependent expression.");
14974 
14975   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14976   EvalInfo Info(Ctx, Result, EM);
14977   Info.InConstantContext = true;
14978 
14979   // The type of the object we're initializing is 'const T' for a class NTTP.
14980   QualType T = getType();
14981   if (Kind == ConstantExprKind::ClassTemplateArgument)
14982     T.addConst();
14983 
14984   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14985   // represent the result of the evaluation. CheckConstantExpression ensures
14986   // this doesn't escape.
14987   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14988   APValue::LValueBase Base(&BaseMTE);
14989 
14990   Info.setEvaluatingDecl(Base, Result.Val);
14991   LValue LVal;
14992   LVal.set(Base);
14993 
14994   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14995     return false;
14996 
14997   if (!Info.discardCleanups())
14998     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14999 
15000   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15001                                Result.Val, Kind))
15002     return false;
15003   if (!CheckMemoryLeaks(Info))
15004     return false;
15005 
15006   // If this is a class template argument, it's required to have constant
15007   // destruction too.
15008   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15009       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15010                             true) ||
15011        Result.HasSideEffects)) {
15012     // FIXME: Prefix a note to indicate that the problem is lack of constant
15013     // destruction.
15014     return false;
15015   }
15016 
15017   return true;
15018 }
15019 
15020 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15021                                  const VarDecl *VD,
15022                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15023   assert(!isValueDependent() &&
15024          "Expression evaluator can't be called on a dependent expression.");
15025 
15026   // FIXME: Evaluating initializers for large array and record types can cause
15027   // performance problems. Only do so in C++11 for now.
15028   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15029       !Ctx.getLangOpts().CPlusPlus11)
15030     return false;
15031 
15032   Expr::EvalStatus EStatus;
15033   EStatus.Diag = &Notes;
15034 
15035   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
15036                                       ? EvalInfo::EM_ConstantExpression
15037                                       : EvalInfo::EM_ConstantFold);
15038   Info.setEvaluatingDecl(VD, Value);
15039   Info.InConstantContext = true;
15040 
15041   SourceLocation DeclLoc = VD->getLocation();
15042   QualType DeclTy = VD->getType();
15043 
15044   if (Info.EnableNewConstInterp) {
15045     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15046     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15047       return false;
15048   } else {
15049     LValue LVal;
15050     LVal.set(VD);
15051 
15052     if (!EvaluateInPlace(Value, Info, LVal, this,
15053                          /*AllowNonLiteralTypes=*/true) ||
15054         EStatus.HasSideEffects)
15055       return false;
15056 
15057     // At this point, any lifetime-extended temporaries are completely
15058     // initialized.
15059     Info.performLifetimeExtension();
15060 
15061     if (!Info.discardCleanups())
15062       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15063   }
15064   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15065                                  ConstantExprKind::Normal) &&
15066          CheckMemoryLeaks(Info);
15067 }
15068 
15069 bool VarDecl::evaluateDestruction(
15070     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15071   Expr::EvalStatus EStatus;
15072   EStatus.Diag = &Notes;
15073 
15074   // Only treat the destruction as constant destruction if we formally have
15075   // constant initialization (or are usable in a constant expression).
15076   bool IsConstantDestruction = hasConstantInitialization();
15077 
15078   // Make a copy of the value for the destructor to mutate, if we know it.
15079   // Otherwise, treat the value as default-initialized; if the destructor works
15080   // anyway, then the destruction is constant (and must be essentially empty).
15081   APValue DestroyedValue;
15082   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15083     DestroyedValue = *getEvaluatedValue();
15084   else if (!getDefaultInitValue(getType(), DestroyedValue))
15085     return false;
15086 
15087   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15088                            getType(), getLocation(), EStatus,
15089                            IsConstantDestruction) ||
15090       EStatus.HasSideEffects)
15091     return false;
15092 
15093   ensureEvaluatedStmt()->HasConstantDestruction = true;
15094   return true;
15095 }
15096 
15097 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15098 /// constant folded, but discard the result.
15099 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15100   assert(!isValueDependent() &&
15101          "Expression evaluator can't be called on a dependent expression.");
15102 
15103   EvalResult Result;
15104   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15105          !hasUnacceptableSideEffect(Result, SEK);
15106 }
15107 
15108 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15109                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15110   assert(!isValueDependent() &&
15111          "Expression evaluator can't be called on a dependent expression.");
15112 
15113   EvalResult EVResult;
15114   EVResult.Diag = Diag;
15115   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15116   Info.InConstantContext = true;
15117 
15118   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15119   (void)Result;
15120   assert(Result && "Could not evaluate expression");
15121   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15122 
15123   return EVResult.Val.getInt();
15124 }
15125 
15126 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15127     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15128   assert(!isValueDependent() &&
15129          "Expression evaluator can't be called on a dependent expression.");
15130 
15131   EvalResult EVResult;
15132   EVResult.Diag = Diag;
15133   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15134   Info.InConstantContext = true;
15135   Info.CheckingForUndefinedBehavior = true;
15136 
15137   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15138   (void)Result;
15139   assert(Result && "Could not evaluate expression");
15140   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15141 
15142   return EVResult.Val.getInt();
15143 }
15144 
15145 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15146   assert(!isValueDependent() &&
15147          "Expression evaluator can't be called on a dependent expression.");
15148 
15149   bool IsConst;
15150   EvalResult EVResult;
15151   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15152     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15153     Info.CheckingForUndefinedBehavior = true;
15154     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15155   }
15156 }
15157 
15158 bool Expr::EvalResult::isGlobalLValue() const {
15159   assert(Val.isLValue());
15160   return IsGlobalLValue(Val.getLValueBase());
15161 }
15162 
15163 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15164 /// an integer constant expression.
15165 
15166 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15167 /// comma, etc
15168 
15169 // CheckICE - This function does the fundamental ICE checking: the returned
15170 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15171 // and a (possibly null) SourceLocation indicating the location of the problem.
15172 //
15173 // Note that to reduce code duplication, this helper does no evaluation
15174 // itself; the caller checks whether the expression is evaluatable, and
15175 // in the rare cases where CheckICE actually cares about the evaluated
15176 // value, it calls into Evaluate.
15177 
15178 namespace {
15179 
15180 enum ICEKind {
15181   /// This expression is an ICE.
15182   IK_ICE,
15183   /// This expression is not an ICE, but if it isn't evaluated, it's
15184   /// a legal subexpression for an ICE. This return value is used to handle
15185   /// the comma operator in C99 mode, and non-constant subexpressions.
15186   IK_ICEIfUnevaluated,
15187   /// This expression is not an ICE, and is not a legal subexpression for one.
15188   IK_NotICE
15189 };
15190 
15191 struct ICEDiag {
15192   ICEKind Kind;
15193   SourceLocation Loc;
15194 
15195   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15196 };
15197 
15198 }
15199 
15200 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15201 
15202 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15203 
15204 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15205   Expr::EvalResult EVResult;
15206   Expr::EvalStatus Status;
15207   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15208 
15209   Info.InConstantContext = true;
15210   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15211       !EVResult.Val.isInt())
15212     return ICEDiag(IK_NotICE, E->getBeginLoc());
15213 
15214   return NoDiag();
15215 }
15216 
15217 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15218   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15219   if (!E->getType()->isIntegralOrEnumerationType())
15220     return ICEDiag(IK_NotICE, E->getBeginLoc());
15221 
15222   switch (E->getStmtClass()) {
15223 #define ABSTRACT_STMT(Node)
15224 #define STMT(Node, Base) case Expr::Node##Class:
15225 #define EXPR(Node, Base)
15226 #include "clang/AST/StmtNodes.inc"
15227   case Expr::PredefinedExprClass:
15228   case Expr::FloatingLiteralClass:
15229   case Expr::ImaginaryLiteralClass:
15230   case Expr::StringLiteralClass:
15231   case Expr::ArraySubscriptExprClass:
15232   case Expr::MatrixSubscriptExprClass:
15233   case Expr::OMPArraySectionExprClass:
15234   case Expr::OMPArrayShapingExprClass:
15235   case Expr::OMPIteratorExprClass:
15236   case Expr::MemberExprClass:
15237   case Expr::CompoundAssignOperatorClass:
15238   case Expr::CompoundLiteralExprClass:
15239   case Expr::ExtVectorElementExprClass:
15240   case Expr::DesignatedInitExprClass:
15241   case Expr::ArrayInitLoopExprClass:
15242   case Expr::ArrayInitIndexExprClass:
15243   case Expr::NoInitExprClass:
15244   case Expr::DesignatedInitUpdateExprClass:
15245   case Expr::ImplicitValueInitExprClass:
15246   case Expr::ParenListExprClass:
15247   case Expr::VAArgExprClass:
15248   case Expr::AddrLabelExprClass:
15249   case Expr::StmtExprClass:
15250   case Expr::CXXMemberCallExprClass:
15251   case Expr::CUDAKernelCallExprClass:
15252   case Expr::CXXAddrspaceCastExprClass:
15253   case Expr::CXXDynamicCastExprClass:
15254   case Expr::CXXTypeidExprClass:
15255   case Expr::CXXUuidofExprClass:
15256   case Expr::MSPropertyRefExprClass:
15257   case Expr::MSPropertySubscriptExprClass:
15258   case Expr::CXXNullPtrLiteralExprClass:
15259   case Expr::UserDefinedLiteralClass:
15260   case Expr::CXXThisExprClass:
15261   case Expr::CXXThrowExprClass:
15262   case Expr::CXXNewExprClass:
15263   case Expr::CXXDeleteExprClass:
15264   case Expr::CXXPseudoDestructorExprClass:
15265   case Expr::UnresolvedLookupExprClass:
15266   case Expr::TypoExprClass:
15267   case Expr::RecoveryExprClass:
15268   case Expr::DependentScopeDeclRefExprClass:
15269   case Expr::CXXConstructExprClass:
15270   case Expr::CXXInheritedCtorInitExprClass:
15271   case Expr::CXXStdInitializerListExprClass:
15272   case Expr::CXXBindTemporaryExprClass:
15273   case Expr::ExprWithCleanupsClass:
15274   case Expr::CXXTemporaryObjectExprClass:
15275   case Expr::CXXUnresolvedConstructExprClass:
15276   case Expr::CXXDependentScopeMemberExprClass:
15277   case Expr::UnresolvedMemberExprClass:
15278   case Expr::ObjCStringLiteralClass:
15279   case Expr::ObjCBoxedExprClass:
15280   case Expr::ObjCArrayLiteralClass:
15281   case Expr::ObjCDictionaryLiteralClass:
15282   case Expr::ObjCEncodeExprClass:
15283   case Expr::ObjCMessageExprClass:
15284   case Expr::ObjCSelectorExprClass:
15285   case Expr::ObjCProtocolExprClass:
15286   case Expr::ObjCIvarRefExprClass:
15287   case Expr::ObjCPropertyRefExprClass:
15288   case Expr::ObjCSubscriptRefExprClass:
15289   case Expr::ObjCIsaExprClass:
15290   case Expr::ObjCAvailabilityCheckExprClass:
15291   case Expr::ShuffleVectorExprClass:
15292   case Expr::ConvertVectorExprClass:
15293   case Expr::BlockExprClass:
15294   case Expr::NoStmtClass:
15295   case Expr::OpaqueValueExprClass:
15296   case Expr::PackExpansionExprClass:
15297   case Expr::SubstNonTypeTemplateParmPackExprClass:
15298   case Expr::FunctionParmPackExprClass:
15299   case Expr::AsTypeExprClass:
15300   case Expr::ObjCIndirectCopyRestoreExprClass:
15301   case Expr::MaterializeTemporaryExprClass:
15302   case Expr::PseudoObjectExprClass:
15303   case Expr::AtomicExprClass:
15304   case Expr::LambdaExprClass:
15305   case Expr::CXXFoldExprClass:
15306   case Expr::CoawaitExprClass:
15307   case Expr::DependentCoawaitExprClass:
15308   case Expr::CoyieldExprClass:
15309   case Expr::SYCLUniqueStableNameExprClass:
15310     return ICEDiag(IK_NotICE, E->getBeginLoc());
15311 
15312   case Expr::InitListExprClass: {
15313     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15314     // form "T x = { a };" is equivalent to "T x = a;".
15315     // Unless we're initializing a reference, T is a scalar as it is known to be
15316     // of integral or enumeration type.
15317     if (E->isPRValue())
15318       if (cast<InitListExpr>(E)->getNumInits() == 1)
15319         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15320     return ICEDiag(IK_NotICE, E->getBeginLoc());
15321   }
15322 
15323   case Expr::SizeOfPackExprClass:
15324   case Expr::GNUNullExprClass:
15325   case Expr::SourceLocExprClass:
15326     return NoDiag();
15327 
15328   case Expr::SubstNonTypeTemplateParmExprClass:
15329     return
15330       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15331 
15332   case Expr::ConstantExprClass:
15333     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15334 
15335   case Expr::ParenExprClass:
15336     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15337   case Expr::GenericSelectionExprClass:
15338     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15339   case Expr::IntegerLiteralClass:
15340   case Expr::FixedPointLiteralClass:
15341   case Expr::CharacterLiteralClass:
15342   case Expr::ObjCBoolLiteralExprClass:
15343   case Expr::CXXBoolLiteralExprClass:
15344   case Expr::CXXScalarValueInitExprClass:
15345   case Expr::TypeTraitExprClass:
15346   case Expr::ConceptSpecializationExprClass:
15347   case Expr::RequiresExprClass:
15348   case Expr::ArrayTypeTraitExprClass:
15349   case Expr::ExpressionTraitExprClass:
15350   case Expr::CXXNoexceptExprClass:
15351     return NoDiag();
15352   case Expr::CallExprClass:
15353   case Expr::CXXOperatorCallExprClass: {
15354     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15355     // constant expressions, but they can never be ICEs because an ICE cannot
15356     // contain an operand of (pointer to) function type.
15357     const CallExpr *CE = cast<CallExpr>(E);
15358     if (CE->getBuiltinCallee())
15359       return CheckEvalInICE(E, Ctx);
15360     return ICEDiag(IK_NotICE, E->getBeginLoc());
15361   }
15362   case Expr::CXXRewrittenBinaryOperatorClass:
15363     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15364                     Ctx);
15365   case Expr::DeclRefExprClass: {
15366     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15367     if (isa<EnumConstantDecl>(D))
15368       return NoDiag();
15369 
15370     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15371     // integer variables in constant expressions:
15372     //
15373     // C++ 7.1.5.1p2
15374     //   A variable of non-volatile const-qualified integral or enumeration
15375     //   type initialized by an ICE can be used in ICEs.
15376     //
15377     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15378     // that mode, use of reference variables should not be allowed.
15379     const VarDecl *VD = dyn_cast<VarDecl>(D);
15380     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15381         !VD->getType()->isReferenceType())
15382       return NoDiag();
15383 
15384     return ICEDiag(IK_NotICE, E->getBeginLoc());
15385   }
15386   case Expr::UnaryOperatorClass: {
15387     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15388     switch (Exp->getOpcode()) {
15389     case UO_PostInc:
15390     case UO_PostDec:
15391     case UO_PreInc:
15392     case UO_PreDec:
15393     case UO_AddrOf:
15394     case UO_Deref:
15395     case UO_Coawait:
15396       // C99 6.6/3 allows increment and decrement within unevaluated
15397       // subexpressions of constant expressions, but they can never be ICEs
15398       // because an ICE cannot contain an lvalue operand.
15399       return ICEDiag(IK_NotICE, E->getBeginLoc());
15400     case UO_Extension:
15401     case UO_LNot:
15402     case UO_Plus:
15403     case UO_Minus:
15404     case UO_Not:
15405     case UO_Real:
15406     case UO_Imag:
15407       return CheckICE(Exp->getSubExpr(), Ctx);
15408     }
15409     llvm_unreachable("invalid unary operator class");
15410   }
15411   case Expr::OffsetOfExprClass: {
15412     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15413     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15414     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15415     // compliance: we should warn earlier for offsetof expressions with
15416     // array subscripts that aren't ICEs, and if the array subscripts
15417     // are ICEs, the value of the offsetof must be an integer constant.
15418     return CheckEvalInICE(E, Ctx);
15419   }
15420   case Expr::UnaryExprOrTypeTraitExprClass: {
15421     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15422     if ((Exp->getKind() ==  UETT_SizeOf) &&
15423         Exp->getTypeOfArgument()->isVariableArrayType())
15424       return ICEDiag(IK_NotICE, E->getBeginLoc());
15425     return NoDiag();
15426   }
15427   case Expr::BinaryOperatorClass: {
15428     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15429     switch (Exp->getOpcode()) {
15430     case BO_PtrMemD:
15431     case BO_PtrMemI:
15432     case BO_Assign:
15433     case BO_MulAssign:
15434     case BO_DivAssign:
15435     case BO_RemAssign:
15436     case BO_AddAssign:
15437     case BO_SubAssign:
15438     case BO_ShlAssign:
15439     case BO_ShrAssign:
15440     case BO_AndAssign:
15441     case BO_XorAssign:
15442     case BO_OrAssign:
15443       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15444       // constant expressions, but they can never be ICEs because an ICE cannot
15445       // contain an lvalue operand.
15446       return ICEDiag(IK_NotICE, E->getBeginLoc());
15447 
15448     case BO_Mul:
15449     case BO_Div:
15450     case BO_Rem:
15451     case BO_Add:
15452     case BO_Sub:
15453     case BO_Shl:
15454     case BO_Shr:
15455     case BO_LT:
15456     case BO_GT:
15457     case BO_LE:
15458     case BO_GE:
15459     case BO_EQ:
15460     case BO_NE:
15461     case BO_And:
15462     case BO_Xor:
15463     case BO_Or:
15464     case BO_Comma:
15465     case BO_Cmp: {
15466       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15467       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15468       if (Exp->getOpcode() == BO_Div ||
15469           Exp->getOpcode() == BO_Rem) {
15470         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15471         // we don't evaluate one.
15472         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15473           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15474           if (REval == 0)
15475             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15476           if (REval.isSigned() && REval.isAllOnes()) {
15477             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15478             if (LEval.isMinSignedValue())
15479               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15480           }
15481         }
15482       }
15483       if (Exp->getOpcode() == BO_Comma) {
15484         if (Ctx.getLangOpts().C99) {
15485           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15486           // if it isn't evaluated.
15487           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15488             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15489         } else {
15490           // In both C89 and C++, commas in ICEs are illegal.
15491           return ICEDiag(IK_NotICE, E->getBeginLoc());
15492         }
15493       }
15494       return Worst(LHSResult, RHSResult);
15495     }
15496     case BO_LAnd:
15497     case BO_LOr: {
15498       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15499       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15500       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15501         // Rare case where the RHS has a comma "side-effect"; we need
15502         // to actually check the condition to see whether the side
15503         // with the comma is evaluated.
15504         if ((Exp->getOpcode() == BO_LAnd) !=
15505             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15506           return RHSResult;
15507         return NoDiag();
15508       }
15509 
15510       return Worst(LHSResult, RHSResult);
15511     }
15512     }
15513     llvm_unreachable("invalid binary operator kind");
15514   }
15515   case Expr::ImplicitCastExprClass:
15516   case Expr::CStyleCastExprClass:
15517   case Expr::CXXFunctionalCastExprClass:
15518   case Expr::CXXStaticCastExprClass:
15519   case Expr::CXXReinterpretCastExprClass:
15520   case Expr::CXXConstCastExprClass:
15521   case Expr::ObjCBridgedCastExprClass: {
15522     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15523     if (isa<ExplicitCastExpr>(E)) {
15524       if (const FloatingLiteral *FL
15525             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15526         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15527         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15528         APSInt IgnoredVal(DestWidth, !DestSigned);
15529         bool Ignored;
15530         // If the value does not fit in the destination type, the behavior is
15531         // undefined, so we are not required to treat it as a constant
15532         // expression.
15533         if (FL->getValue().convertToInteger(IgnoredVal,
15534                                             llvm::APFloat::rmTowardZero,
15535                                             &Ignored) & APFloat::opInvalidOp)
15536           return ICEDiag(IK_NotICE, E->getBeginLoc());
15537         return NoDiag();
15538       }
15539     }
15540     switch (cast<CastExpr>(E)->getCastKind()) {
15541     case CK_LValueToRValue:
15542     case CK_AtomicToNonAtomic:
15543     case CK_NonAtomicToAtomic:
15544     case CK_NoOp:
15545     case CK_IntegralToBoolean:
15546     case CK_IntegralCast:
15547       return CheckICE(SubExpr, Ctx);
15548     default:
15549       return ICEDiag(IK_NotICE, E->getBeginLoc());
15550     }
15551   }
15552   case Expr::BinaryConditionalOperatorClass: {
15553     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15554     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15555     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15556     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15557     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15558     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15559     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15560         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15561     return FalseResult;
15562   }
15563   case Expr::ConditionalOperatorClass: {
15564     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15565     // If the condition (ignoring parens) is a __builtin_constant_p call,
15566     // then only the true side is actually considered in an integer constant
15567     // expression, and it is fully evaluated.  This is an important GNU
15568     // extension.  See GCC PR38377 for discussion.
15569     if (const CallExpr *CallCE
15570         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15571       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15572         return CheckEvalInICE(E, Ctx);
15573     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15574     if (CondResult.Kind == IK_NotICE)
15575       return CondResult;
15576 
15577     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15578     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15579 
15580     if (TrueResult.Kind == IK_NotICE)
15581       return TrueResult;
15582     if (FalseResult.Kind == IK_NotICE)
15583       return FalseResult;
15584     if (CondResult.Kind == IK_ICEIfUnevaluated)
15585       return CondResult;
15586     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15587       return NoDiag();
15588     // Rare case where the diagnostics depend on which side is evaluated
15589     // Note that if we get here, CondResult is 0, and at least one of
15590     // TrueResult and FalseResult is non-zero.
15591     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15592       return FalseResult;
15593     return TrueResult;
15594   }
15595   case Expr::CXXDefaultArgExprClass:
15596     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15597   case Expr::CXXDefaultInitExprClass:
15598     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15599   case Expr::ChooseExprClass: {
15600     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15601   }
15602   case Expr::BuiltinBitCastExprClass: {
15603     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15604       return ICEDiag(IK_NotICE, E->getBeginLoc());
15605     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15606   }
15607   }
15608 
15609   llvm_unreachable("Invalid StmtClass!");
15610 }
15611 
15612 /// Evaluate an expression as a C++11 integral constant expression.
15613 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15614                                                     const Expr *E,
15615                                                     llvm::APSInt *Value,
15616                                                     SourceLocation *Loc) {
15617   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15618     if (Loc) *Loc = E->getExprLoc();
15619     return false;
15620   }
15621 
15622   APValue Result;
15623   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15624     return false;
15625 
15626   if (!Result.isInt()) {
15627     if (Loc) *Loc = E->getExprLoc();
15628     return false;
15629   }
15630 
15631   if (Value) *Value = Result.getInt();
15632   return true;
15633 }
15634 
15635 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15636                                  SourceLocation *Loc) const {
15637   assert(!isValueDependent() &&
15638          "Expression evaluator can't be called on a dependent expression.");
15639 
15640   if (Ctx.getLangOpts().CPlusPlus11)
15641     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15642 
15643   ICEDiag D = CheckICE(this, Ctx);
15644   if (D.Kind != IK_ICE) {
15645     if (Loc) *Loc = D.Loc;
15646     return false;
15647   }
15648   return true;
15649 }
15650 
15651 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15652                                                     SourceLocation *Loc,
15653                                                     bool isEvaluated) const {
15654   if (isValueDependent()) {
15655     // Expression evaluator can't succeed on a dependent expression.
15656     return None;
15657   }
15658 
15659   APSInt Value;
15660 
15661   if (Ctx.getLangOpts().CPlusPlus11) {
15662     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15663       return Value;
15664     return None;
15665   }
15666 
15667   if (!isIntegerConstantExpr(Ctx, Loc))
15668     return None;
15669 
15670   // The only possible side-effects here are due to UB discovered in the
15671   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15672   // required to treat the expression as an ICE, so we produce the folded
15673   // value.
15674   EvalResult ExprResult;
15675   Expr::EvalStatus Status;
15676   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15677   Info.InConstantContext = true;
15678 
15679   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15680     llvm_unreachable("ICE cannot be evaluated!");
15681 
15682   return ExprResult.Val.getInt();
15683 }
15684 
15685 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15686   assert(!isValueDependent() &&
15687          "Expression evaluator can't be called on a dependent expression.");
15688 
15689   return CheckICE(this, Ctx).Kind == IK_ICE;
15690 }
15691 
15692 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15693                                SourceLocation *Loc) const {
15694   assert(!isValueDependent() &&
15695          "Expression evaluator can't be called on a dependent expression.");
15696 
15697   // We support this checking in C++98 mode in order to diagnose compatibility
15698   // issues.
15699   assert(Ctx.getLangOpts().CPlusPlus);
15700 
15701   // Build evaluation settings.
15702   Expr::EvalStatus Status;
15703   SmallVector<PartialDiagnosticAt, 8> Diags;
15704   Status.Diag = &Diags;
15705   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15706 
15707   APValue Scratch;
15708   bool IsConstExpr =
15709       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15710       // FIXME: We don't produce a diagnostic for this, but the callers that
15711       // call us on arbitrary full-expressions should generally not care.
15712       Info.discardCleanups() && !Status.HasSideEffects;
15713 
15714   if (!Diags.empty()) {
15715     IsConstExpr = false;
15716     if (Loc) *Loc = Diags[0].first;
15717   } else if (!IsConstExpr) {
15718     // FIXME: This shouldn't happen.
15719     if (Loc) *Loc = getExprLoc();
15720   }
15721 
15722   return IsConstExpr;
15723 }
15724 
15725 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15726                                     const FunctionDecl *Callee,
15727                                     ArrayRef<const Expr*> Args,
15728                                     const Expr *This) const {
15729   assert(!isValueDependent() &&
15730          "Expression evaluator can't be called on a dependent expression.");
15731 
15732   Expr::EvalStatus Status;
15733   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15734   Info.InConstantContext = true;
15735 
15736   LValue ThisVal;
15737   const LValue *ThisPtr = nullptr;
15738   if (This) {
15739 #ifndef NDEBUG
15740     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15741     assert(MD && "Don't provide `this` for non-methods.");
15742     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15743 #endif
15744     if (!This->isValueDependent() &&
15745         EvaluateObjectArgument(Info, This, ThisVal) &&
15746         !Info.EvalStatus.HasSideEffects)
15747       ThisPtr = &ThisVal;
15748 
15749     // Ignore any side-effects from a failed evaluation. This is safe because
15750     // they can't interfere with any other argument evaluation.
15751     Info.EvalStatus.HasSideEffects = false;
15752   }
15753 
15754   CallRef Call = Info.CurrentCall->createCall(Callee);
15755   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15756        I != E; ++I) {
15757     unsigned Idx = I - Args.begin();
15758     if (Idx >= Callee->getNumParams())
15759       break;
15760     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15761     if ((*I)->isValueDependent() ||
15762         !EvaluateCallArg(PVD, *I, Call, Info) ||
15763         Info.EvalStatus.HasSideEffects) {
15764       // If evaluation fails, throw away the argument entirely.
15765       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15766         *Slot = APValue();
15767     }
15768 
15769     // Ignore any side-effects from a failed evaluation. This is safe because
15770     // they can't interfere with any other argument evaluation.
15771     Info.EvalStatus.HasSideEffects = false;
15772   }
15773 
15774   // Parameter cleanups happen in the caller and are not part of this
15775   // evaluation.
15776   Info.discardCleanups();
15777   Info.EvalStatus.HasSideEffects = false;
15778 
15779   // Build fake call to Callee.
15780   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15781   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15782   FullExpressionRAII Scope(Info);
15783   return Evaluate(Value, Info, this) && Scope.destroy() &&
15784          !Info.EvalStatus.HasSideEffects;
15785 }
15786 
15787 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15788                                    SmallVectorImpl<
15789                                      PartialDiagnosticAt> &Diags) {
15790   // FIXME: It would be useful to check constexpr function templates, but at the
15791   // moment the constant expression evaluator cannot cope with the non-rigorous
15792   // ASTs which we build for dependent expressions.
15793   if (FD->isDependentContext())
15794     return true;
15795 
15796   Expr::EvalStatus Status;
15797   Status.Diag = &Diags;
15798 
15799   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15800   Info.InConstantContext = true;
15801   Info.CheckingPotentialConstantExpression = true;
15802 
15803   // The constexpr VM attempts to compile all methods to bytecode here.
15804   if (Info.EnableNewConstInterp) {
15805     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15806     return Diags.empty();
15807   }
15808 
15809   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15810   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15811 
15812   // Fabricate an arbitrary expression on the stack and pretend that it
15813   // is a temporary being used as the 'this' pointer.
15814   LValue This;
15815   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15816   This.set({&VIE, Info.CurrentCall->Index});
15817 
15818   ArrayRef<const Expr*> Args;
15819 
15820   APValue Scratch;
15821   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15822     // Evaluate the call as a constant initializer, to allow the construction
15823     // of objects of non-literal types.
15824     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15825     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15826   } else {
15827     SourceLocation Loc = FD->getLocation();
15828     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15829                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15830   }
15831 
15832   return Diags.empty();
15833 }
15834 
15835 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15836                                               const FunctionDecl *FD,
15837                                               SmallVectorImpl<
15838                                                 PartialDiagnosticAt> &Diags) {
15839   assert(!E->isValueDependent() &&
15840          "Expression evaluator can't be called on a dependent expression.");
15841 
15842   Expr::EvalStatus Status;
15843   Status.Diag = &Diags;
15844 
15845   EvalInfo Info(FD->getASTContext(), Status,
15846                 EvalInfo::EM_ConstantExpressionUnevaluated);
15847   Info.InConstantContext = true;
15848   Info.CheckingPotentialConstantExpression = true;
15849 
15850   // Fabricate a call stack frame to give the arguments a plausible cover story.
15851   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15852 
15853   APValue ResultScratch;
15854   Evaluate(ResultScratch, Info, E);
15855   return Diags.empty();
15856 }
15857 
15858 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15859                                  unsigned Type) const {
15860   if (!getType()->isPointerType())
15861     return false;
15862 
15863   Expr::EvalStatus Status;
15864   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15865   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15866 }
15867 
15868 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15869                                   EvalInfo &Info) {
15870   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15871     return false;
15872 
15873   LValue String;
15874 
15875   if (!EvaluatePointer(E, String, Info))
15876     return false;
15877 
15878   QualType CharTy = E->getType()->getPointeeType();
15879 
15880   // Fast path: if it's a string literal, search the string value.
15881   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15882           String.getLValueBase().dyn_cast<const Expr *>())) {
15883     StringRef Str = S->getBytes();
15884     int64_t Off = String.Offset.getQuantity();
15885     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15886         S->getCharByteWidth() == 1 &&
15887         // FIXME: Add fast-path for wchar_t too.
15888         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15889       Str = Str.substr(Off);
15890 
15891       StringRef::size_type Pos = Str.find(0);
15892       if (Pos != StringRef::npos)
15893         Str = Str.substr(0, Pos);
15894 
15895       Result = Str.size();
15896       return true;
15897     }
15898 
15899     // Fall through to slow path.
15900   }
15901 
15902   // Slow path: scan the bytes of the string looking for the terminating 0.
15903   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15904     APValue Char;
15905     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15906         !Char.isInt())
15907       return false;
15908     if (!Char.getInt()) {
15909       Result = Strlen;
15910       return true;
15911     }
15912     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15913       return false;
15914   }
15915 }
15916 
15917 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15918   Expr::EvalStatus Status;
15919   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15920   return EvaluateBuiltinStrLen(this, Result, Info);
15921 }
15922